-
Notifications
You must be signed in to change notification settings - Fork 0
/
genl_hub.go
executable file
·368 lines (340 loc) · 8.3 KB
/
genl_hub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// +build linux
package nlgo
import (
"fmt"
"log"
"sync"
"syscall"
"unsafe"
)
type GenlMessage struct {
Header syscall.NlMsghdr
Genl *GenlMsghdr
Family string
Payload []byte // fixe header + attributes
Error error
}
type GenlListener interface {
GenlListen(GenlMessage)
}
type groupKey struct {
Family string
Name string
}
// GenlHub is generic netlink version of RtHub.
type GenlHub struct {
sock *NlSock
lock *sync.Mutex
familyIds map[uint16]GenlFamily
groupIds map[uint32]GenlGroup
membership []uint32
unicast map[uint32]chan GenlMessage
multicast map[groupKey][]GenlListener
}
func (self *GenlHub) join(group uint32) error {
for _, member := range self.membership {
if member == group {
return nil
}
}
self.membership = append(self.membership, group)
return NlSocketAddMembership(self.sock, int(group))
}
func (self *GenlHub) leave(group uint32) error {
var active []uint32
hit := false
for _, member := range self.membership {
if member == group {
hit = true
} else {
active = append(active, member)
}
}
self.membership = active
if hit {
return NlSocketDropMembership(self.sock, int(group))
}
return nil
}
func (self *GenlHub) sync() error {
var active []uint32
for gkey, _ := range self.multicast {
for _, ginfo := range self.groupIds {
if ginfo.Family == gkey.Family && ginfo.Name == gkey.Name {
active = append(active, ginfo.Id)
}
}
}
for _, old := range self.membership {
drop := true
for _, new := range active {
if new == old {
drop = false
}
}
if drop {
if err := self.leave(old); err != nil {
return err
}
}
}
for _, new := range active {
join := true
for _, old := range self.membership {
if new == old {
join = false
}
}
if join {
if err := self.join(new); err != nil {
return err
}
}
}
return nil
}
func NewGenlHub() (*GenlHub, error) {
self := &GenlHub{
sock: NlSocketAlloc(),
lock: &sync.Mutex{},
familyIds: map[uint16]GenlFamily{
GENL_ID_CTRL: GenlFamily{
Id: GENL_ID_CTRL,
Name: "nlctrl",
Version: 1,
},
},
groupIds: map[uint32]GenlGroup{
GENL_ID_CTRL: GenlGroup{
Id: GENL_ID_CTRL,
Family: "nlctrl",
Name: "notify",
},
},
unicast: make(map[uint32]chan GenlMessage),
multicast: make(map[groupKey][]GenlListener),
}
if err := NlConnect(self.sock, syscall.NETLINK_GENERIC); err != nil {
NlSocketFree(self.sock)
return nil, err
}
go func() {
feed := func(msg GenlMessage) {
seq := msg.Header.Seq
if seq == 0 { // multicast
var listeners []GenlListener
self.lock.Lock()
if family, ok := self.familyIds[msg.Header.Type]; ok {
for gkey, ls := range self.multicast {
if gkey.Family == family.Name {
for _, listener := range ls {
if ok := func() bool { // remove duplicate
for _, li := range listeners {
if li == listener {
return false
}
}
return true
}(); ok {
listeners = append(listeners, listener)
}
}
}
}
} else {
log.Print("got unknown family message")
}
self.lock.Unlock()
for _, listener := range listeners {
listener.GenlListen(msg)
}
} else {
self.lock.Lock()
listener := self.unicast[seq]
self.lock.Unlock()
if listener != nil {
listener <- msg
mtype := msg.Header.Type
if mtype == syscall.NLMSG_DONE || mtype == syscall.NLMSG_ERROR { // NlSock.Flags NL_NO_AUTO_ACK is 0 by default
self.lock.Lock()
delete(self.unicast, seq)
self.lock.Unlock()
close(listener)
}
}
}
}
for {
buf := make([]byte, syscall.Getpagesize())
if bufN, _, err := syscall.Recvfrom(self.sock.Fd, buf, syscall.MSG_TRUNC); err != nil {
if e, ok := err.(syscall.Errno); ok && e.Temporary() {
continue
}
feed(GenlMessage{Error: err})
return
} else if bufN > len(buf) {
feed(GenlMessage{Error: fmt.Errorf("msg trunc")})
return
} else if msgs, err := syscall.ParseNetlinkMessage(buf[:bufN]); err != nil {
feed(GenlMessage{Error: err})
return
} else {
for _, msg := range msgs {
switch msg.Header.Type {
default:
feed(GenlMessage{
Header: msg.Header,
Family: self.familyIds[msg.Header.Type].Name,
Genl: (*GenlMsghdr)(unsafe.Pointer(&msg.Data[0])),
Payload: msg.Data[GENL_HDRLEN:],
})
case syscall.NLMSG_ERROR:
err := *(*syscall.NlMsgerr)(unsafe.Pointer(&msg.Data[0]))
feed(GenlMessage{
Header: msg.Header,
Error: MsgError{In: err},
})
case syscall.NLMSG_DONE:
feed(GenlMessage{
Header: msg.Header,
Genl: nil,
Payload: msg.Data,
})
}
}
}
}
}()
self.Add("nlctrl", "notify", self)
if res, err := self.Request("nlctrl", CTRL_VERSION, CTRL_CMD_GETFAMILY, syscall.NLM_F_DUMP, nil, nil); err != nil {
return nil, err
} else {
for _, r := range res {
self.GenlListen(r)
}
}
return self, nil
}
func (self GenlHub) Close() {
NlSocketFree(self.sock)
}
func (self GenlHub) GenlListen(msg GenlMessage) {
if msg.Header.Type != GENL_ID_CTRL {
return
}
family := GenlFamily{}
groups := make(map[uint32]GenlGroup)
if attrs, err := CtrlPolicy.Parse(msg.Payload); err != nil {
log.Print(err)
} else if amap, ok := attrs.(AttrMap); !ok {
fmt.Printf("unknown genl family structure %v", attrs)
} else {
family.FromAttrs(amap)
familyName := func() string {
self.lock.Lock()
defer self.lock.Unlock()
if f, ok := self.familyIds[family.Id]; ok {
return f.Name
}
return family.Name
}()
if grps := amap.Get(CTRL_ATTR_MCAST_GROUPS); grps != nil {
for _, grp := range grps.(AttrSlice).Slice() {
gattr := grp.Value.(AttrMap)
key := uint32(gattr.Get(CTRL_ATTR_MCAST_GRP_ID).(U32))
groups[key] = GenlGroup{
Id: key,
Family: familyName,
Name: string(gattr.Get(CTRL_ATTR_MCAST_GRP_NAME).(NulString)),
}
}
}
}
self.lock.Lock()
defer self.lock.Unlock()
switch msg.Genl.Cmd {
case CTRL_CMD_NEWFAMILY:
self.familyIds[family.Id] = family
fallthrough
case CTRL_CMD_NEWMCAST_GRP:
for _, grp := range groups {
if _, exists := self.groupIds[grp.Id]; !exists {
self.groupIds[grp.Id] = grp
}
}
case CTRL_CMD_DELFAMILY:
delete(self.familyIds, family.Id)
fallthrough
case CTRL_CMD_DELMCAST_GRP:
for _, grp := range groups {
if _, exists := self.groupIds[grp.Id]; exists {
delete(self.groupIds, grp.Id)
}
}
}
self.sync()
}
func (self GenlHub) Request(family string, version uint8, cmd uint8, flags uint16, payload []byte, attr AttrList) ([]GenlMessage, error) {
var familyInfo GenlFamily
familyInfoMiss := true
self.lock.Lock()
for _, f := range self.familyIds {
if f.Name == family {
familyInfo = f
familyInfoMiss = false
}
}
self.lock.Unlock()
if familyInfoMiss {
return nil, fmt.Errorf("family %s not found", family)
}
res := make(chan GenlMessage)
msg := make([]byte, GENL_HDRLEN+NLMSG_ALIGN(int(familyInfo.Hdrsize)))
*(*GenlMsghdr)(unsafe.Pointer(&msg[0])) = GenlMsghdr{
Cmd: cmd,
Version: version,
}
copy(msg[GENL_HDRLEN:], payload)
if attr != nil {
msg = append(msg, attr.Bytes()...)
}
if err := func() error {
self.lock.Lock()
defer self.lock.Unlock()
self.unicast[self.sock.SeqNext] = res
if err := NlSendSimple(self.sock, familyInfo.Id, flags, msg); err != nil {
return err
}
return nil
}(); err != nil {
return nil, err
}
var ret []GenlMessage
for r := range res {
ret = append(ret, r)
}
return ret, nil
}
// Add adds a GenlListener to GenlHub.
// listeners will recieve all of the same family events, regardless of their group registration.
// If you want to limited group multicast, create separate GenlHub for each.
func (self GenlHub) Add(family, group string, listener GenlListener) error {
self.lock.Lock()
defer self.lock.Unlock()
key := groupKey{Family: family, Name: group}
self.multicast[key] = append(self.multicast[key], listener)
return self.sync()
}
func (self GenlHub) Remove(family, group string, listener GenlListener) error {
self.lock.Lock()
defer self.lock.Unlock()
key := groupKey{Family: family, Name: group}
var active []GenlListener
for _, li := range self.multicast[key] {
if li != listener {
active = append(active, li)
}
}
self.multicast[key] = active
return self.sync()
}