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;
65 r = sd_rtnl_new(&rtnl);
69 rtnl->fd = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_ROUTE);
73 rtnl->sockaddr.nl.nl_groups = groups;
75 r = bind(rtnl->fd, &rtnl->sockaddr.sa, sizeof(rtnl->sockaddr));
85 sd_rtnl *sd_rtnl_ref(sd_rtnl *rtnl) {
87 assert_se(REFCNT_INC(rtnl->n_ref) >= 2);
92 sd_rtnl *sd_rtnl_unref(sd_rtnl *rtnl) {
93 if (rtnl && REFCNT_DEC(rtnl->n_ref) <= 0) {
95 close_nointr_nofail(rtnl->fd);
102 int sd_rtnl_send_with_reply_and_block(sd_rtnl *nl,
103 sd_rtnl_message *message,
105 sd_rtnl_message **ret) {
106 struct pollfd p[1] = {};
107 struct timespec left;
111 assert_return(nl, -EINVAL);
112 assert_return(!rtnl_pid_changed(nl), -ECHILD);
113 assert_return(message, -EINVAL);
115 r = message_seal(nl, message);
119 serial = message_get_serial(message);
122 p[0].events = POLLOUT;
124 if (usec == (uint64_t) -1)
127 timeout = now(CLOCK_MONOTONIC) + RTNL_DEFAULT_TIMEOUT;
129 timeout = now(CLOCK_MONOTONIC) + usec;
135 n = now(CLOCK_MONOTONIC);
139 timespec_store(&left, timeout - n);
142 r = ppoll(p, 1, timeout ? &left : NULL, NULL);
146 r = socket_write_message(nl, message);
155 p[0].events = POLLIN;
158 _cleanup_sd_rtnl_message_unref_ sd_rtnl_message *reply = NULL;
163 n = now(CLOCK_MONOTONIC);
167 timespec_store(&left, timeout - n);
170 r = ppoll(p, 1, timeout ? &left : NULL, NULL);
174 r = socket_read_message(nl, &reply);
179 int received_serial = message_get_serial(reply);
181 if (received_serial == serial) {
182 r = message_get_errno(reply);