1 /* SPDX-License-Identifier: LGPL-2.1-only */
2 /*
3  * lib/cache.c		Caching Module
4  *
5  *	This library is free software; you can redistribute it and/or
6  *	modify it under the terms of the GNU Lesser General Public
7  *	License as published by the Free Software Foundation version 2.1
8  *	of the License.
9  *
10  * Copyright (c) 2003-2012 Thomas Graf <tgraf@suug.ch>
11  */
12 
13 /**
14  * @ingroup cache_mngt
15  * @defgroup cache Cache
16  *
17  * @code
18  *   Cache Management             |    | Type Specific Cache Operations
19  *
20  *                                |    | +----------------+ +------------+
21  *                                       | request update | | msg_parser |
22  *                                |    | +----------------+ +------------+
23  *                                     +- - - - -^- - - - - - - -^- -|- - - -
24  *    nl_cache_update:            |              |               |   |
25  *          1) --------- co_request_update ------+               |   |
26  *                                |                              |   |
27  *          2) destroy old cache     +----------- pp_cb ---------|---+
28  *                                |  |                           |
29  *          3) ---------- nl_recvmsgs ----------+   +- cb_valid -+
30  *             +--------------+   |  |          |   |
31  *             | nl_cache_add |<-----+   + - - -v- -|- - - - - - - - - - -
32  *             +--------------+   |      | +-------------+
33  *                                         | nl_recvmsgs |
34  *                                |      | +-----|-^-----+
35  *                                           +---v-|---+
36  *                                |      |   | nl_recv |
37  *                                           +---------+
38  *                                |      |                 Core Netlink
39  * @endcode
40  *
41  * Related sections in the development guide:
42  * - @core_doc{core_cache, Caching System}
43  *
44  * @{
45  *
46  * Header
47  * ------
48  * ~~~~{.c}
49  * #include <netlink/cache.h>
50  * ~~~~
51  */
52 
53 #include <netlink-private/netlink.h>
54 #include <netlink/netlink.h>
55 #include <netlink/cache.h>
56 #include <netlink/object.h>
57 #include <netlink/hashtable.h>
58 #include <netlink/utils.h>
59 
60 /**
61  * @name Access Functions
62  * @{
63  */
64 
65 /**
66  * Return the number of items in the cache
67  * @arg cache		cache handle
68  */
nl_cache_nitems(struct nl_cache * cache)69 int nl_cache_nitems(struct nl_cache *cache)
70 {
71 	return cache->c_nitems;
72 }
73 
74 /**
75  * Return the number of items matching a filter in the cache
76  * @arg cache		Cache object.
77  * @arg filter		Filter object.
78  */
nl_cache_nitems_filter(struct nl_cache * cache,struct nl_object * filter)79 int nl_cache_nitems_filter(struct nl_cache *cache, struct nl_object *filter)
80 {
81 	struct nl_object *obj;
82 	int nitems = 0;
83 
84 	if (cache->c_ops == NULL)
85 		BUG();
86 
87 	nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
88 		if (filter && !nl_object_match_filter(obj, filter))
89 			continue;
90 
91 		nitems++;
92 	}
93 
94 	return nitems;
95 }
96 
97 /**
98  * Returns \b true if the cache is empty.
99  * @arg cache		Cache to check
100  * @return \a true if the cache is empty, otherwise \b false is returned.
101  */
nl_cache_is_empty(struct nl_cache * cache)102 int nl_cache_is_empty(struct nl_cache *cache)
103 {
104 	return nl_list_empty(&cache->c_items);
105 }
106 
107 /**
108  * Return the operations set of the cache
109  * @arg cache		cache handle
110  */
nl_cache_get_ops(struct nl_cache * cache)111 struct nl_cache_ops *nl_cache_get_ops(struct nl_cache *cache)
112 {
113 	return cache->c_ops;
114 }
115 
116 /**
117  * Return the first element in the cache
118  * @arg cache		cache handle
119  */
nl_cache_get_first(struct nl_cache * cache)120 struct nl_object *nl_cache_get_first(struct nl_cache *cache)
121 {
122 	if (nl_list_empty(&cache->c_items))
123 		return NULL;
124 
125 	return nl_list_entry(cache->c_items.next,
126 			     struct nl_object, ce_list);
127 }
128 
129 /**
130  * Return the last element in the cache
131  * @arg cache		cache handle
132  */
nl_cache_get_last(struct nl_cache * cache)133 struct nl_object *nl_cache_get_last(struct nl_cache *cache)
134 {
135 	if (nl_list_empty(&cache->c_items))
136 		return NULL;
137 
138 	return nl_list_entry(cache->c_items.prev,
139 			     struct nl_object, ce_list);
140 }
141 
142 /**
143  * Return the next element in the cache
144  * @arg obj		current object
145  */
nl_cache_get_next(struct nl_object * obj)146 struct nl_object *nl_cache_get_next(struct nl_object *obj)
147 {
148 	if (nl_list_at_tail(obj, &obj->ce_cache->c_items, ce_list))
149 		return NULL;
150 	else
151 		return nl_list_entry(obj->ce_list.next,
152 				     struct nl_object, ce_list);
153 }
154 
155 /**
156  * Return the previous element in the cache
157  * @arg obj		current object
158  */
nl_cache_get_prev(struct nl_object * obj)159 struct nl_object *nl_cache_get_prev(struct nl_object *obj)
160 {
161 	if (nl_list_at_head(obj, &obj->ce_cache->c_items, ce_list))
162 		return NULL;
163 	else
164 		return nl_list_entry(obj->ce_list.prev,
165 				     struct nl_object, ce_list);
166 }
167 
168 /** @} */
169 
170 /**
171  * @name Cache Allocation/Deletion
172  * @{
173  */
174 
175 /**
176  * Allocate new cache
177  * @arg ops		Cache operations
178  *
179  * Allocate and initialize a new cache based on the cache operations
180  * provided.
181  *
182  * @return Allocated cache or NULL if allocation failed.
183  */
nl_cache_alloc(struct nl_cache_ops * ops)184 struct nl_cache *nl_cache_alloc(struct nl_cache_ops *ops)
185 {
186 	struct nl_cache *cache;
187 
188 	cache = calloc(1, sizeof(*cache));
189 	if (!cache)
190 		return NULL;
191 
192 	nl_init_list_head(&cache->c_items);
193 	cache->c_ops = ops;
194 	cache->c_flags |= ops->co_flags;
195 	cache->c_refcnt = 1;
196 
197 	/*
198 	 * If object type provides a hash keygen
199 	 * functions, allocate a hash table for the
200 	 * cache objects for faster lookups
201 	 */
202 	if (ops->co_obj_ops->oo_keygen) {
203 		int hashtable_size;
204 
205 		if (ops->co_hash_size)
206 			hashtable_size = ops->co_hash_size;
207 		else
208 			hashtable_size = NL_MAX_HASH_ENTRIES;
209 
210 		cache->hashtable = nl_hash_table_alloc(hashtable_size);
211 	}
212 
213 	NL_DBG(2, "Allocated cache %p <%s>.\n", cache, nl_cache_name(cache));
214 
215 	return cache;
216 }
217 
218 /**
219  * Allocate new cache and fill it
220  * @arg ops		Cache operations
221  * @arg sock		Netlink socket
222  * @arg result		Result pointer
223  *
224  * Allocate new cache and fill it. Equivalent to calling:
225  * @code
226  * cache = nl_cache_alloc(ops);
227  * nl_cache_refill(sock, cache);
228  * @endcode
229  *
230  * @see nl_cache_alloc
231  *
232  * @return 0 on success or a negative error code.
233  */
nl_cache_alloc_and_fill(struct nl_cache_ops * ops,struct nl_sock * sock,struct nl_cache ** result)234 int nl_cache_alloc_and_fill(struct nl_cache_ops *ops, struct nl_sock *sock,
235 			    struct nl_cache **result)
236 {
237 	struct nl_cache *cache;
238 	int err;
239 
240 	if (!(cache = nl_cache_alloc(ops)))
241 		return -NLE_NOMEM;
242 
243 	if (sock && (err = nl_cache_refill(sock, cache)) < 0) {
244 		nl_cache_free(cache);
245 		return err;
246 	}
247 
248 	*result = cache;
249 	return 0;
250 }
251 
252 /**
253  * Allocate new cache based on type name
254  * @arg kind		Name of cache type
255  * @arg result		Result pointer
256  *
257  * Lookup cache ops via nl_cache_ops_lookup() and allocate the cache
258  * by calling nl_cache_alloc(). Stores the allocated cache in the
259  * result pointer provided.
260  *
261  * @see nl_cache_alloc
262  *
263  * @return 0 on success or a negative error code.
264  */
nl_cache_alloc_name(const char * kind,struct nl_cache ** result)265 int nl_cache_alloc_name(const char *kind, struct nl_cache **result)
266 {
267 	struct nl_cache_ops *ops;
268 	struct nl_cache *cache;
269 
270 	ops = nl_cache_ops_lookup_safe(kind);
271 	if (!ops)
272 		return -NLE_NOCACHE;
273 
274 	cache = nl_cache_alloc(ops);
275 	nl_cache_ops_put(ops);
276 	if (!cache)
277 		return -NLE_NOMEM;
278 
279 	*result = cache;
280 	return 0;
281 }
282 
283 /**
284  * Allocate new cache containing a subset of an existing cache
285  * @arg orig		Original cache to base new cache on
286  * @arg filter		Filter defining the subset to be filled into the new cache
287  *
288  * Allocates a new cache matching the type of the cache specified by
289  * \p orig. Iterates over the \p orig cache applying the specified
290  * \p filter and copies all objects that match to the new cache.
291  *
292  * The copied objects are clones but do not contain a reference to each
293  * other. Later modifications to objects in the original cache will
294  * not affect objects in the new cache.
295  *
296  * @return A newly allocated cache or NULL.
297  */
nl_cache_subset(struct nl_cache * orig,struct nl_object * filter)298 struct nl_cache *nl_cache_subset(struct nl_cache *orig,
299 				 struct nl_object *filter)
300 {
301 	struct nl_cache *cache;
302 	struct nl_object *obj;
303 
304 	if (!filter)
305 		BUG();
306 
307 	cache = nl_cache_alloc(orig->c_ops);
308 	if (!cache)
309 		return NULL;
310 
311 	NL_DBG(2, "Filling subset of cache %p <%s> with filter %p into %p\n",
312 	       orig, nl_cache_name(orig), filter, cache);
313 
314 	nl_list_for_each_entry(obj, &orig->c_items, ce_list) {
315 		if (!nl_object_match_filter(obj, filter))
316 			continue;
317 
318 		nl_cache_add(cache, obj);
319 	}
320 
321 	return cache;
322 }
323 
324 /**
325  * Allocate new cache and copy the contents of an existing cache
326  * @arg cache		Original cache to base new cache on
327  *
328  * Allocates a new cache matching the type of the cache specified by
329  * \p cache. Iterates over the \p cache cache and copies all objects
330  * to the new cache.
331  *
332  * The copied objects are clones but do not contain a reference to each
333  * other. Later modifications to objects in the original cache will
334  * not affect objects in the new cache.
335  *
336  * @return A newly allocated cache or NULL.
337  */
nl_cache_clone(struct nl_cache * cache)338 struct nl_cache *nl_cache_clone(struct nl_cache *cache)
339 {
340 	struct nl_cache_ops *ops = nl_cache_get_ops(cache);
341 	struct nl_cache *clone;
342 	struct nl_object *obj;
343 
344 	clone = nl_cache_alloc(ops);
345 	if (!clone)
346 		return NULL;
347 
348 	NL_DBG(2, "Cloning %p into %p\n", cache, clone);
349 
350 	nl_list_for_each_entry(obj, &cache->c_items, ce_list)
351 		nl_cache_add(clone, obj);
352 
353 	return clone;
354 }
355 
356 /**
357  * Remove all objects of a cache.
358  * @arg cache		Cache to clear
359  *
360  * The objects are unliked/removed from the cache by calling
361  * nl_cache_remove() on each object in the cache. If any of the objects
362  * to not contain any further references to them, those objects will
363  * be freed.
364  *
365  * Unlike with nl_cache_free(), the cache is not freed just emptied.
366  */
nl_cache_clear(struct nl_cache * cache)367 void nl_cache_clear(struct nl_cache *cache)
368 {
369 	struct nl_object *obj, *tmp;
370 
371 	NL_DBG(2, "Clearing cache %p <%s>...\n", cache, nl_cache_name(cache));
372 
373 	nl_list_for_each_entry_safe(obj, tmp, &cache->c_items, ce_list)
374 		nl_cache_remove(obj);
375 }
376 
__nl_cache_free(struct nl_cache * cache)377 static void __nl_cache_free(struct nl_cache *cache)
378 {
379 	nl_cache_clear(cache);
380 
381 	if (cache->hashtable)
382 		nl_hash_table_free(cache->hashtable);
383 
384 	NL_DBG(2, "Freeing cache %p <%s>...\n", cache, nl_cache_name(cache));
385 	free(cache);
386 }
387 
388 /**
389  * Increase reference counter of cache
390  * @arg cache		Cache
391  */
nl_cache_get(struct nl_cache * cache)392 void nl_cache_get(struct nl_cache *cache)
393 {
394 	cache->c_refcnt++;
395 
396 	NL_DBG(3, "Incremented cache %p <%s> reference count to %d\n",
397 	       cache, nl_cache_name(cache), cache->c_refcnt);
398 }
399 
400 /**
401  * Free a cache.
402  * @arg cache		Cache to free.
403  *
404  * Calls nl_cache_clear() to remove all objects associated with the
405  * cache and frees the cache afterwards.
406  *
407  * @see nl_cache_clear()
408  */
nl_cache_free(struct nl_cache * cache)409 void nl_cache_free(struct nl_cache *cache)
410 {
411 	if (!cache)
412 		return;
413 
414 	cache->c_refcnt--;
415 
416 	NL_DBG(3, "Decremented cache %p <%s> reference count, %d remaining\n",
417 	       cache, nl_cache_name(cache), cache->c_refcnt);
418 
419 	if (cache->c_refcnt <= 0)
420 		__nl_cache_free(cache);
421 }
422 
nl_cache_put(struct nl_cache * cache)423 void nl_cache_put(struct nl_cache *cache)
424 {
425 	nl_cache_free(cache);
426 }
427 
428 /** @} */
429 
430 /**
431  * @name Cache Modifications
432  * @{
433  */
434 
__cache_add(struct nl_cache * cache,struct nl_object * obj)435 static int __cache_add(struct nl_cache *cache, struct nl_object *obj)
436 {
437 	int ret;
438 
439 	obj->ce_cache = cache;
440 
441 	if (cache->hashtable) {
442 		ret = nl_hash_table_add(cache->hashtable, obj);
443 		if (ret < 0) {
444 			obj->ce_cache = NULL;
445 			return ret;
446 		}
447 	}
448 
449 	nl_list_add_tail(&obj->ce_list, &cache->c_items);
450 	cache->c_nitems++;
451 
452 	NL_DBG(3, "Added object %p to cache %p <%s>, nitems %d\n",
453 	       obj, cache, nl_cache_name(cache), cache->c_nitems);
454 
455 	return 0;
456 }
457 
458 /**
459  * Add object to cache.
460  * @arg cache		Cache
461  * @arg obj		Object to be added to the cache
462  *
463  * Adds the object \p obj to the specified \p cache. In case the object
464  * is already associated with another cache, the object is cloned before
465  * adding it to the cache. In this case, the sole reference to the object
466  * will be the one of the cache. Therefore clearing/freeing the cache
467  * will result in the object being freed again.
468  *
469  * If the object has not been associated with a cache yet, the reference
470  * counter of the object is incremented to account for the additional
471  * reference.
472  *
473  * The type of the object and cache must match, otherwise an error is
474  * returned (-NLE_OBJ_MISMATCH).
475  *
476  * @see nl_cache_move()
477  *
478  * @return 0 or a negative error code.
479  */
nl_cache_add(struct nl_cache * cache,struct nl_object * obj)480 int nl_cache_add(struct nl_cache *cache, struct nl_object *obj)
481 {
482 	struct nl_object *new;
483 	int ret = 0;
484 
485 	if (cache->c_ops->co_obj_ops != obj->ce_ops)
486 		return -NLE_OBJ_MISMATCH;
487 
488 	if (!nl_list_empty(&obj->ce_list)) {
489 		NL_DBG(3, "Object %p already in cache, cloning new object\n", obj);
490 
491 		new = nl_object_clone(obj);
492 		if (!new)
493 			return -NLE_NOMEM;
494 	} else {
495 		nl_object_get(obj);
496 		new = obj;
497 	}
498 
499 	ret = __cache_add(cache, new);
500 	if (ret < 0)
501 		nl_object_put(new);
502 
503 	return ret;
504 }
505 
506 /**
507  * Move object from one cache to another
508  * @arg cache		Cache to move object to.
509  * @arg obj		Object subject to be moved
510  *
511  * Removes the the specified object \p obj from its associated cache
512  * and moves it to another cache.
513  *
514  * If the object is not associated with a cache, the function behaves
515  * just like nl_cache_add().
516  *
517  * The type of the object and cache must match, otherwise an error is
518  * returned (-NLE_OBJ_MISMATCH).
519  *
520  * @see nl_cache_add()
521  *
522  * @return 0 on success or a negative error code.
523  */
nl_cache_move(struct nl_cache * cache,struct nl_object * obj)524 int nl_cache_move(struct nl_cache *cache, struct nl_object *obj)
525 {
526 	if (cache->c_ops->co_obj_ops != obj->ce_ops)
527 		return -NLE_OBJ_MISMATCH;
528 
529 	NL_DBG(3, "Moving object %p from cache %p to cache %p\n",
530 	       obj, obj->ce_cache, cache);
531 
532 	/* Acquire reference, if already in a cache this will be
533 	 * reverted during removal */
534 	nl_object_get(obj);
535 
536 	if (!nl_list_empty(&obj->ce_list))
537 		nl_cache_remove(obj);
538 
539 	return __cache_add(cache, obj);
540 }
541 
542 /**
543  * Remove object from cache.
544  * @arg obj		Object to remove from cache
545  *
546  * Removes the object \c obj from the cache it is associated with. The
547  * reference counter of the object will be decremented. If the reference
548  * to the object was the only one remaining, the object will be freed.
549  *
550  * If no cache is associated with the object, this function is a NOP.
551  */
nl_cache_remove(struct nl_object * obj)552 void nl_cache_remove(struct nl_object *obj)
553 {
554 	int ret;
555 	struct nl_cache *cache = obj->ce_cache;
556 
557 	if (cache == NULL)
558 		return;
559 
560 	if (cache->hashtable) {
561 		ret = nl_hash_table_del(cache->hashtable, obj);
562 		if (ret < 0)
563 			NL_DBG(2, "Failed to delete %p from cache %p <%s>.\n",
564 			       obj, cache, nl_cache_name(cache));
565 	}
566 
567 	nl_list_del(&obj->ce_list);
568 	obj->ce_cache = NULL;
569 	nl_object_put(obj);
570 	cache->c_nitems--;
571 
572 	NL_DBG(2, "Deleted object %p from cache %p <%s>.\n",
573 	       obj, cache, nl_cache_name(cache));
574 }
575 
576 /** @} */
577 
578 /**
579  * @name Synchronization
580  * @{
581  */
582 
583 /**
584  * Set synchronization arg1 of cache
585  * @arg cache		Cache
586  * @arg arg		argument
587  *
588  * Synchronization arguments are used to specify filters when
589  * requesting dumps from the kernel.
590  */
nl_cache_set_arg1(struct nl_cache * cache,int arg)591 void nl_cache_set_arg1(struct nl_cache *cache, int arg)
592 {
593 	cache->c_iarg1 = arg;
594 }
595 
596 /**
597  * Set synchronization arg2 of cache
598  * @arg cache		Cache
599  * @arg arg		argument
600  *
601  * Synchronization arguments are used to specify filters when
602  * requesting dumps from the kernel.
603  */
nl_cache_set_arg2(struct nl_cache * cache,int arg)604 void nl_cache_set_arg2(struct nl_cache *cache, int arg)
605 {
606 	cache->c_iarg2 = arg;
607 }
608 
609 /**
610  * Set cache flags
611  * @arg cache		Cache
612  * @arg flags		Flags
613  */
nl_cache_set_flags(struct nl_cache * cache,unsigned int flags)614 void nl_cache_set_flags(struct nl_cache *cache, unsigned int flags)
615 {
616 	cache->c_flags |= flags;
617 }
618 
619 /**
620  * Invoke the request-update operation
621  * @arg sk		Netlink socket.
622  * @arg cache		Cache
623  *
624  * This function causes the \e request-update function of the cache
625  * operations to be invoked. This usually causes a dump request to
626  * be sent over the netlink socket which triggers the kernel to dump
627  * all objects of a specific type to be dumped onto the netlink
628  * socket for pickup.
629  *
630  * The behaviour of this function depends on the implemenation of
631  * the \e request_update function of each individual type of cache.
632  *
633  * This function will not have any effects on the cache (unless the
634  * request_update implementation of the cache operations does so).
635  *
636  * Use nl_cache_pickup() to pick-up (read) the objects from the socket
637  * and fill them into the cache.
638  *
639  * @see nl_cache_pickup(), nl_cache_resync()
640  *
641  * @return 0 on success or a negative error code. Some implementations
642  * of co_request_update() return a positive number on success that is
643  * the number of bytes sent. Treat any non-negative number as success too.
644  */
nl_cache_request_full_dump(struct nl_sock * sk,struct nl_cache * cache)645 static int nl_cache_request_full_dump(struct nl_sock *sk,
646 				      struct nl_cache *cache)
647 {
648 	if (sk->s_proto != cache->c_ops->co_protocol)
649 		return -NLE_PROTO_MISMATCH;
650 
651 	if (cache->c_ops->co_request_update == NULL)
652 		return -NLE_OPNOTSUPP;
653 
654 	NL_DBG(2, "Requesting update from kernel for cache %p <%s>\n",
655 	          cache, nl_cache_name(cache));
656 
657 	return cache->c_ops->co_request_update(cache, sk);
658 }
659 
660 /** @cond SKIP */
661 struct update_xdata {
662 	struct nl_cache_ops *ops;
663 	struct nl_parser_param *params;
664 };
665 
update_msg_parser(struct nl_msg * msg,void * arg)666 static int update_msg_parser(struct nl_msg *msg, void *arg)
667 {
668 	struct update_xdata *x = arg;
669 	int ret = 0;
670 
671 	ret = nl_cache_parse(x->ops, &msg->nm_src, msg->nm_nlh, x->params);
672 	if (ret == -NLE_EXIST)
673 		return NL_SKIP;
674 	else
675 		return ret;
676 }
677 /** @endcond */
678 
679 /**
680  * Pick-up a netlink request-update with your own parser
681  * @arg sk		Netlink socket
682  * @arg cache		Cache
683  * @arg param		Parser parameters
684  */
__cache_pickup(struct nl_sock * sk,struct nl_cache * cache,struct nl_parser_param * param)685 static int __cache_pickup(struct nl_sock *sk, struct nl_cache *cache,
686 			  struct nl_parser_param *param)
687 {
688 	int err;
689 	struct nl_cb *cb;
690 	struct update_xdata x = {
691 		.ops = cache->c_ops,
692 		.params = param,
693 	};
694 
695 	NL_DBG(2, "Picking up answer for cache %p <%s>\n",
696 	       cache, nl_cache_name(cache));
697 
698 	cb = nl_cb_clone(sk->s_cb);
699 	if (cb == NULL)
700 		return -NLE_NOMEM;
701 
702 	nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, update_msg_parser, &x);
703 
704 	err = nl_recvmsgs(sk, cb);
705 	if (err < 0)
706 		NL_DBG(2, "While picking up for %p <%s>, recvmsgs() returned %d: %s\n",
707 		       cache, nl_cache_name(cache), err, nl_geterror(err));
708 
709 	nl_cb_put(cb);
710 
711 	return err;
712 }
713 
pickup_checkdup_cb(struct nl_object * c,struct nl_parser_param * p)714 static int pickup_checkdup_cb(struct nl_object *c, struct nl_parser_param *p)
715 {
716 	struct nl_cache *cache = (struct nl_cache *)p->pp_arg;
717 	struct nl_object *old;
718 
719 	old = nl_cache_search(cache, c);
720 	if (old) {
721 		if (nl_object_update(old, c) == 0) {
722 			nl_object_put(old);
723 			return 0;
724 		}
725 
726 		nl_cache_remove(old);
727 		nl_object_put(old);
728 	}
729 
730 	return nl_cache_add(cache, c);
731 }
732 
pickup_cb(struct nl_object * c,struct nl_parser_param * p)733 static int pickup_cb(struct nl_object *c, struct nl_parser_param *p)
734 {
735 	struct nl_cache *cache = p->pp_arg;
736 
737 	return nl_cache_add(cache, c);
738 }
739 
__nl_cache_pickup(struct nl_sock * sk,struct nl_cache * cache,int checkdup)740 static int __nl_cache_pickup(struct nl_sock *sk, struct nl_cache *cache,
741 			     int checkdup)
742 {
743 	struct nl_parser_param p;
744 
745 	p.pp_cb = checkdup ? pickup_checkdup_cb : pickup_cb;
746 	p.pp_arg = cache;
747 
748 	if (sk->s_proto != cache->c_ops->co_protocol)
749 		return -NLE_PROTO_MISMATCH;
750 
751 	return __cache_pickup(sk, cache, &p);
752 }
753 
754 /**
755  * Pickup a netlink dump response and put it into a cache.
756  * @arg sk		Netlink socket.
757  * @arg cache		Cache to put items into.
758  *
759  * Waits for netlink messages to arrive, parses them and puts them into
760  * the specified cache.
761  *
762  * @return 0 on success or a negative error code.
763  */
nl_cache_pickup_checkdup(struct nl_sock * sk,struct nl_cache * cache)764 int nl_cache_pickup_checkdup(struct nl_sock *sk, struct nl_cache *cache)
765 {
766 	return __nl_cache_pickup(sk, cache, 1);
767 }
768 
769 /**
770  * Pickup a netlink dump response and put it into a cache.
771  * @arg sk		Netlink socket.
772  * @arg cache		Cache to put items into.
773  *
774  * Waits for netlink messages to arrive, parses them and puts them into
775  * the specified cache. If an old object with same key attributes is
776  * present in the cache, it is replaced with the new object.
777  * If the old object type supports an update operation, an update is
778  * attempted before a replace.
779  *
780  * @return 0 on success or a negative error code.
781  */
nl_cache_pickup(struct nl_sock * sk,struct nl_cache * cache)782 int nl_cache_pickup(struct nl_sock *sk, struct nl_cache *cache)
783 {
784 	return __nl_cache_pickup(sk, cache, 0);
785 }
786 
cache_include(struct nl_cache * cache,struct nl_object * obj,struct nl_msgtype * type,change_func_t cb,change_func_v2_t cb_v2,void * data)787 static int cache_include(struct nl_cache *cache, struct nl_object *obj,
788 			 struct nl_msgtype *type, change_func_t cb,
789 			 change_func_v2_t cb_v2, void *data)
790 {
791 	struct nl_object *old;
792 	struct nl_object *clone = NULL;
793 	uint64_t diff = 0;
794 
795 	switch (type->mt_act) {
796 	case NL_ACT_NEW:
797 	case NL_ACT_DEL:
798 		old = nl_cache_search(cache, obj);
799 		if (old) {
800 			if (cb_v2 && old->ce_ops->oo_update) {
801 				clone = nl_object_clone(old);
802 				diff = nl_object_diff64(old, obj);
803 			}
804 			/*
805 			 * Some objects types might support merging the new
806 			 * object with the old existing cache object.
807 			 * Handle them first.
808 			 */
809 			if (nl_object_update(old, obj) == 0) {
810 				if (cb_v2) {
811 					cb_v2(cache, clone, obj, diff,
812 					      NL_ACT_CHANGE, data);
813 					nl_object_put(clone);
814 				} else if (cb)
815 					cb(cache, old, NL_ACT_CHANGE, data);
816 				nl_object_put(old);
817 				return 0;
818 			}
819 			nl_object_put(clone);
820 
821 			nl_cache_remove(old);
822 			if (type->mt_act == NL_ACT_DEL) {
823 				if (cb_v2)
824 					cb_v2(cache, old, NULL, 0, NL_ACT_DEL,
825 					      data);
826 				else if (cb)
827 					cb(cache, old, NL_ACT_DEL, data);
828 				nl_object_put(old);
829 			}
830 		}
831 
832 		if (type->mt_act == NL_ACT_NEW) {
833 			nl_cache_move(cache, obj);
834 			if (old == NULL) {
835 				if (cb_v2) {
836 					cb_v2(cache, NULL, obj, 0, NL_ACT_NEW,
837 					      data);
838 				} else if (cb)
839 					cb(cache, obj, NL_ACT_NEW, data);
840 			} else if (old) {
841 				diff = 0;
842 				if (cb || cb_v2)
843 					diff = nl_object_diff64(old, obj);
844 				if (diff && cb_v2) {
845 					cb_v2(cache, old, obj, diff, NL_ACT_CHANGE,
846 					      data);
847 				} else if (diff && cb)
848 					cb(cache, obj, NL_ACT_CHANGE, data);
849 
850 				nl_object_put(old);
851 			}
852 		}
853 		break;
854 	default:
855 		NL_DBG(2, "Unknown action associated to object %p\n", obj);
856 		return 0;
857 	}
858 
859 	return 0;
860 }
861 
nl_cache_include(struct nl_cache * cache,struct nl_object * obj,change_func_t change_cb,void * data)862 int nl_cache_include(struct nl_cache *cache, struct nl_object *obj,
863 		     change_func_t change_cb, void *data)
864 {
865 	struct nl_cache_ops *ops = cache->c_ops;
866 	int i;
867 
868 	if (ops->co_obj_ops != obj->ce_ops)
869 		return -NLE_OBJ_MISMATCH;
870 
871 	for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++)
872 		if (ops->co_msgtypes[i].mt_id == obj->ce_msgtype)
873 			return cache_include(cache, obj, &ops->co_msgtypes[i],
874 					     change_cb, NULL, data);
875 
876 	NL_DBG(3, "Object %p does not seem to belong to cache %p <%s>\n",
877 	       obj, cache, nl_cache_name(cache));
878 
879 	return -NLE_MSGTYPE_NOSUPPORT;
880 }
881 
nl_cache_include_v2(struct nl_cache * cache,struct nl_object * obj,change_func_v2_t change_cb,void * data)882 int nl_cache_include_v2(struct nl_cache *cache, struct nl_object *obj,
883 			change_func_v2_t change_cb, void *data)
884 {
885 	struct nl_cache_ops *ops = cache->c_ops;
886 	int i;
887 
888 	if (ops->co_obj_ops != obj->ce_ops)
889 		return -NLE_OBJ_MISMATCH;
890 
891 	for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++)
892 		if (ops->co_msgtypes[i].mt_id == obj->ce_msgtype)
893 			return cache_include(cache, obj, &ops->co_msgtypes[i],
894 						NULL, change_cb, data);
895 
896 	NL_DBG(3, "Object %p does not seem to belong to cache %p <%s>\n",
897 	       obj, cache, nl_cache_name(cache));
898 
899 	return -NLE_MSGTYPE_NOSUPPORT;
900 }
901 
resync_cb(struct nl_object * c,struct nl_parser_param * p)902 static int resync_cb(struct nl_object *c, struct nl_parser_param *p)
903 {
904 	struct nl_cache_assoc *ca = p->pp_arg;
905 
906 	if (ca->ca_change_v2)
907 		return nl_cache_include_v2(ca->ca_cache, c, ca->ca_change_v2,
908 					   ca->ca_change_data);
909 	else
910 		return nl_cache_include(ca->ca_cache, c, ca->ca_change,
911 					ca->ca_change_data);
912 }
913 
nl_cache_resync(struct nl_sock * sk,struct nl_cache * cache,change_func_t change_cb,void * data)914 int nl_cache_resync(struct nl_sock *sk, struct nl_cache *cache,
915 		    change_func_t change_cb, void *data)
916 {
917 	struct nl_object *obj, *next;
918 	struct nl_af_group *grp;
919 	struct nl_cache_assoc ca = {
920 		.ca_cache = cache,
921 		.ca_change = change_cb,
922 		.ca_change_data = data,
923 	};
924 	struct nl_parser_param p = {
925 		.pp_cb = resync_cb,
926 		.pp_arg = &ca,
927 	};
928 	int err;
929 
930 	if (sk->s_proto != cache->c_ops->co_protocol)
931 		return -NLE_PROTO_MISMATCH;
932 
933 	NL_DBG(1, "Resyncing cache %p <%s>...\n", cache, nl_cache_name(cache));
934 
935 	/* Mark all objects so we can see if some of them are obsolete */
936 	nl_cache_mark_all(cache);
937 
938 	grp = cache->c_ops->co_groups;
939 	do {
940 		if (grp && grp->ag_group &&
941 			(cache->c_flags & NL_CACHE_AF_ITER))
942 			nl_cache_set_arg1(cache, grp->ag_family);
943 
944 restart:
945 		err = nl_cache_request_full_dump(sk, cache);
946 		if (err < 0)
947 			goto errout;
948 
949 		err = __cache_pickup(sk, cache, &p);
950 		if (err == -NLE_DUMP_INTR)
951 			goto restart;
952 		else if (err < 0)
953 			goto errout;
954 
955 		if (grp)
956 			grp++;
957 	} while (grp && grp->ag_group &&
958 		(cache->c_flags & NL_CACHE_AF_ITER));
959 
960 	nl_list_for_each_entry_safe(obj, next, &cache->c_items, ce_list) {
961 		if (nl_object_is_marked(obj)) {
962 			nl_object_get(obj);
963 			nl_cache_remove(obj);
964 			if (change_cb)
965 				change_cb(cache, obj, NL_ACT_DEL, data);
966 			nl_object_put(obj);
967 		}
968 	}
969 
970 	NL_DBG(1, "Finished resyncing %p <%s>\n", cache, nl_cache_name(cache));
971 
972 	err = 0;
973 errout:
974 	return err;
975 }
976 
977 /** @} */
978 
979 /**
980  * @name Parsing
981  * @{
982  */
983 
984 /** @cond SKIP */
nl_cache_parse(struct nl_cache_ops * ops,struct sockaddr_nl * who,struct nlmsghdr * nlh,struct nl_parser_param * params)985 int nl_cache_parse(struct nl_cache_ops *ops, struct sockaddr_nl *who,
986 		   struct nlmsghdr *nlh, struct nl_parser_param *params)
987 {
988 	int i, err;
989 
990 	if (!nlmsg_valid_hdr(nlh, ops->co_hdrsize))
991 		return -NLE_MSG_TOOSHORT;
992 
993 	for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++) {
994 		if (ops->co_msgtypes[i].mt_id == nlh->nlmsg_type) {
995 			err = ops->co_msg_parser(ops, who, nlh, params);
996 			if (err != -NLE_OPNOTSUPP)
997 				goto errout;
998 		}
999 	}
1000 
1001 
1002 	err = -NLE_MSGTYPE_NOSUPPORT;
1003 errout:
1004 	return err;
1005 }
1006 /** @endcond */
1007 
1008 /**
1009  * Parse a netlink message and add it to the cache.
1010  * @arg cache		cache to add element to
1011  * @arg msg		netlink message
1012  *
1013  * Parses a netlink message by calling the cache specific message parser
1014  * and adds the new element to the cache. If an old object with same key
1015  * attributes is present in the cache, it is replaced with the new object.
1016  * If the old object type supports an update operation, an update is
1017  * attempted before a replace.
1018  *
1019  * @return 0 or a negative error code.
1020  */
nl_cache_parse_and_add(struct nl_cache * cache,struct nl_msg * msg)1021 int nl_cache_parse_and_add(struct nl_cache *cache, struct nl_msg *msg)
1022 {
1023 	struct nl_parser_param p = {
1024 		.pp_cb = pickup_cb,
1025 		.pp_arg = cache,
1026 	};
1027 
1028 	return nl_cache_parse(cache->c_ops, NULL, nlmsg_hdr(msg), &p);
1029 }
1030 
1031 /**
1032  * (Re)fill a cache with the contents in the kernel.
1033  * @arg sk		Netlink socket.
1034  * @arg cache		cache to update
1035  *
1036  * Clears the specified cache and fills it with the current state in
1037  * the kernel.
1038  *
1039  * @return 0 or a negative error code.
1040  */
nl_cache_refill(struct nl_sock * sk,struct nl_cache * cache)1041 int nl_cache_refill(struct nl_sock *sk, struct nl_cache *cache)
1042 {
1043 	struct nl_af_group *grp;
1044 	int err;
1045 
1046 	if (sk->s_proto != cache->c_ops->co_protocol)
1047 		return -NLE_PROTO_MISMATCH;
1048 
1049 	nl_cache_clear(cache);
1050 	grp = cache->c_ops->co_groups;
1051 	do {
1052 		if (grp && grp->ag_group &&
1053 			(cache->c_flags & NL_CACHE_AF_ITER))
1054 			nl_cache_set_arg1(cache, grp->ag_family);
1055 
1056 restart:
1057 		err = nl_cache_request_full_dump(sk, cache);
1058 		if (err < 0)
1059 			return err;
1060 
1061 		NL_DBG(2, "Updating cache %p <%s> for family %u, request sent, waiting for reply\n",
1062 		       cache, nl_cache_name(cache), grp ? grp->ag_family : AF_UNSPEC);
1063 
1064 		err = nl_cache_pickup(sk, cache);
1065 		if (err == -NLE_DUMP_INTR) {
1066 			NL_DBG(2, "Dump interrupted, restarting!\n");
1067 			goto restart;
1068 		} else if (err < 0)
1069 			break;
1070 
1071 		if (grp)
1072 			grp++;
1073 	} while (grp && grp->ag_group &&
1074 			(cache->c_flags & NL_CACHE_AF_ITER));
1075 
1076 	return err;
1077 }
1078 
1079 /** @} */
1080 
1081 /**
1082  * @name Utillities
1083  * @{
1084  */
__cache_fast_lookup(struct nl_cache * cache,struct nl_object * needle)1085 static struct nl_object *__cache_fast_lookup(struct nl_cache *cache,
1086 					     struct nl_object *needle)
1087 {
1088 	struct nl_object *obj;
1089 
1090 	obj = nl_hash_table_lookup(cache->hashtable, needle);
1091 	if (obj) {
1092 		nl_object_get(obj);
1093 		return obj;
1094 	}
1095 
1096 	return NULL;
1097 }
1098 
1099 /**
1100  * Search object in cache
1101  * @arg cache		Cache
1102  * @arg needle		Object to look for.
1103  *
1104  * Searches the cache for an object which matches the object \p needle.
1105  * The function nl_object_identical() is used to determine if the
1106  * objects match. If a matching object is found, the reference counter
1107  * is incremented and the object is returned.
1108  *
1109  * Therefore, if an object is returned, the reference to the object
1110  * must be returned by calling nl_object_put() after usage.
1111  *
1112  * @return Reference to object or NULL if not found.
1113  */
nl_cache_search(struct nl_cache * cache,struct nl_object * needle)1114 struct nl_object *nl_cache_search(struct nl_cache *cache,
1115 				  struct nl_object *needle)
1116 {
1117 	struct nl_object *obj;
1118 
1119 	if (cache->hashtable)
1120 		return __cache_fast_lookup(cache, needle);
1121 
1122 	nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
1123 		if (nl_object_identical(obj, needle)) {
1124 			nl_object_get(obj);
1125 			return obj;
1126 		}
1127 	}
1128 
1129 	return NULL;
1130 }
1131 
1132 /**
1133  * Find object in cache
1134  * @arg cache		Cache
1135  * @arg filter		object acting as a filter
1136  *
1137  * Searches the cache for an object which matches the object filter.
1138  * If the filter attributes matches the object type id attributes,
1139  * and the cache supports hash lookups, a faster hashtable lookup
1140  * is used to return the object. Else, function nl_object_match_filter() is
1141  * used to determine if the objects match. If a matching object is
1142  * found, the reference counter is incremented and the object is returned.
1143  *
1144  * Therefore, if an object is returned, the reference to the object
1145  * must be returned by calling nl_object_put() after usage.
1146  *
1147  * @return Reference to object or NULL if not found.
1148  */
nl_cache_find(struct nl_cache * cache,struct nl_object * filter)1149 struct nl_object *nl_cache_find(struct nl_cache *cache,
1150 				struct nl_object *filter)
1151 {
1152 	struct nl_object *obj;
1153 
1154 	if (cache->c_ops == NULL)
1155 		BUG();
1156 
1157 	if ((nl_object_get_id_attrs(filter) == filter->ce_mask)
1158 		&& cache->hashtable)
1159 		return __cache_fast_lookup(cache, filter);
1160 
1161 	nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
1162 		if (nl_object_match_filter(obj, filter)) {
1163 			nl_object_get(obj);
1164 			return obj;
1165 		}
1166 	}
1167 
1168 	return NULL;
1169 }
1170 
1171 /**
1172  * Mark all objects of a cache
1173  * @arg cache		Cache
1174  *
1175  * Marks all objects of a cache by calling nl_object_mark() on each
1176  * object associated with the cache.
1177  */
nl_cache_mark_all(struct nl_cache * cache)1178 void nl_cache_mark_all(struct nl_cache *cache)
1179 {
1180 	struct nl_object *obj;
1181 
1182 	NL_DBG(2, "Marking all objects in cache %p <%s>\n",
1183 	       cache, nl_cache_name(cache));
1184 
1185 	nl_list_for_each_entry(obj, &cache->c_items, ce_list)
1186 		nl_object_mark(obj);
1187 }
1188 
1189 /** @} */
1190 
1191 /**
1192  * @name Dumping
1193  * @{
1194  */
1195 
1196 /**
1197  * Dump all elements of a cache.
1198  * @arg cache		cache to dump
1199  * @arg params		dumping parameters
1200  *
1201  * Dumps all elements of the \a cache to the file descriptor \a fd.
1202  */
nl_cache_dump(struct nl_cache * cache,struct nl_dump_params * params)1203 void nl_cache_dump(struct nl_cache *cache, struct nl_dump_params *params)
1204 {
1205 	nl_cache_dump_filter(cache, params, NULL);
1206 }
1207 
1208 /**
1209  * Dump all elements of a cache (filtered).
1210  * @arg cache		cache to dump
1211  * @arg params		dumping parameters (optional)
1212  * @arg filter		filter object
1213  *
1214  * Dumps all elements of the \a cache to the file descriptor \a fd
1215  * given they match the given filter \a filter.
1216  */
nl_cache_dump_filter(struct nl_cache * cache,struct nl_dump_params * params,struct nl_object * filter)1217 void nl_cache_dump_filter(struct nl_cache *cache,
1218 			  struct nl_dump_params *params,
1219 			  struct nl_object *filter)
1220 {
1221 	int type = params ? params->dp_type : NL_DUMP_DETAILS;
1222 	struct nl_object_ops *ops;
1223 	struct nl_object *obj;
1224 
1225 	NL_DBG(2, "Dumping cache %p <%s> with filter %p\n",
1226 	       cache, nl_cache_name(cache), filter);
1227 
1228 	if (type > NL_DUMP_MAX || type < 0)
1229 		BUG();
1230 
1231 	if (cache->c_ops == NULL)
1232 		BUG();
1233 
1234 	ops = cache->c_ops->co_obj_ops;
1235 	if (!ops->oo_dump[type])
1236 		return;
1237 
1238 	if (params && params->dp_buf)
1239 		memset(params->dp_buf, 0, params->dp_buflen);
1240 
1241 	nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
1242 		if (filter && !nl_object_match_filter(obj, filter))
1243 			continue;
1244 
1245 		NL_DBG(4, "Dumping object %p...\n", obj);
1246 		dump_from_ops(obj, params);
1247 	}
1248 }
1249 
1250 /** @} */
1251 
1252 /**
1253  * @name Iterators
1254  * @{
1255  */
1256 
1257 /**
1258  * Call a callback on each element of the cache.
1259  * @arg cache		cache to iterate on
1260  * @arg cb		callback function
1261  * @arg arg		argument passed to callback function
1262  *
1263  * Calls a callback function \a cb on each element of the \a cache.
1264  * The argument \a arg is passed on the callback function.
1265  */
nl_cache_foreach(struct nl_cache * cache,void (* cb)(struct nl_object *,void *),void * arg)1266 void nl_cache_foreach(struct nl_cache *cache,
1267 		      void (*cb)(struct nl_object *, void *), void *arg)
1268 {
1269 	nl_cache_foreach_filter(cache, NULL, cb, arg);
1270 }
1271 
1272 /**
1273  * Call a callback on each element of the cache (filtered).
1274  * @arg cache		cache to iterate on
1275  * @arg filter		filter object
1276  * @arg cb		callback function
1277  * @arg arg		argument passed to callback function
1278  *
1279  * Calls a callback function \a cb on each element of the \a cache
1280  * that matches the \a filter. The argument \a arg is passed on
1281  * to the callback function.
1282  */
nl_cache_foreach_filter(struct nl_cache * cache,struct nl_object * filter,void (* cb)(struct nl_object *,void *),void * arg)1283 void nl_cache_foreach_filter(struct nl_cache *cache, struct nl_object *filter,
1284 			     void (*cb)(struct nl_object *, void *), void *arg)
1285 {
1286 	struct nl_object *obj, *tmp;
1287 
1288 	if (cache->c_ops == NULL)
1289 		BUG();
1290 
1291 	nl_list_for_each_entry_safe(obj, tmp, &cache->c_items, ce_list) {
1292 		if (filter) {
1293 			int diff = nl_object_match_filter(obj, filter);
1294 
1295 			NL_DBG(3, "%p<->%p object difference: %x\n",
1296 				obj, filter, diff);
1297 
1298 			if (!diff)
1299 				continue;
1300 		}
1301 
1302 		/* Caller may hold obj for a long time */
1303 		nl_object_get(obj);
1304 
1305 		cb(obj, arg);
1306 
1307 		nl_object_put(obj);
1308 	}
1309 }
1310 
1311 /** @} */
1312 
1313 /** @} */
1314