a4d3faf081a57d27ee0a2b1b3e59975e256439c2
[vpp.git] / src / plugins / linux-cp / lcp.c
1 /*
2  * Copyright (c) 2020 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <sched.h>
17 #include <fcntl.h>
18 #include <ctype.h>
19 #include <sys/socket.h>
20 #include <net/if.h>
21
22 #include <plugins/linux-cp/lcp.h>
23
24 lcp_main_t lcp_main;
25
26 u8 *
27 lcp_get_default_ns (void)
28 {
29   lcp_main_t *lcpm = &lcp_main;
30
31   if (!lcpm->default_namespace || lcpm->default_namespace[0] == 0)
32     return NULL;
33
34   return lcpm->default_namespace;
35 }
36
37 int
38 lcp_get_default_ns_fd (void)
39 {
40   lcp_main_t *lcpm = &lcp_main;
41
42   return lcpm->default_ns_fd;
43 }
44
45 /*
46  * ns is expected to be or look like a NUL-terminated C string.
47  */
48 int
49 lcp_set_default_ns (u8 *ns)
50 {
51   lcp_main_t *lcpm = &lcp_main;
52   char *p;
53   int len;
54   u8 *s;
55
56   p = (char *) ns;
57   len = clib_strnlen (p, LCP_NS_LEN);
58   if (len >= LCP_NS_LEN)
59     return -1;
60
61   if (!p || *p == 0)
62     {
63       lcpm->default_namespace = NULL;
64       if (lcpm->default_ns_fd > 0)
65         close (lcpm->default_ns_fd);
66       lcpm->default_ns_fd = 0;
67       return 0;
68     }
69
70   vec_validate_init_c_string (lcpm->default_namespace, p,
71                               clib_strnlen (p, LCP_NS_LEN));
72   s = format (0, "/var/run/netns/%s%c", (char *) lcpm->default_namespace, 0);
73   lcpm->default_ns_fd = open ((char *) s, O_RDONLY);
74   vec_free (s);
75
76   return 0;
77 }
78
79 /*
80  * fd.io coding-style-patch-verification: ON
81  *
82  * Local Variables:
83  * eval: (c-set-style "gnu")
84  * End:
85  */