Debian Codegraph @

tests/nl-test-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-only */
2
3 #include "nl-default.h"
4
5 #include "nl-test-util.h"
6
7 #include <fcntl.h>
8 #include <fnmatch.h>
9 #include <linux/if.h>
10 #include <sched.h>
11 #include <stdio.h>
12 #include <sys/mount.h>
13
14 #include <netlink/netlink.h>
15 #include <netlink/route/link.h>
16 #include <netlink/route/route.h>
17 #include <netlink/route/addr.h>
18 #include <netlink/socket.h>
19
20 #include "lib/route/nl-route.h"
21
22 #include "nl-aux-route/nl-route.h"
23
24 /*****************************************************************************/
25
26 void _nltst_get_urandom(void *ptr, size_t len)
27 {
28 int fd;
29 ssize_t nread;
30
31 ck_assert_int_gt(len, 0);
32 ck_assert_ptr_nonnull(ptr);
33
34 fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOCTTY);
35 _nltst_assert_errno(fd >= 0);
36
37 nread = read(fd, ptr, len);
38 _nltst_assert_errno(nread >= 0 && ((size_t)nread) == len);
39
40 _nltst_close(fd);
41 }
42
43 uint32_t _nltst_rand_u32(void)
44 {
45 _nl_thread_local static unsigned short entropy[3];
46 _nl_thread_local static bool has_entropy = false;
47
48 if (!has_entropy) {
49 unsigned long long seed;
50 uint64_t seed64;
51 const char *s;
52 char *s_end;
53
54 memset(entropy, 0, sizeof(entropy));
55 s = getenv("NLTST_SEED_RAND");
56 if (!s)
57 seed = 0;
58 else if (s[0] != '\0') {
59 errno = 0;
60 seed = strtoull(s, &s_end, 10);
61 if (errno != 0 || s_end[0] != '\0') {
62 ck_assert_msg(
63 0,
64 "invalid NLTST_SEED_RAND=\"%s\". Must be an integer to seed the random numbers",
65 s);
66 }
67 } else
68 _nltst_get_urandom(&seed, sizeof(seed));
69
70 seed64 = seed;
71 printf("runs with NLTST_SEED_RAND=%" PRIu64 "\n", seed64);
72
73 entropy[0] = (seed64 >> 0) ^ (seed64 >> 48);
74 entropy[1] = (seed64 >> 16) ^ (seed64 >> 0);
75 entropy[2] = (seed64 >> 32) ^ (seed64 >> 16);
76 has_entropy = true;
77 }
78
79 _NL_STATIC_ASSERT(sizeof(long) >= sizeof(uint32_t));
80 return jrand48(entropy);
81 }
82
83 /*****************************************************************************/
84
85 #define _CANARY 539339
86
87 struct nltst_netns {
88 int canary;
89 bool is_unshared;
90 };
91
92 /*****************************************************************************/
93
94 #define _assert_nltst_netns(nsdata) \
95 do { \
96 const struct nltst_netns *_nsdata = (nsdata); \
97 \
98 ck_assert_ptr_nonnull(_nsdata); \
99 ck_assert_int_eq(_nsdata->canary, _CANARY); \
100 } while (0)
101
102 static struct {
103 struct nltst_netns *nsdata;
104 } _netns_fixture_global;
105
106 void nltst_netns_fixture_setup(void)
107 {
108 ck_assert(!_netns_fixture_global.nsdata);
109
110 _netns_fixture_global.nsdata = nltst_netns_enter();
111 _assert_nltst_netns(_netns_fixture_global.nsdata);
112 }
113
114 void nltst_netns_fixture_teardown(void)
115 {
116 _assert_nltst_netns(_netns_fixture_global.nsdata);
117 _nl_clear_pointer(&_netns_fixture_global.nsdata, nltst_netns_leave);
118 }
119
120 bool nltst_netns_fixture_is_unshared(void)
121 {
122 _assert_nltst_netns(_netns_fixture_global.nsdata);
123 return _netns_fixture_global.nsdata->is_unshared;
124 }
125
126 /*****************************************************************************/
127
128 bool _nltst_skip_no_netns(void)
129 {
130 if (nltst_netns_fixture_is_unshared())
131 return false;
132
133 printf("skip test due to having no private netns\n");
134 return true;
135 }
136
137 /*****************************************************************************/
138
139 static void unshare_user(void)
140 {
141 const uid_t uid = geteuid();
142 const gid_t gid = getegid();
143 FILE *f;
144 int r;
145
146 /* Become a root in new user NS. */
147 r = unshare(CLONE_NEWUSER);
148 if (r != 0 && errno == EPERM) {
149 /* No permissions? Ignore. Will be handled later. */
150 return;
151 }
152 _nltst_assert_errno(r == 0);
153
154 /* Since Linux 3.19 we have to disable setgroups() in order to map users.
155 * Just proceed if the file is not there. */
156 f = fopen("/proc/self/setgroups", "we");
157 if (f) {
158 r = fprintf(f, "deny");
159 _nltst_assert_errno(r > 0);
160 _nltst_fclose(f);
161 }
162
163 /* Map current UID to root in NS to be created. */
164 f = fopen("/proc/self/uid_map", "we");
165 if (!f) {
166 if (errno == EACCES) {
167 /* Accessing uid_map might fail due to sandboxing.
168 * We ignore that error and proceed with the test. It will probably
169 * still work. */
170 return;
171 }
172 _nltst_assert_errno(f);
173 }
174 r = fprintf(f, "0 %d 1", uid);
175 _nltst_assert_errno(r > 0);
176 r = fclose(f);
177 if (r != 0 && errno == EPERM) {
178 /* Oddly, it seems close() can fail at this point. Ignore it,
179 * but we probably will be unable to unshare (which we handle
180 * later).
181 */
182 } else
183 _nltst_assert_errno(r == 0);
184
185 /* Map current GID to root in NS to be created. */
186 f = fopen("/proc/self/gid_map", "we");
187 _nltst_assert_errno(f);
188 r = fprintf(f, "0 %d 1", gid);
189 _nltst_assert_errno(r > 0);
190 r = fclose(f);
191 if (r != 0 && errno == EPERM) {
192 /* Oddly, it seems close() can fail at this point. Ignore it, but
193 * we probably will be unable to unshare (which we handle
194 * later).
195 */
196 } else
197 _nltst_assert_errno(r == 0);
198 }
199
200 struct nltst_netns *nltst_netns_enter(void)
201 {
202 struct nltst_netns *nsdata;
203 int r;
204
205 nsdata = calloc(1, sizeof(struct nltst_netns));
206 ck_assert(nsdata);
207
208 nsdata->canary = _CANARY;
209
210 unshare_user();
211
212 r = unshare(CLONE_NEWNET | CLONE_NEWNS);
213 if (r != 0 && errno == EPERM) {
214 /* The system is probably sandboxed somehow and we are unable
215 * to create a private netns. That seems questionable, because
216 * a point of a private netns is to sandbox an application.
217 * Not having permissions to sandbox sounds bad.
218 *
219 * Anyway. We accept this and will later skip some tests. */
220 return nsdata;
221 }
222 _nltst_assert_errno(r == 0);
223
224 /* We need a read-only /sys so that the platform knows there's no udev. */
225 mount(NULL, "/sys", "sysfs", MS_SLAVE, NULL);
226 r = mount("sys", "/sys", "sysfs", MS_RDONLY, NULL);
227 _nltst_assert_errno(r == 0);
228
229 nsdata->is_unshared = true;
230 return nsdata;
231 }
232
233 void nltst_netns_leave(struct nltst_netns *nsdata)
234 {
235 ck_assert(nsdata);
236 ck_assert_int_eq(nsdata->canary, _CANARY);
237
238 /* nltst_netns_leave() was supposed to enter the original namespaces again
239 * and undo enter.
240 *
241 * However, I could get it to work (setns() always fails with EPERM)
242 * and valgrind on current Ubuntu seems not to support setns() call.
243 *
244 * So, do nothing. It's not really a problem, because the next test
245 * either should unshare yet another namespace, or not care about
246 * such things. */
247
248 free(nsdata);
249 }
250
251 /*****************************************************************************/
252
253 void _nltst_object_identical(const void *a, const void *b)
254 {
255 struct nl_object *o_a = (void *)a;
256 struct nl_object *o_b = (void *)b;
257
258 ck_assert(a);
259 ck_assert(b);
260
261 ck_assert_int_eq(nl_object_identical(o_a, o_b), 1);
262 ck_assert_int_eq(nl_object_identical(o_b, o_a), 1);
263 ck_assert_int_eq(nl_object_diff64(o_b, o_a), 0);
264 ck_assert_int_eq(nl_object_diff64(o_a, o_b), 0);
265 ck_assert_int_eq(nl_object_diff(o_a, o_b), 0);
266 ck_assert_int_eq(nl_object_diff(o_b, o_a), 0);
267 }
268
269 /*****************************************************************************/
270
271 char *_nltst_object_to_string(const struct nl_object *obj)
272 {
273 size_t L = 1024;
274 size_t l;
275 char *s;
276 struct nl_dump_params dp;
277 char canary;
278
279 if (!obj)
280 return strdup("(null)");
281
282 s = malloc(L);
283 ck_assert_ptr_nonnull(s);
284
285 canary = _nltst_rand_u32();
286 s[L - 1u] = canary;
287
288 dp = (struct nl_dump_params){
289 .dp_type = NL_DUMP_LINE,
290 .dp_buf = s,
291 .dp_buflen = L - 1u,
292 };
293
294 nl_object_dump((struct nl_object *)obj, &dp);
295
296 l = strlen(s);
297 ck_assert_int_ge(l, 2);
298 ck_assert_int_lt(l, L);
299 ck_assert(canary == s[L - 1u]);
300 s = realloc(s, l + 1);
301 ck_assert_ptr_nonnull(s);
302
303 ck_assert_msg(s[l - 1u] == '\n',
304 "expects newline after dump. Got \"%s\"", s);
305 s[l - 1u] = '\0';
306
307 ck_assert_msg(!strchr(s, '\n'),
308 "no further newline expected. Got \"%s\"", s);
309
310 return s;
311 }
312
313 char *_nltst_objects_to_string(const char *description,
314 struct nl_object *const *objs, ssize_t len)
315 {
316 _nl_auto_free char *result = NULL;
317 size_t extra_len;
318 size_t start_idx;
319 size_t l;
320 size_t i;
321
322 l = _nl_ptrarray_len(objs, len);
323
324 start_idx = 0;
325 extra_len = 300 + (description ? strlen(description) : 0u);
326
327 result = _nltst_malloc0(extra_len);
328
329 _nltst_sprintf(result, &start_idx, &extra_len, ">>> [%zu] objects", l);
330 if (description) {
331 _nltst_sprintf(result, &start_idx, &extra_len, " (%s)",
332 description);
333 }
334 _nltst_sprintf(result, &start_idx, &extra_len, "\n");
335
336 for (i = 0; i < l; i++) {
337 _nl_auto_free char *s = NULL;
338 size_t slen;
339 size_t extra_len;
340
341 s = _nltst_object_to_string(objs[i]);
342 slen = strlen(s);
343
344 /* Don't bother to calculate the exact extra space. Just always
345 * reallocate enough. */
346 extra_len = slen + 100;
347 result = _nltst_assert_nonnull(
348 realloc(result, start_idx + extra_len));
349
350 _nltst_sprintf(result, &start_idx, &extra_len, ">>> [%zu] %s\n",
351 i, s);
352 }
353
354 return _nl_steal_pointer(&result);
355 }
356
357 struct cache_get_all_data {
358 struct nl_object **arr;
359 size_t len;
360 size_t idx;
361 };
362
363 static void _cache_get_all_fcn(struct nl_object *obj, void *user_data)
364 {
365 struct cache_get_all_data *data = user_data;
366 size_t i;
367
368 ck_assert(obj);
369 ck_assert_int_lt(data->idx, data->len);
370
371 for (i = 0; i < data->idx; i++)
372 ck_assert_ptr_ne(data->arr[i], obj);
373
374 data->arr[data->idx++] = obj;
375 }
376
377 struct nl_object **_nltst_cache_get_all(struct nl_cache *cache, size_t *out_len)
378 {
379 int nitems;
380 struct cache_get_all_data data = {
381 .idx = 0,
382 .len = 0,
383 };
384 size_t len2 = 0;
385 size_t i;
386 size_t j;
387
388 ck_assert(cache);
389
390 nitems = nl_cache_nitems(cache);
391 ck_assert_int_ge(nitems, 0);
392
393 data.len = nitems;
394 data.arr = malloc(sizeof(struct nl_object *) * (data.len + 1));
395 ck_assert_ptr_nonnull(data.arr);
396
397 nl_cache_foreach(cache, _cache_get_all_fcn, &data);
398
399 ck_assert_int_eq(data.idx, data.len);
400
401 ck_assert_int_le(data.len, SSIZE_MAX);
402
403 data.arr[data.len] = NULL;
404 if (out_len)
405 *out_len = data.len;
406
407 /* double check the result. */
408 for (struct nl_object *obj = nl_cache_get_first(cache); obj;
409 obj = nl_cache_get_next(obj)) {
410 ck_assert_ptr_eq(data.arr[len2], obj);
411 len2++;
412 }
413 ck_assert_ptr_null(data.arr[len2]);
414
415 for (i = 0; i < data.len; i++) {
416 ck_assert_ptr_nonnull(data.arr[i]);
417 for (j = i + 1; j < data.len; j++)
418 ck_assert_ptr_ne(data.arr[i], data.arr[j]);
419 }
420
421 return data.arr;
422 }
423
424 struct rtnl_link *_nltst_cache_get_link(struct nl_cache *cache,
425 const char *ifname)
426 {
427 _nl_auto_free struct nl_object **objs = NULL;
428 struct rtnl_link *link = NULL;
429 size_t i;
430
431 ck_assert_ptr_nonnull(cache);
432 ck_assert_ptr_nonnull(ifname);
433
434 objs = _nltst_cache_get_all(cache, NULL);
435 for (i = 0; objs[i]; i++) {
436 if (_nl_streq(rtnl_link_get_name((struct rtnl_link *)objs[i]),
437 ifname)) {
438 ck_assert_ptr_null(link);
439 link = (struct rtnl_link *)objs[i];
440 }
441 }
442
443 if (_nltst_rand_u32_range(5) == 0) {
444 _nl_auto_rtnl_link struct rtnl_link *link2 = NULL;
445
446 link2 = rtnl_link_get_by_name(cache, ifname);
447 ck_assert_ptr_eq(link2, link);
448 }
449
450 return link;
451 }
452
453 /*****************************************************************************/
454
455 struct nl_sock *_nltst_socket(int protocol)
456 {
457 struct nl_sock *sk;
458 int r;
459
460 sk = nl_socket_alloc();
461 ck_assert(sk);
462
463 r = nl_connect(sk, protocol);
464 ck_assert_int_eq(r, 0);
465
466 if (_nltst_rand_u32_range(5) == 0)
467 nl_cache_free(_nltst_rtnl_link_alloc_cache(sk, AF_UNSPEC, 0));
468
469 if (_nltst_rand_u32_range(5) == 0)
470 nl_cache_free(_nltst_rtnl_route_alloc_cache(
471 sk, _nltst_rand_select(AF_UNSPEC, AF_INET, AF_INET6)));
472
473 return sk;
474 }
475
476 void _nltst_add_link(struct nl_sock *sk, const char *ifname, const char *kind,
477 int *out_ifindex)
478 {
479 _nl_auto_nl_socket struct nl_sock *sk_free = NULL;
480 _nl_auto_rtnl_link struct rtnl_link *link = NULL;
481 _nl_auto_nl_cache struct nl_cache *cache = NULL;
482 struct rtnl_link *link2;
483 int ifindex;
484 int r;
485
486 ck_assert(ifname);
487 ck_assert(kind);
488
489 if (_nltst_rand_u32_range(5) == 0)
490 _nltst_assert_link_not_exists(ifname);
491
492 if (!sk) {
493 sk = _nltst_socket(NETLINK_ROUTE);
494 sk_free = sk;
495 }
496
497 link = rtnl_link_alloc();
498 ck_assert(link);
499
500 r = rtnl_link_set_type(link, kind);
501 ck_assert_int_eq(r, 0);
502
503 rtnl_link_set_name(link, ifname);
504
505 r = rtnl_link_add(sk, link, NLM_F_CREATE);
506 ck_assert_int_eq(r, 0);
507
508 if (!out_ifindex && _nltst_rand_u32_range(5) != 0)
509 return;
510
511 cache = _nltst_rtnl_link_alloc_cache(sk, AF_UNSPEC, 0);
512
513 link2 = _nltst_cache_get_link(cache, ifname);
514 ck_assert_ptr_nonnull(link2);
515
516 ifindex = rtnl_link_get_ifindex(link2);
517 ck_assert_int_gt(ifindex, 0);
518
519 if (out_ifindex)
520 *out_ifindex = ifindex;
521 }
522
523 void _nltst_delete_link(struct nl_sock *sk, const char *ifname)
524 {
525 _nl_auto_nl_socket struct nl_sock *sk_free = NULL;
526 _nl_auto_rtnl_link struct rtnl_link *link = NULL;
527
528 _nltst_assert_link_exists(ifname);
529
530 if (!sk) {
531 sk = _nltst_socket(NETLINK_ROUTE);
532 sk_free = sk;
533 }
534
535 if (_nltst_rand_u32_range(5) == 0) {
536 _nl_auto_nl_cache struct nl_cache *cache = NULL;
537
538 cache = _nltst_rtnl_link_alloc_cache(sk, AF_UNSPEC, 0);
539 ck_assert_ptr_nonnull(_nltst_cache_get_link(cache, ifname));
540 }
541
542 link = rtnl_link_alloc();
543 ck_assert_ptr_nonnull(link);
544
545 rtnl_link_set_name(link, ifname);
546
547 _nltst_assert_retcode(rtnl_link_delete(sk, link));
548
549 _nltst_assert_link_not_exists(ifname);
550 }
551
552 void _nltst_get_link(struct nl_sock *sk, const char *ifname, int *out_ifindex,
553 struct rtnl_link **out_link)
554 {
555 _nl_auto_nl_cache struct nl_cache *cache = NULL;
556 struct rtnl_link *link;
557
558 if (_nltst_rand_u32_range(5) == 0)
559 _nltst_assert_link_exists(ifname);
560
561 cache = _nltst_rtnl_link_alloc_cache(sk, AF_UNSPEC, 0);
562
563 link = _nltst_cache_get_link(cache, ifname);
564 ck_assert(link);
565
566 if (out_ifindex)
567 *out_ifindex = rtnl_link_get_ifindex(link);
568
569 if (out_link) {
570 nl_object_get((struct nl_object *)link);
571 *out_link = link;
572 }
573 }
574
575 void _nltst_addr4_add(struct nl_sock *sk, int ifindex, const char *ip,
576 int prefixlen)
577 {
578 _nl_auto_rtnl_addr struct rtnl_addr *addr = NULL;
579 _nl_auto_nl_addr struct nl_addr *local4 = NULL;
580
581 addr = rtnl_addr_alloc();
582 ck_assert_ptr_nonnull(addr);
583 rtnl_addr_set_ifindex(addr, ifindex);
584 rtnl_addr_set_family(addr, AF_INET);
585 ck_assert_int_eq(nl_addr_parse(ip, AF_INET, &local4), 0);
586 ck_assert_int_eq(rtnl_addr_set_local(addr, local4), 0);
587 rtnl_addr_set_prefixlen(addr, prefixlen);
588 ck_assert_int_eq(rtnl_addr_add(sk, addr, 0), 0);
589 }
590
591 void _nltst_addr6_add(struct nl_sock *sk, int ifindex, const char *ip,
592 int prefixlen)
593 {
594 _nl_auto_rtnl_addr struct rtnl_addr *addr = NULL;
595 _nl_auto_nl_addr struct nl_addr *local6 = NULL;
596
597 addr = rtnl_addr_alloc();
598 ck_assert_ptr_nonnull(addr);
599 rtnl_addr_set_ifindex(addr, ifindex);
600 rtnl_addr_set_family(addr, AF_INET6);
601 ck_assert_int_eq(nl_addr_parse(ip, AF_INET6, &local6), 0);
602 ck_assert_int_eq(rtnl_addr_set_local(addr, local6), 0);
603 rtnl_addr_set_prefixlen(addr, prefixlen);
604 ck_assert_int_eq(rtnl_addr_add(sk, addr, 0), 0);
605 }
606
607 struct nl_cache *_nltst_rtnl_link_alloc_cache(struct nl_sock *sk,
608 int addr_family, unsigned flags)
609 {
610 _nl_auto_nl_socket struct nl_sock *sk_free = NULL;
611 struct nl_cache *cache;
612 int r;
613
614 if (!sk) {
615 sk = _nltst_socket(NETLINK_ROUTE);
616 sk_free = sk;
617 }
618
619 if (flags == 0 && _nltst_rand_bool())
620 r = rtnl_link_alloc_cache(sk, addr_family, &cache);
621 else
622 r = rtnl_link_alloc_cache_flags(sk, addr_family, &cache, flags);
623
624 _nltst_assert_retcode(r);
625
626 if (_nltst_rand_u32_range(5) == 0)
627 free(_nltst_cache_get_all(cache, NULL));
628
629 return _nltst_assert(cache);
630 }
631
632 struct nl_cache *_nltst_rtnl_route_alloc_cache(struct nl_sock *sk,
633 int addr_family)
634 {
635 struct nl_cache *cache;
636
637 ck_assert_ptr_nonnull(sk);
638 ck_assert(addr_family == AF_UNSPEC || addr_family == AF_INET ||
639 addr_family == AF_INET6);
640
641 _nltst_assert_retcode(
642 rtnl_route_alloc_cache(sk, addr_family, 0, &cache));
643
644 if (_nltst_rand_u32_range(5) == 0)
645 free(_nltst_cache_get_all(cache, NULL));
646
647 return _nltst_assert(cache);
648 }
649
650 /*****************************************************************************/
651
652 char *_nltst_strtok(const char **p_str)
653 {
654 const char *str;
655 _nl_auto_free char *dst = NULL;
656 size_t dst_len = 0;
657 size_t dst_alloc = 0;
658 size_t i;
659
660 ck_assert_ptr_nonnull(p_str);
661
662 str = _nltst_str_skip_space(*p_str);
663
664 if (str[0] == '\0') {
665 *p_str = str;
666 return NULL;
667 }
668
669 dst_len = 0;
670 dst_alloc = 10;
671 dst = malloc(dst_alloc);
672 ck_assert_ptr_nonnull(dst);
673
674 i = 0;
675 while (true) {
676 char ch1 = '\0';
677 char ch2 = '\0';
678
679 /* We take the first word, up until whitespace. Note that backslash
680 * escape is honored, so you can backslash escape spaces. The returned
681 * string will NOT have backslashes removed. */
682
683 if (str[i] == '\0') {
684 *p_str = &str[i];
685 break;
686 }
687 if (_nltst_char_is_space(str[i])) {
688 *p_str = _nltst_str_skip_space(&str[i + 1]);
689 break;
690 }
691 ch1 = str[i];
692 if (str[i] == '\\') {
693 if (str[i + 1] != '\0') {
694 ch2 = str[i + 1];
695 i += 2;
696 } else
697 i += 1;
698 } else
699 i += 1;
700
701 if (dst_len + 3 >= dst_alloc) {
702 dst_alloc *= 2;
703 dst = realloc(dst, dst_alloc);
704 ck_assert_ptr_nonnull(dst);
705 }
706 dst[dst_len++] = ch1;
707 if (ch2 != '\0')
708 dst[dst_len++] = ch2;
709 }
710
711 ck_assert_int_gt(dst_len, 0);
712 return strndup(dst, dst_len);
713 }
714
715 char **_nltst_strtokv(const char *str)
716 {
717 _nl_auto_free char *s = NULL;
718 _nltst_auto_strfreev char **result = NULL;
719 size_t r_len = 0;
720 size_t r_alloc = 0;
721
722 if (!str)
723 return NULL;
724
725 r_alloc = 4;
726 result = malloc(sizeof(char *) * r_alloc);
727 ck_assert_ptr_nonnull(result);
728
729 while ((s = _nltst_strtok(&str))) {
730 if (r_len + 2 >= r_alloc) {
731 r_alloc *= 2;
732 result = realloc(result, sizeof(char *) * r_alloc);
733 ck_assert_ptr_nonnull(result);
734 }
735 result[r_len++] = _nl_steal_pointer(&s);
736 }
737 ck_assert_int_lt(r_len, r_alloc);
738 result[r_len] = NULL;
739 return _nl_steal_pointer(&result);
740 }
741
742 /*****************************************************************************/
743
744 void _nltst_assert_link_exists_full(const char *ifname, bool exists)
745 {
746 _nl_auto_nl_cache struct nl_cache *cache = NULL;
747 _nl_auto_rtnl_link struct rtnl_link *link_clone = NULL;
748 struct rtnl_link *link;
749 char path[100];
750 struct stat st;
751 int rnd;
752 int r;
753
754 ck_assert_pstr_ne(ifname, NULL);
755 ck_assert_int_lt(strlen(ifname), IFNAMSIZ);
756
757 strcpy(path, "/sys/class/net/");
758 strcat(path, ifname);
759 ck_assert_int_lt(strlen(path), sizeof(path));
760
761 r = stat(path, &st);
762 if (exists) {
763 if (r != 0) {
764 const int errsv = (errno);
765
766 ck_assert_msg(
767 0,
768 "link(%s) does not exist (stat(%s) failed with r=%d, errno=%d (%s))",
769 ifname, path, r, errsv, strerror(errsv));
770 }
771 } else {
772 if (r != -1 && errno != ENOENT) {
773 const int errsv = (errno);
774
775 ck_assert_msg(
776 0,
777 "link(%s) should not exist but stat(%s) gave r=%d, errno=%d (%s)",
778 ifname, path, r, errsv, strerror(errsv));
779 }
780 }
781
782 rnd = _nltst_rand_u32_range(3);
783
784 if (rnd == 0)
785 return;
786
787 cache = _nltst_rtnl_link_alloc_cache(NULL, AF_UNSPEC, 0);
788
789 link = _nltst_cache_get_link(cache, ifname);
790 if (exists)
791 ck_assert_ptr_nonnull(link);
792 else
793 ck_assert_ptr_null(link);
794
795 if (!link || rnd == 1)
796 return;
797
798 link_clone =
799 (struct rtnl_link *)nl_object_clone((struct nl_object *)link);
800 ck_assert(link_clone);
801
802 /* FIXME: we would expect that the cloned object is identical. It is not. */
803 /* _nltst_object_identical(link, link_clone); */
804 }
805
806 /*****************************************************************************/
807
808 bool _nltst_in_ci(void)
809 {
810 return _nl_streq0(getenv("NLTST_IN_CI"), "1");
811 }
812
813 /*****************************************************************************/
814
815 bool _nltst_has_iproute2(void)
816 {
817 static int has = -1;
818
819 if (has == -1)
820 has = (system("ip link &>/dev/null") == 0);
821
822 return has;
823 }
824
825 bool _nltst_skip_no_iproute2(const char *msg)
826 {
827 if (_nltst_has_iproute2())
828 return false;
829
830 ck_assert_msg(
831 !_nltst_in_ci(),
832 "We seem to not have iproute2, but we are in NLTST_IN_CI=1. This is fatal.");
833
834 printf("skip test due to missing iproute2%s%s%s\n", msg ? " (" : "",
835 msg ?: "", msg ? ")" : "");
836 return true;
837 }
838
839 /*****************************************************************************/
840
841 void _nltst_add_dummy_and_up(struct nl_sock *sk, const char *ifname,
842 int *out_ifindex)
843 {
844 _nl_auto_rtnl_link struct rtnl_link *link_obj = NULL;
845 _nl_auto_rtnl_link struct rtnl_link *change = NULL;
846
847 /* Add the link */
848 _nltst_add_link(sk, ifname, "dummy", out_ifindex);
849
850 /* Bring the link up */
851 _nltst_get_link(sk, ifname, NULL, &link_obj);
852 change = rtnl_link_alloc();
853 ck_assert_ptr_nonnull(change);
854 rtnl_link_set_flags(change, IFF_UP);
855 ck_assert_int_eq(rtnl_link_change(sk, link_obj, change, 0), 0);
856 }
857
858 void _nltst_add_dummy_v4_with_addr(struct nl_sock *sk, const char *ifname,
859 int *out_ifindex, const char *ip,
860 int prefixlen)
861 {
862 int ifindex_local;
863
864 _nltst_add_dummy_and_up(sk, ifname, &ifindex_local);
865 _nltst_addr4_add(sk, ifindex_local, ip, prefixlen);
866 if (out_ifindex)
867 *out_ifindex = ifindex_local;
868 }
869
870 void _nltst_add_dummy_v6_with_addr(struct nl_sock *sk, const char *ifname,
871 int *out_ifindex, const char *ip,
872 int prefixlen)
873 {
874 int ifindex_local;
875
876 _nltst_add_dummy_and_up(sk, ifname, &ifindex_local);
877 _nltst_addr6_add(sk, ifindex_local, ip, prefixlen);
878 if (out_ifindex)
879 *out_ifindex = ifindex_local;
880 }
881
882 /*****************************************************************************/
883
884 void _nltst_select_route_clear(NLTstSelectRoute *select_route)
885 {
886 _nltst_assert_select_route(select_route);
887
888 _nl_clear_free(&select_route->addr);
889 _nl_clear_free(&select_route->addr_pattern);
890 }
891
892 int _nltst_select_route_cmp(const NLTstSelectRoute *select_route1,
893 const NLTstSelectRoute *select_route2)
894 {
895 _NL_CMP_SELF(select_route1, select_route2);
896 _NL_CMP_FIELD_STR0(select_route1, select_route2, addr);
897 _NL_CMP_FIELD_STR0(select_route1, select_route2, addr_pattern);
898 _NL_CMP_FIELD(select_route1, select_route2, addr_family);
899 _NL_CMP_FIELD(select_route1, select_route2, ifindex);
900 _NL_CMP_FIELD(select_route1, select_route2, plen);
901 return 0;
902 }
903
904 char *_nltst_select_route_to_string(const NLTstSelectRoute *select_route)
905 {
906 char buf[1024];
907 const char *family;
908 char b_plen[100];
909
910 _nltst_assert_select_route(select_route);
911
912 if (select_route->addr_family == AF_INET)
913 family = "4 ";
914 else if (select_route->addr_family == AF_INET6)
915 family = "6 ";
916 else
917 family = "";
918
919 b_plen[0] = '\0';
920 if (select_route->plen != -1)
921 _nltst_sprintf_arr(b_plen, "/%d", select_route->plen);
922
923 _nltst_sprintf_arr(buf,
924 "%s"
925 "%s"
926 "%s"
927 "",
928 family,
929 select_route->addr_pattern ?: select_route->addr,
930 b_plen);
931 return _nltst_strdup(buf);
932 }
933
934 void _nltst_select_route_parse(const char *str,
935 NLTstSelectRoute *out_select_route)
936 {
937 _nltst_auto_strfreev char **tokens0 = NULL;
938 const char *const *tokens;
939 int addr_family = AF_UNSPEC;
940 int addr_family2 = AF_UNSPEC;
941 NLTstIPAddr addr;
942 int plen = -1;
943 _nl_auto_free char *addr_free = NULL;
944 const char *s_addr_pattern;
945 const char *s_addr = NULL;
946 const char *s;
947 const char *s1;
948
949 ck_assert_ptr_nonnull(str);
950 _nltst_assert_select_route(out_select_route);
951
952 tokens0 = _nltst_strtokv(str);
953 tokens = (const char *const *)tokens0;
954
955 s = tokens[0];
956 if (!s)
957 ck_abort_msg("invalid empty route pattern \"%s\"", str);
958 if (_nl_streq(s, "4") || _nl_streq(s, "inet") ||
959 _nl_streq(s, "inet4")) {
960 addr_family = AF_INET;
961 tokens++;
962 } else if (_nl_streq(s, "6") || _nl_streq(s, "inet6")) {
963 addr_family = AF_INET6;
964 tokens++;
965 }
966
967 s_addr_pattern = tokens[0];
968 if (!s_addr_pattern) {
969 ck_abort_msg(
970 "the route pattern \"%s\" is invalid and contains no destination address",
971 str);
972 }
973 tokens++;
974
975 s = strchr(s_addr_pattern, '/');
976 if (s) {
977 long int plen2;
978
979 if (s == s_addr_pattern) {
980 ck_abort_msg(
981 "the route pattern \"%s\" contains no valid destination address",
982 str);
983 }
984 addr_free = strndup(s_addr_pattern, s - s_addr_pattern);
985 s_addr_pattern = addr_free;
986 s++;
987
988 errno = 0;
989 plen2 = strtol(s, (char **)&s1, 10);
990 if (errno != 0 || s1[0] != '\0' || plen2 < 0 || plen2 > 128 ||
991 ((_nltst_str_find_first_not_from_charset(
992 s, "0123456789"))[0] != '\0')) {
993 ck_abort_msg(
994 "the route pattern \"%s\" contains no valid destination address",
995 str);
996 }
997 plen = plen2;
998 }
999 if ((_nltst_str_find_first_not_from_charset(
1000 s_addr_pattern, "abcdefABCDEF0123456789:.?*"))[0] != '\0') {
1001 ck_abort_msg(
1002 "the route pattern \"%s\" contains no valid destination address",
1003 str);
1004 }
1005 if (_nltst_inet_pton(addr_family, s_addr_pattern, &addr_family2,
1006 &addr)) {
1007 free(addr_free);
1008 addr_free = _nltst_inet_ntop_dup(addr_family2, &addr);
1009 s_addr_pattern = addr_free;
1010 addr_family = addr_family2;
1011 } else {
1012 if (addr_family == AF_UNSPEC) {
1013 ck_abort_msg(
1014 "the route pattern \"%s\" contains a wild card address, it requires the address family",
1015 str);
1016 }
1017 }
1018
1019 ck_assert(addr_family == AF_INET || addr_family == AF_INET6);
1020
1021 if (plen > (addr_family == AF_INET ? 32 : 128)) {
1022 ck_abort_msg(
1023 "the route pattern \"%s\" contains no valid destination address (prefix length too large)",
1024 str);
1025 }
1026 ck_assert_int_ge(plen, -1);
1027
1028 s = tokens[0];
1029 if (s) {
1030 ck_abort_msg("the route pattern \"%s\" contains extra tokens",
1031 str);
1032 }
1033
1034 if (_nltst_inet_valid(addr_family, s_addr_pattern))
1035 _NL_SWAP(&s_addr, &s_addr_pattern);
1036
1037 _nltst_select_route_clear(out_select_route);
1038 memset(out_select_route, 0, sizeof(*out_select_route));
1039 *out_select_route = (NLTstSelectRoute){
1040 .addr_family = addr_family,
1041 .plen = plen,
1042 .ifindex = 0,
1043 .addr = s_addr ? strdup(s_addr) : NULL,
1044 .addr_pattern = s_addr_pattern ? strdup(s_addr_pattern) : NULL,
1045 };
1046 ck_assert(!s_addr || out_select_route->addr);
1047 ck_assert(!s_addr_pattern || out_select_route->addr_pattern);
1048 _nltst_assert_select_route(out_select_route);
1049 }
1050
1051 bool _nltst_select_route_match(struct nl_object *route,
1052 const NLTstSelectRoute *select_route,
1053 bool do_assert)
1054 {
1055 struct nl_addr *addr;
1056 struct rtnl_route *route_;
1057 int i;
1058 char sbuf1[200];
1059
1060 ck_assert_ptr_nonnull(route);
1061 ck_assert_str_eq(nl_object_get_type(route), "route/route");
1062 ck_assert_ptr_nonnull(select_route);
1063
1064 route_ = (struct rtnl_route *)route;
1065
1066 _nltst_assert_select_route(select_route);
1067
1068 #define _check(cond, msg, ...) \
1069 do { \
1070 if (do_assert) { \
1071 _nl_auto_free char *s1 = NULL; \
1072 _nl_auto_free char *s2 = NULL; \
1073 \
1074 ck_assert_msg( \
1075 (cond), \
1076 "Checking condition \"%s\" for route \"%s\" (expected \"%s\") failed (msg: " msg \
1077 ")", \
1078 #cond, (s1 = _nltst_object_to_string(route)), \
1079 (s2 = _nltst_select_route_to_string( \
1080 select_route)), \
1081 ##__VA_ARGS__); \
1082 } else if (cond) { \
1083 } else { \
1084 return false; \
1085 } \
1086 } while (0)
1087
1088 if (select_route->addr_family != AF_UNSPEC) {
1089 _check(rtnl_route_get_family(route_) ==
1090 select_route->addr_family,
1091 "mismatching address family");
1092 }
1093
1094 if (select_route->ifindex != 0) {
1095 struct nl_list_head *list;
1096 struct rtnl_nexthop *nh;
1097 size_t n;
1098 struct rtnl_nexthop *nh2;
1099
1100 list = rtnl_route_get_nexthops(route_);
1101 _check(list, "no nexthops for ifindex");
1102
1103 n = 0;
1104 nl_list_for_each_entry(nh, list, rtnh_list) {
1105 nh2 = nh;
1106 n++;
1107 }
1108 _check(n == 1, "expects one nexthop for ifindex but got %zu",
1109 n);
1110 ck_assert_ptr_nonnull(nh2);
1111
1112 i = rtnl_route_nh_get_ifindex(nh2);
1113 _check(i == select_route->ifindex,
1114 "route has unexpected ifindex %d for next hop", i);
1115 }
1116
1117 addr = rtnl_route_get_dst(route_);
1118
1119 if (addr) {
1120 if (select_route->addr_family != AF_UNSPEC) {
1121 _check(nl_addr_get_family(addr) ==
1122 select_route->addr_family,
1123 "unexecpted address family of dst");
1124 }
1125 }
1126
1127 if (select_route->plen != -1) {
1128 _check(addr, "missing address");
1129 _check(nl_addr_get_prefixlen(addr) ==
1130 (unsigned)select_route->plen,
1131 "unexpected prefix length");
1132 }
1133 if (select_route->addr || select_route->addr_pattern) {
1134 _check(addr, "missing address");
1135
1136 _nl_inet_ntop(nl_addr_get_family(addr),
1137 nl_addr_get_binary_addr(addr), sbuf1);
1138
1139 ck_assert(strlen(sbuf1) > 0);
1140 ck_assert(strlen(sbuf1) < sizeof(sbuf1));
1141
1142 if (select_route->addr) {
1143 _check(_nl_streq(sbuf1, select_route->addr),
1144 "unexpected address, \"%s\" does not match \"%s\"",
1145 sbuf1, select_route->addr);
1146 }
1147 if (select_route->addr_pattern) {
1148 _check(fnmatch(select_route->addr_pattern, sbuf1, 0) ==
1149 0,
1150 "unexpected address, \"%s\" does not match pattern \"%s\"",
1151 sbuf1, select_route->addr_pattern);
1152 }
1153 }
1154
1155 #undef _check
1156
1157 return true;
1158 }
1159
1160 /*****************************************************************************/
1161
1162 static void _nltst_assert_route_list_print(struct nl_object *const *objs,
1163 size_t l_objs,
1164 const char *const *expected_routes,
1165 size_t l_expected)
1166 {
1167 _nl_auto_free char *s2 =
1168 _nltst_objects_to_string("route-list", objs, l_objs);
1169 size_t j;
1170
1171 printf("route content: %s", s2);
1172 printf("expected routes: %zu\n", l_expected);
1173 for (j = 0; j < l_expected; j++) {
1174 printf("expected route: [%zu] %s\n", j, expected_routes[j]);
1175 }
1176 printf("ip-route:>>>\n");
1177 _nltst_system("ip -d -4 route show table all");
1178 _nltst_system("ip -d -6 route show table all");
1179 printf("<<<\n");
1180 }
1181
1182 static bool
1183 _nltst_assert_route_list_equal(struct nl_object *const *objs,
1184 const NLTstSelectRoute *expected_route_selects,
1185 size_t len)
1186 {
1187 size_t i;
1188
1189 for (i = 0; i < len; i++) {
1190 struct nl_object *route = objs[i];
1191 const NLTstSelectRoute *select_route =
1192 &expected_route_selects[i];
1193
1194 if (!_nltst_select_route_match(route, select_route, false))
1195 return false;
1196 }
1197 return true;
1198 }
1199
1200 typedef struct {
1201 const NLTstSelectRoute *expected_route_selects;
1202 } NltstAssertRouteListPermData;
1203
1204 static bool
1205 _nltst_assert_route_list_permutate(const NltstAssertRouteListPermData *data,
1206 struct nl_object **objs, size_t idx,
1207 size_t num)
1208 {
1209 size_t i;
1210
1211 if (idx + 1 == num)
1212 return true;
1213
1214 for (i = idx; i < num; i++) {
1215 if (!_nltst_select_route_match(
1216 objs[i], &data->expected_route_selects[idx],
1217 false)) {
1218 /* This entry does not match. We can shortcut this permutation. */
1219 continue;
1220 }
1221 _nl_swap(&objs[idx], &objs[i]);
1222 if (_nltst_assert_route_list_permutate(data, objs, idx + 1,
1223 num)) {
1224 /* This is a permutation that matches. Leave objs in
1225 * this order and return */
1226 return true;
1227 }
1228 _nl_swap(&objs[idx], &objs[i]);
1229 }
1230 return false;
1231 }
1232
1233 void _nltst_assert_route_list(struct nl_object *const *objs, ssize_t len,
1234 const char *const *expected_routes)
1235 {
1236 const size_t l_expected = _nl_ptrarray_len(expected_routes, -1);
1237 const size_t l_objs = _nl_ptrarray_len(objs, len);
1238 _nl_auto_free NLTstSelectRoute *expected_route_selects = NULL;
1239 _nl_auto_free struct nl_object **objs2 = NULL;
1240 size_t i;
1241
1242 if (l_expected != l_objs)
1243 goto out_fail;
1244
1245 if (l_objs == 0)
1246 goto out_free;
1247
1248 objs2 = _nltst_assert_nonnull(
1249 _nl_memdup(objs, sizeof(struct nl_object *) * l_objs));
1250
1251 expected_route_selects =
1252 _nltst_malloc0(sizeof(NLTstSelectRoute) * (l_expected + 1u));
1253 for (i = 0; i < l_expected; i++) {
1254 _nltst_select_route_parse(expected_routes[i],
1255 &expected_route_selects[i]);
1256 }
1257
1258 /* Permutate through the list of objects and check that we find at
1259 * least one match with the list of expected routes. */
1260 if (!_nltst_assert_route_list_permutate(
1261 &((const NltstAssertRouteListPermData){
1262 .expected_route_selects = expected_route_selects,
1263 }),
1264 objs2, 0, l_objs))
1265 goto out_fail;
1266
1267 if (!_nltst_assert_route_list_equal(objs2, expected_route_selects,
1268 len)) {
1269 _nltst_assert_route_list_print(objs, l_objs, expected_routes,
1270 l_expected);
1271 ck_abort_msg(
1272 "there is a in _nltst_assert_route_list_permutate(), the permutation should now match");
1273 }
1274
1275 goto out_free;
1276
1277 out_fail:
1278 _nltst_assert_route_list_print(objs, l_objs, expected_routes,
1279 l_expected);
1280 ck_abort_msg(
1281 "The list of %zu routes did not find a one-to-one match with the list of %zu expected routes",
1282 l_objs, l_expected);
1283
1284 out_free:
1285 if (expected_route_selects) {
1286 for (i = 0; i < l_expected; i++) {
1287 _nltst_select_route_clear(&expected_route_selects[i]);
1288 }
1289 }
1290 }
1291
1292 void _nltst_assert_route_cache_v(struct nl_cache *cache,
1293 const char *const *expected_routes)
1294 {
1295 _nl_auto_free struct nl_object **objs = NULL;
1296 size_t len;
1297
1298 ck_assert(cache);
1299 ck_assert(expected_routes);
1300
1301 objs = _nltst_cache_get_all(cache, &len);
1302
1303 _nltst_assert_route_list(objs, len, expected_routes);
1304 }