]> git.ipfire.org Git - people/ms/network.git/blob - src/libnetwork/interface.c
ip-tunnel: Set TTL to 255 by default
[people/ms/network.git] / src / libnetwork / interface.c
1 /*#############################################################################
2 # #
3 # IPFire.org - A linux based firewall #
4 # Copyright (C) 2018 IPFire Network Development Team #
5 # #
6 # This program is free software: you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation, either version 3 of the License, or #
9 # (at your option) any later version. #
10 # #
11 # This program is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
15 # #
16 # You should have received a copy of the GNU General Public License #
17 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
18 # #
19 #############################################################################*/
20
21 #include <errno.h>
22 #include <net/if.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include <network/interface.h>
27 #include <network/libnetwork.h>
28 #include <network/logging.h>
29 #include "libnetwork-private.h"
30
31 struct network_interface {
32 struct network_ctx* ctx;
33 int refcount;
34
35 unsigned int index;
36 char* name;
37 };
38
39 NETWORK_EXPORT int network_interface_new(struct network_ctx* ctx,
40 struct network_interface** intf, const char* name) {
41 if (!name)
42 return -EINVAL;
43
44 unsigned int index = if_nametoindex(name);
45 if (!index) {
46 ERROR(ctx, "Could not find interface %s\n", name);
47 return -ENODEV;
48 }
49
50 struct network_interface* i = calloc(1, sizeof(*i));
51 if (!i)
52 return -ENOMEM;
53
54 // Initialise object
55 i->ctx = network_ref(ctx);
56 i->refcount = 1;
57 i->index = index;
58 i->name = strdup(name);
59
60 DEBUG(i->ctx, "Allocated network interface at %p\n", i);
61
62 *intf = i;
63 return 0;
64 }
65
66 NETWORK_EXPORT struct network_interface* network_interface_ref(struct network_interface* intf) {
67 if (!intf)
68 return NULL;
69
70 intf->refcount++;
71 return intf;
72 }
73
74 static void network_interface_free(struct network_interface* intf) {
75 DEBUG(intf->ctx, "Released network interface at %p\n", intf);
76
77 if (intf->name)
78 free(intf->name);
79
80 network_unref(intf->ctx);
81 free(intf);
82 }
83
84 NETWORK_EXPORT struct network_interface* network_interface_unref(struct network_interface* intf) {
85 if (!intf)
86 return NULL;
87
88 if (--intf->refcount > 0)
89 return intf;
90
91 network_interface_free(intf);
92 return NULL;
93 }
94
95 NETWORK_EXPORT const char* network_interface_get_name(struct network_interface* intf) {
96 return intf->name;
97 }