]> git.ipfire.org Git - people/ms/network.git/blob - src/libnetwork/interface.c
libnetwork: Add interface objects
[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 <stdlib.h>
23 #include <string.h>
24
25 #include <network/interface.h>
26 #include <network/libnetwork.h>
27 #include <network/logging.h>
28 #include "libnetwork-private.h"
29
30 struct network_interface {
31 struct network_ctx* ctx;
32 int refcount;
33
34 char* name;
35 };
36
37 NETWORK_EXPORT int network_interface_new(struct network_ctx* ctx,
38 struct network_interface** intf, const char* name) {
39 if (!name)
40 return -EINVAL;
41
42 struct network_interface* i = calloc(1, sizeof(*i));
43 if (!i)
44 return -ENOMEM;
45
46 // Initialise object
47 i->ctx = network_ref(ctx);
48 i->refcount = 1;
49 i->name = strdup(name);
50
51 DEBUG(i->ctx, "Allocated network interface at %p\n", i);
52
53 *intf = i;
54 return 0;
55 }
56
57 NETWORK_EXPORT struct network_interface* network_interface_ref(struct network_interface* intf) {
58 if (!intf)
59 return NULL;
60
61 intf->refcount++;
62 return intf;
63 }
64
65 static void network_interface_free(struct network_interface* intf) {
66 DEBUG(intf->ctx, "Released network interface at %p\n", intf);
67
68 if (intf->name)
69 free(intf->name);
70
71 network_unref(intf->ctx);
72 free(intf);
73 }
74
75 NETWORK_EXPORT struct network_interface* network_interface_unref(struct network_interface* intf) {
76 if (!intf)
77 return NULL;
78
79 if (--intf->refcount > 0)
80 return intf;
81
82 network_interface_free(intf);
83 return NULL;
84 }
85
86 NETWORK_EXPORT const char* network_interface_get_name(struct network_interface* intf) {
87 return intf->name;
88 }