move device cleanup to common code, fixes use-after-free in tunnel code
[project/netifd.git] / tunnel.c
1 #include "netifd.h"
2 #include "device.h"
3 #include "config.h"
4 #include "system.h"
5
6 struct tunnel {
7         struct device dev;
8         device_state_cb set_state;
9 };
10
11 static int
12 tunnel_set_state(struct device *dev, bool up)
13 {
14         struct tunnel *tun = container_of(dev, struct tunnel, dev);
15         int ret;
16
17         if (up) {
18                 ret = system_add_ip_tunnel(dev->ifname, dev->config);
19                 if (ret != 0)
20                         return ret;
21         }
22
23         ret = tun->set_state(dev, up);
24         if (ret || !up)
25                 system_del_ip_tunnel(dev->ifname);
26
27         return ret;
28 }
29
30 static struct device *
31 tunnel_create(const char *name, struct blob_attr *attr)
32 {
33         struct tunnel *tun;
34         struct device *dev;
35
36         tun = calloc(1, sizeof(*tun));
37         dev = &tun->dev;
38         device_init(dev, &tunnel_device_type, name);
39         tun->set_state = dev->set_state;
40         dev->set_state = tunnel_set_state;
41         device_set_present(dev, true);
42
43         return dev;
44 }
45
46 static void
47 tunnel_free(struct device *dev)
48 {
49         struct tunnel *tun = container_of(dev, struct tunnel, dev);
50
51         free(tun);
52 }
53
54 const struct device_type tunnel_device_type = {
55         .name = "IP tunnel",
56         .config_params = &tunnel_attr_list,
57
58         .create = tunnel_create,
59         .free = tunnel_free,
60 };
61
62