1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2017 Petr Vorel <pvorel@suse.cz>
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 #define TST_NO_DEFAULT_MAIN
10 #include "tst_test.h"
11
12 #include "tst_net.h"
13 #include "tst_private.h"
14
15 #define DEFAULT_IPV4_PREFIX 24
16 #define DEFAULT_IPV6_PREFIX 64
17
usage(const char * cmd)18 static void usage(const char *cmd)
19 {
20 fprintf(stderr, "USAGE:\n"
21 "%s IP_LHOST[/PREFIX]\n"
22 "%s -r IP_RHOST[/PREFIX]\n"
23 "%s -h\n\n"
24 "Set IP variables without prefix and prefix for given IP.\n"
25 "EXPORTED VARIABLES:\n"
26 "Export one of the following variables without /prefix:\n"
27 "IPV4_LHOST: IPv4 address of the local host\n"
28 "IPV4_RHOST: IPv4 address of the remote host\n"
29 "IPV6_LHOST: IPv6 address of the local host\n"
30 "IPV6_RHOST: IPv6 address of the remote host\n"
31 "Export one of the following variables:\n"
32 "IPV4_LPREFIX: IPv4 prefix for IPV4_LNETWORK\n"
33 "IPV4_RPREFIX: IPv4 prefix for IPV4_RNETWORK\n"
34 "IPV6_LPREFIX: IPv6 prefix for IPV6_LNETWORK\n"
35 "IPV6_RPREFIX: IPv6 prefix for IPV6_RNETWORK\n"
36 "Default IPv4 prefix: %d.\n"
37 "Default IPv6 prefix: %d.\n\n"
38 "PARAMS:\n"
39 "-h this help\n"
40 "-r export remote environment variables\n",
41 cmd, cmd, cmd, DEFAULT_IPV4_PREFIX, DEFAULT_IPV6_PREFIX);
42 }
43
print_ivar(const char * name,unsigned int val)44 static void print_ivar(const char *name, unsigned int val)
45 {
46 printf("export %s=%d\n", name, val);
47 }
48
main(int argc,char * argv[])49 int main(int argc, char *argv[])
50 {
51 char *ip_str = NULL, *prefix_str = NULL;
52 int is_ipv6, is_rhost = 0, prefix;
53 struct in_addr ip;
54 struct in6_addr ip6;
55
56 int is_usage = argc > 1 && (!strcmp(argv[1], "-h") ||
57 !strcmp(argv[1], "--help"));
58 if (argc < 2 || is_usage) {
59 usage(argv[0]);
60 exit(is_usage ? EXIT_SUCCESS : EXIT_FAILURE);
61 }
62 if (!strcmp(argv[1], "-r"))
63 is_rhost = 1;
64
65 ip_str = argv[is_rhost ? 2 : 1];
66 is_ipv6 = !!strchr(ip_str, ':');
67
68 prefix_str = strchr(ip_str, '/');
69
70 if (prefix_str)
71 prefix = tst_get_prefix(ip_str, is_ipv6);
72 else
73 prefix = is_ipv6 ? DEFAULT_IPV6_PREFIX : DEFAULT_IPV4_PREFIX;
74
75 /* checks for validity of IP string */
76 if (is_ipv6)
77 tst_get_in6_addr(ip_str, &ip6);
78 else
79 tst_get_in_addr(ip_str, &ip);
80
81 if (is_ipv6) {
82 print_ivar(is_rhost ? "IPV6_RPREFIX" : "IPV6_LPREFIX", prefix);
83 tst_print_svar(is_rhost ? "IPV6_RHOST" : "IPV6_LHOST", ip_str);
84 } else {
85 print_ivar(is_rhost ? "IPV4_RPREFIX" : "IPV4_LPREFIX", prefix);
86 tst_print_svar(is_rhost ? "IPV4_RHOST" : "IPV4_LHOST", ip_str);
87 }
88
89 exit(EXIT_SUCCESS);
90 }
91