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;
46 rtnl->original_pid = getpid();
52 static bool rtnl_pid_changed(sd_rtnl *rtnl) {
55 /* We don't support people creating an rtnl connection and
56 * keeping it around over a fork(). Let's complain. */
58 return rtnl->original_pid != getpid();
61 int sd_rtnl_open(uint32_t groups, sd_rtnl **ret) {
62 _cleanup_sd_rtnl_unref_ sd_rtnl *rtnl = NULL;
66 r = sd_rtnl_new(&rtnl);
70 rtnl->fd = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_ROUTE);
74 rtnl->sockaddr.nl.nl_groups = groups;
76 addrlen = sizeof(rtnl->sockaddr);
78 r = bind(rtnl->fd, &rtnl->sockaddr.sa, addrlen);
82 r = getsockname(rtnl->fd, &rtnl->sockaddr.sa, &addrlen);
92 sd_rtnl *sd_rtnl_ref(sd_rtnl *rtnl) {
94 assert_se(REFCNT_INC(rtnl->n_ref) >= 2);
99 sd_rtnl *sd_rtnl_unref(sd_rtnl *rtnl) {
100 if (rtnl && REFCNT_DEC(rtnl->n_ref) <= 0) {
102 close_nointr_nofail(rtnl->fd);
109 int sd_rtnl_send_with_reply_and_block(sd_rtnl *nl,
110 sd_rtnl_message *message,
112 sd_rtnl_message **ret) {
113 struct pollfd p[1] = {};
114 struct timespec left;
118 assert_return(nl, -EINVAL);
119 assert_return(!rtnl_pid_changed(nl), -ECHILD);
120 assert_return(message, -EINVAL);
122 r = message_seal(nl, message);
126 serial = message_get_serial(message);
129 p[0].events = POLLOUT;
131 if (usec == (uint64_t) -1)
134 timeout = now(CLOCK_MONOTONIC) + RTNL_DEFAULT_TIMEOUT;
136 timeout = now(CLOCK_MONOTONIC) + usec;
142 n = now(CLOCK_MONOTONIC);
146 timespec_store(&left, timeout - n);
149 r = ppoll(p, 1, timeout ? &left : NULL, NULL);
153 r = socket_write_message(nl, message);
162 p[0].events = POLLIN;
165 _cleanup_sd_rtnl_message_unref_ sd_rtnl_message *reply = NULL;
170 n = now(CLOCK_MONOTONIC);
174 timespec_store(&left, timeout - n);
177 r = ppoll(p, 1, timeout ? &left : NULL, NULL);
181 r = socket_read_message(nl, &reply);
186 int received_serial = message_get_serial(reply);
188 if (received_serial == serial) {
189 r = message_get_errno(reply);