1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2013 Tom Gundersen <teg@jklm.no>
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/socket.h>
29 #include "rtnl-internal.h"
31 static int sd_rtnl_new(sd_rtnl **ret) {
34 assert_return(ret, -EINVAL);
36 rtnl = new0(sd_rtnl, 1);
40 rtnl->n_ref = REFCNT_INIT;
44 rtnl->sockaddr.nl.nl_family = AF_NETLINK;
50 int sd_rtnl_open(__u32 groups, sd_rtnl **ret) {
54 r = sd_rtnl_new(&rtnl);
58 rtnl->fd = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_ROUTE);
65 rtnl->sockaddr.nl.nl_groups = groups;
67 r = bind(rtnl->fd, &rtnl->sockaddr.sa, sizeof(rtnl->sockaddr));
79 sd_rtnl *sd_rtnl_ref(sd_rtnl *rtnl) {
81 assert_se(REFCNT_INC(rtnl->n_ref) >= 2);
86 sd_rtnl *sd_rtnl_unref(sd_rtnl *rtnl) {
87 if (rtnl && REFCNT_DEC(rtnl->n_ref) <= 0) {
89 close_nointr_nofail(rtnl->fd);
96 int sd_rtnl_send_with_reply_and_block(sd_rtnl *nl,
97 sd_rtnl_message *message,
99 sd_rtnl_message **ret) {
100 struct pollfd p[1] = {};
101 sd_rtnl_message *reply;
102 struct timespec left;
106 assert_return(nl, -EINVAL);
107 assert_return(message, -EINVAL);
109 r = message_seal(nl, message);
113 serial = message_get_serial(message);
116 p[0].events = POLLOUT;
118 timeout = now(CLOCK_MONOTONIC) + usec;
121 if (usec != (uint64_t) -1) {
124 n = now(CLOCK_MONOTONIC);
128 timespec_store(&left, timeout - n);
131 r = ppoll(p, 1, usec == (uint64_t) -1 ? NULL : &left, NULL);
135 r = socket_write_message(nl, message);
144 p[0].events = POLLIN;
147 if (usec != (uint64_t) -1) {
150 n = now(CLOCK_MONOTONIC);
154 timespec_store(&left, timeout - n);
157 r = ppoll(p, 1, usec == (uint64_t) -1 ? NULL : &left, NULL);
161 r = socket_read_message(nl, &reply);
166 int received_serial = message_get_serial(reply);
168 if (received_serial == serial) {
169 r = message_get_errno(reply);
171 sd_rtnl_message_unref(reply);
178 reply = sd_rtnl_message_unref(reply);
183 reply = sd_rtnl_message_unref(reply);