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"
30 #include "rtnl-util.h"
32 static int sd_rtnl_new(sd_rtnl **ret) {
35 assert_return(ret, -EINVAL);
37 rtnl = new0(sd_rtnl, 1);
41 rtnl->n_ref = REFCNT_INIT;
45 rtnl->sockaddr.nl.nl_family = AF_NETLINK;
47 rtnl->original_pid = getpid();
53 static bool rtnl_pid_changed(sd_rtnl *rtnl) {
56 /* We don't support people creating an rtnl connection and
57 * keeping it around over a fork(). Let's complain. */
59 return rtnl->original_pid != getpid();
62 int sd_rtnl_open(uint32_t groups, sd_rtnl **ret) {
63 _cleanup_sd_rtnl_unref_ sd_rtnl *rtnl = NULL;
67 r = sd_rtnl_new(&rtnl);
71 rtnl->fd = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_ROUTE);
75 rtnl->sockaddr.nl.nl_groups = groups;
77 addrlen = sizeof(rtnl->sockaddr);
79 r = bind(rtnl->fd, &rtnl->sockaddr.sa, addrlen);
83 r = getsockname(rtnl->fd, &rtnl->sockaddr.sa, &addrlen);
93 sd_rtnl *sd_rtnl_ref(sd_rtnl *rtnl) {
95 assert_se(REFCNT_INC(rtnl->n_ref) >= 2);
100 sd_rtnl *sd_rtnl_unref(sd_rtnl *rtnl) {
101 if (rtnl && REFCNT_DEC(rtnl->n_ref) <= 0) {
103 close_nointr_nofail(rtnl->fd);
110 int sd_rtnl_send_with_reply_and_block(sd_rtnl *nl,
111 sd_rtnl_message *message,
113 sd_rtnl_message **ret) {
114 struct pollfd p[1] = {};
115 struct timespec left;
119 assert_return(nl, -EINVAL);
120 assert_return(!rtnl_pid_changed(nl), -ECHILD);
121 assert_return(message, -EINVAL);
123 r = message_seal(nl, message);
127 serial = message_get_serial(message);
130 p[0].events = POLLOUT;
132 if (usec == (uint64_t) -1)
135 timeout = now(CLOCK_MONOTONIC) + RTNL_DEFAULT_TIMEOUT;
137 timeout = now(CLOCK_MONOTONIC) + usec;
143 n = now(CLOCK_MONOTONIC);
147 timespec_store(&left, timeout - n);
150 r = ppoll(p, 1, timeout ? &left : NULL, NULL);
154 r = socket_write_message(nl, message);
163 p[0].events = POLLIN;
166 _cleanup_sd_rtnl_message_unref_ sd_rtnl_message *reply = NULL;
171 n = now(CLOCK_MONOTONIC);
175 timespec_store(&left, timeout - n);
178 r = ppoll(p, 1, timeout ? &left : NULL, NULL);
182 r = socket_read_message(nl, &reply);
187 int received_serial = message_get_serial(reply);
189 if (received_serial == serial) {
190 r = message_get_errno(reply);