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(uint32_t groups, sd_rtnl **ret) {
51 _cleanup_sd_rtnl_unref_ sd_rtnl *rtnl = NULL;
54 r = sd_rtnl_new(&rtnl);
58 rtnl->fd = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_ROUTE);
62 rtnl->sockaddr.nl.nl_groups = groups;
64 r = bind(rtnl->fd, &rtnl->sockaddr.sa, sizeof(rtnl->sockaddr));
74 sd_rtnl *sd_rtnl_ref(sd_rtnl *rtnl) {
76 assert_se(REFCNT_INC(rtnl->n_ref) >= 2);
81 sd_rtnl *sd_rtnl_unref(sd_rtnl *rtnl) {
82 if (rtnl && REFCNT_DEC(rtnl->n_ref) <= 0) {
84 close_nointr_nofail(rtnl->fd);
91 int sd_rtnl_send_with_reply_and_block(sd_rtnl *nl,
92 sd_rtnl_message *message,
94 sd_rtnl_message **ret) {
95 struct pollfd p[1] = {};
100 assert_return(nl, -EINVAL);
101 assert_return(message, -EINVAL);
103 r = message_seal(nl, message);
107 serial = message_get_serial(message);
110 p[0].events = POLLOUT;
112 timeout = now(CLOCK_MONOTONIC) + usec;
115 if (usec != (uint64_t) -1) {
118 n = now(CLOCK_MONOTONIC);
122 timespec_store(&left, timeout - n);
125 r = ppoll(p, 1, usec == (uint64_t) -1 ? NULL : &left, NULL);
129 r = socket_write_message(nl, message);
138 p[0].events = POLLIN;
141 _cleanup_sd_rtnl_message_unref_ sd_rtnl_message *reply = NULL;
143 if (usec != (uint64_t) -1) {
146 n = now(CLOCK_MONOTONIC);
150 timespec_store(&left, timeout - n);
153 r = ppoll(p, 1, usec == (uint64_t) -1 ? NULL : &left, NULL);
157 r = socket_read_message(nl, &reply);
162 int received_serial = message_get_serial(reply);
164 if (received_serial == serial) {
165 r = message_get_errno(reply);