...
1 package netlink
2
3
4
5
6
7
8
9
10
11
12
13
14
15 import (
16 "fmt"
17
18 "github.com/vishvananda/netlink/nl"
19 "golang.org/x/sys/unix"
20 )
21
22
23 const (
24 _ = iota
25 NETNSA_NSID
26 NETNSA_PID
27 NETNSA_FD
28 )
29
30
31
32 func (h *Handle) GetNetNsIdByPid(pid int) (int, error) {
33 return h.getNetNsId(NETNSA_PID, uint32(pid))
34 }
35
36
37
38 func GetNetNsIdByPid(pid int) (int, error) {
39 return pkgHandle.GetNetNsIdByPid(pid)
40 }
41
42
43
44 func (h *Handle) SetNetNsIdByPid(pid, nsid int) error {
45 return h.setNetNsId(NETNSA_PID, uint32(pid), uint32(nsid))
46 }
47
48
49
50 func SetNetNsIdByPid(pid, nsid int) error {
51 return pkgHandle.SetNetNsIdByPid(pid, nsid)
52 }
53
54
55
56
57 func (h *Handle) GetNetNsIdByFd(fd int) (int, error) {
58 return h.getNetNsId(NETNSA_FD, uint32(fd))
59 }
60
61
62
63
64 func GetNetNsIdByFd(fd int) (int, error) {
65 return pkgHandle.GetNetNsIdByFd(fd)
66 }
67
68
69
70
71 func (h *Handle) SetNetNsIdByFd(fd, nsid int) error {
72 return h.setNetNsId(NETNSA_FD, uint32(fd), uint32(nsid))
73 }
74
75
76
77
78 func SetNetNsIdByFd(fd, nsid int) error {
79 return pkgHandle.SetNetNsIdByFd(fd, nsid)
80 }
81
82
83
84 func (h *Handle) getNetNsId(attrType int, val uint32) (int, error) {
85 req := h.newNetlinkRequest(unix.RTM_GETNSID, unix.NLM_F_REQUEST)
86
87 rtgen := nl.NewRtGenMsg()
88 req.AddData(rtgen)
89
90 b := make([]byte, 4)
91 native.PutUint32(b, val)
92 attr := nl.NewRtAttr(attrType, b)
93 req.AddData(attr)
94
95 msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNSID)
96
97 if err != nil {
98 return 0, err
99 }
100
101 for _, m := range msgs {
102 msg := nl.DeserializeRtGenMsg(m)
103
104 attrs, err := nl.ParseRouteAttr(m[msg.Len():])
105 if err != nil {
106 return 0, err
107 }
108
109 for _, attr := range attrs {
110 switch attr.Attr.Type {
111 case NETNSA_NSID:
112 return int(int32(native.Uint32(attr.Value))), nil
113 }
114 }
115 }
116
117 return 0, fmt.Errorf("unexpected empty result")
118 }
119
120
121
122
123 func (h *Handle) setNetNsId(attrType int, val uint32, newnsid uint32) error {
124 req := h.newNetlinkRequest(unix.RTM_NEWNSID, unix.NLM_F_REQUEST|unix.NLM_F_ACK)
125
126 rtgen := nl.NewRtGenMsg()
127 req.AddData(rtgen)
128
129 b := make([]byte, 4)
130 native.PutUint32(b, val)
131 attr := nl.NewRtAttr(attrType, b)
132 req.AddData(attr)
133
134 b1 := make([]byte, 4)
135 native.PutUint32(b1, newnsid)
136 attr1 := nl.NewRtAttr(NETNSA_NSID, b1)
137 req.AddData(attr1)
138
139 _, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNSID)
140 return err
141 }
142
View as plain text