aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go
blob: 7b98c9cb6d3b2c6ab3333de8571406ce7e74cafa (plain)
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
package netlink

import (
	"fmt"
	"syscall"

	"github.com/vishvananda/netns"

	"github.com/vishvananda/netlink/nl"
)

type XfrmMsg interface {
	Type() nl.XfrmMsgType
}

type XfrmMsgExpire struct {
	XfrmState *XfrmState
	Hard      bool
}

func (ue *XfrmMsgExpire) Type() nl.XfrmMsgType {
	return nl.XFRM_MSG_EXPIRE
}

func parseXfrmMsgExpire(b []byte) *XfrmMsgExpire {
	var e XfrmMsgExpire

	msg := nl.DeserializeXfrmUserExpire(b)
	e.XfrmState = xfrmStateFromXfrmUsersaInfo(&msg.XfrmUsersaInfo)
	e.Hard = msg.Hard == 1

	return &e
}

func XfrmMonitor(ch chan<- XfrmMsg, done <-chan struct{}, errorChan chan<- error,
	types ...nl.XfrmMsgType) error {

	groups, err := xfrmMcastGroups(types)
	if err != nil {
		return nil
	}
	s, err := nl.SubscribeAt(netns.None(), netns.None(), syscall.NETLINK_XFRM, groups...)
	if err != nil {
		return err
	}

	if done != nil {
		go func() {
			<-done
			s.Close()
		}()

	}

	go func() {
		defer close(ch)
		for {
			msgs, err := s.Receive()
			if err != nil {
				errorChan <- err
				return
			}
			for _, m := range msgs {
				switch m.Header.Type {
				case nl.XFRM_MSG_EXPIRE:
					ch <- parseXfrmMsgExpire(m.Data)
				default:
					errorChan <- fmt.Errorf("unsupported msg type: %x", m.Header.Type)
				}
			}
		}
	}()

	return nil
}

func xfrmMcastGroups(types []nl.XfrmMsgType) ([]uint, error) {
	groups := make([]uint, 0)

	if len(types) == 0 {
		return nil, fmt.Errorf("no xfrm msg type specified")
	}

	for _, t := range types {
		var group uint

		switch t {
		case nl.XFRM_MSG_EXPIRE:
			group = nl.XFRMNLGRP_EXPIRE
		default:
			return nil, fmt.Errorf("unsupported group: %x", t)
		}

		groups = append(groups, group)
	}

	return groups, nil
}