0c243508a4314ef3f01c1196c13fe748a4f6f280
[thirdparty/systemd.git] / src / network / networkd-link.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <netinet/in.h>
4 #include <linux/if.h>
5 #include <unistd.h>
6
7 #include "alloc-util.h"
8 #include "bus-util.h"
9 #include "dhcp-identifier.h"
10 #include "dhcp-lease-internal.h"
11 #include "env-file.h"
12 #include "fd-util.h"
13 #include "fileio.h"
14 #include "missing_network.h"
15 #include "netdev/bond.h"
16 #include "netdev/bridge.h"
17 #include "netdev/ipvlan.h"
18 #include "netdev/vrf.h"
19 #include "netlink-util.h"
20 #include "network-internal.h"
21 #include "networkd-can.h"
22 #include "networkd-ipv6-proxy-ndp.h"
23 #include "networkd-lldp-tx.h"
24 #include "networkd-manager.h"
25 #include "networkd-ndisc.h"
26 #include "networkd-neighbor.h"
27 #include "networkd-radv.h"
28 #include "networkd-routing-policy-rule.h"
29 #include "set.h"
30 #include "socket-util.h"
31 #include "stdio-util.h"
32 #include "string-table.h"
33 #include "strv.h"
34 #include "sysctl-util.h"
35 #include "tmpfile-util.h"
36 #include "udev-util.h"
37 #include "util.h"
38 #include "virt.h"
39
40 uint32_t link_get_vrf_table(Link *link) {
41         return link->network->vrf ? VRF(link->network->vrf)->table : RT_TABLE_MAIN;
42 }
43
44 uint32_t link_get_dhcp_route_table(Link *link) {
45         /* When the interface is part of an VRF use the VRFs routing table, unless
46          * another table is explicitly specified. */
47         if (link->network->dhcp_route_table_set)
48                 return link->network->dhcp_route_table;
49         return link_get_vrf_table(link);
50 }
51
52 uint32_t link_get_ipv6_accept_ra_route_table(Link *link) {
53         if (link->network->ipv6_accept_ra_route_table_set)
54                 return link->network->ipv6_accept_ra_route_table;
55         return link_get_vrf_table(link);
56 }
57
58 DUID* link_get_duid(Link *link) {
59         if (link->network->duid.type != _DUID_TYPE_INVALID)
60                 return &link->network->duid;
61         else
62                 return &link->manager->duid;
63 }
64
65 static bool link_dhcp6_enabled(Link *link) {
66         assert(link);
67
68         if (!socket_ipv6_is_supported())
69                 return false;
70
71         if (link->flags & IFF_LOOPBACK)
72                 return false;
73
74         if (!link->network)
75                 return false;
76
77         if (link->network->bond)
78                 return false;
79
80         if (STRPTR_IN_SET(link->kind, "can", "vcan", "vxcan"))
81                 return false;
82
83         if (manager_sysctl_ipv6_enabled(link->manager) == 0)
84                 return false;
85
86         return link->network->dhcp & ADDRESS_FAMILY_IPV6;
87 }
88
89 static bool link_dhcp4_enabled(Link *link) {
90         assert(link);
91
92         if (link->flags & IFF_LOOPBACK)
93                 return false;
94
95         if (!link->network)
96                 return false;
97
98         if (link->network->bond)
99                 return false;
100
101         if (STRPTR_IN_SET(link->kind, "can", "vcan", "vxcan"))
102                 return false;
103
104         return link->network->dhcp & ADDRESS_FAMILY_IPV4;
105 }
106
107 static bool link_dhcp4_server_enabled(Link *link) {
108         assert(link);
109
110         if (link->flags & IFF_LOOPBACK)
111                 return false;
112
113         if (!link->network)
114                 return false;
115
116         if (link->network->bond)
117                 return false;
118
119         if (STRPTR_IN_SET(link->kind, "can", "vcan", "vxcan"))
120                 return false;
121
122         return link->network->dhcp_server;
123 }
124
125 bool link_ipv4ll_enabled(Link *link, AddressFamilyBoolean mask) {
126         assert(link);
127         assert((mask & ~(ADDRESS_FAMILY_IPV4 | ADDRESS_FAMILY_FALLBACK_IPV4)) == 0);
128
129         if (link->flags & IFF_LOOPBACK)
130                 return false;
131
132         if (!link->network)
133                 return false;
134
135         if (STRPTR_IN_SET(link->kind, "vrf", "wireguard", "ipip", "gre", "ip6gre", "ip6tnl", "sit", "vti", "vti6", "can", "vcan", "vxcan", "nlmon"))
136                 return false;
137
138         /* L3 or L3S mode do not support ARP. */
139         if (IN_SET(link_get_ipvlan_mode(link), NETDEV_IPVLAN_MODE_L3, NETDEV_IPVLAN_MODE_L3S))
140                 return false;
141
142         if (link->network->bond)
143                 return false;
144
145         if (link->network->bond)
146                 return false;
147
148         return link->network->link_local & mask;
149 }
150
151 static bool link_ipv6ll_enabled(Link *link) {
152         assert(link);
153
154         if (!socket_ipv6_is_supported())
155                 return false;
156
157         if (link->flags & IFF_LOOPBACK)
158                 return false;
159
160         if (!link->network)
161                 return false;
162
163         if (STRPTR_IN_SET(link->kind, "vrf", "wireguard", "ipip", "gre", "sit", "vti", "can", "vcan", "vxcan", "nlmon"))
164                 return false;
165
166         if (link->network->bond)
167                 return false;
168
169         if (manager_sysctl_ipv6_enabled(link->manager) == 0)
170                 return false;
171
172         return link->network->link_local & ADDRESS_FAMILY_IPV6;
173 }
174
175 static bool link_ipv6_enabled(Link *link) {
176         assert(link);
177
178         if (!socket_ipv6_is_supported())
179                 return false;
180
181         if (link->network->bond)
182                 return false;
183
184         if (manager_sysctl_ipv6_enabled(link->manager) == 0)
185                 return false;
186
187         if (STRPTR_IN_SET(link->kind, "can", "vcan", "vxcan"))
188                 return false;
189
190         /* DHCPv6 client will not be started if no IPv6 link-local address is configured. */
191         return link_ipv6ll_enabled(link) || network_has_static_ipv6_addresses(link->network);
192 }
193
194 static bool link_radv_enabled(Link *link) {
195         assert(link);
196
197         if (!link_ipv6ll_enabled(link))
198                 return false;
199
200         return link->network->router_prefix_delegation != RADV_PREFIX_DELEGATION_NONE;
201 }
202
203 static bool link_ipv4_forward_enabled(Link *link) {
204         assert(link);
205
206         if (link->flags & IFF_LOOPBACK)
207                 return false;
208
209         if (!link->network)
210                 return false;
211
212         if (link->network->ip_forward == _ADDRESS_FAMILY_BOOLEAN_INVALID)
213                 return false;
214
215         return link->network->ip_forward & ADDRESS_FAMILY_IPV4;
216 }
217
218 static bool link_ipv6_forward_enabled(Link *link) {
219         assert(link);
220
221         if (!socket_ipv6_is_supported())
222                 return false;
223
224         if (link->flags & IFF_LOOPBACK)
225                 return false;
226
227         if (!link->network)
228                 return false;
229
230         if (link->network->ip_forward == _ADDRESS_FAMILY_BOOLEAN_INVALID)
231                 return false;
232
233         if (manager_sysctl_ipv6_enabled(link->manager) == 0)
234                 return false;
235
236         return link->network->ip_forward & ADDRESS_FAMILY_IPV6;
237 }
238
239 static bool link_proxy_arp_enabled(Link *link) {
240         assert(link);
241
242         if (link->flags & IFF_LOOPBACK)
243                 return false;
244
245         if (!link->network)
246                 return false;
247
248         if (link->network->proxy_arp < 0)
249                 return false;
250
251         return true;
252 }
253
254 static bool link_ipv6_accept_ra_enabled(Link *link) {
255         assert(link);
256
257         if (!socket_ipv6_is_supported())
258                 return false;
259
260         if (link->flags & IFF_LOOPBACK)
261                 return false;
262
263         if (!link->network)
264                 return false;
265
266         if (!link_ipv6ll_enabled(link))
267                 return false;
268
269         /* If unset use system default (enabled if local forwarding is disabled.
270          * disabled if local forwarding is enabled).
271          * If set, ignore or enforce RA independent of local forwarding state.
272          */
273         if (link->network->ipv6_accept_ra < 0)
274                 /* default to accept RA if ip_forward is disabled and ignore RA if ip_forward is enabled */
275                 return !link_ipv6_forward_enabled(link);
276         else if (link->network->ipv6_accept_ra > 0)
277                 /* accept RA even if ip_forward is enabled */
278                 return true;
279         else
280                 /* ignore RA */
281                 return false;
282 }
283
284 static IPv6PrivacyExtensions link_ipv6_privacy_extensions(Link *link) {
285         assert(link);
286
287         if (!socket_ipv6_is_supported())
288                 return _IPV6_PRIVACY_EXTENSIONS_INVALID;
289
290         if (link->flags & IFF_LOOPBACK)
291                 return _IPV6_PRIVACY_EXTENSIONS_INVALID;
292
293         if (!link->network)
294                 return _IPV6_PRIVACY_EXTENSIONS_INVALID;
295
296         return link->network->ipv6_privacy_extensions;
297 }
298
299 static int link_enable_ipv6(Link *link) {
300         bool disabled;
301         int r;
302
303         if (link->flags & IFF_LOOPBACK)
304                 return 0;
305
306         disabled = !link_ipv6_enabled(link);
307
308         r = sysctl_write_ip_property_boolean(AF_INET6, link->ifname, "disable_ipv6", disabled);
309         if (r < 0)
310                 log_link_warning_errno(link, r, "Cannot %s IPv6: %m", enable_disable(!disabled));
311         else
312                 log_link_info(link, "IPv6 successfully %sd", enable_disable(!disabled));
313
314         return 0;
315 }
316
317 static bool link_is_enslaved(Link *link) {
318         if (link->flags & IFF_SLAVE)
319                 /* Even if the link is not managed by networkd, honor IFF_SLAVE flag. */
320                 return true;
321
322         if (!link->network)
323                 return false;
324
325         if (link->master_ifindex > 0 && link->network->bridge)
326                 return true;
327
328         /* TODO: add conditions for other netdevs. */
329
330         return false;
331 }
332
333 static void link_update_master_operstate(Link *link, NetDev *netdev) {
334         Link *master;
335
336         if (!netdev)
337                 return;
338
339         if (link_get(link->manager, netdev->ifindex, &master) < 0)
340                 return;
341
342         link_update_operstate(master, true);
343 }
344
345 void link_update_operstate(Link *link, bool also_update_master) {
346         LinkOperationalState operstate;
347         Iterator i;
348
349         assert(link);
350
351         if (link->kernel_operstate == IF_OPER_DORMANT)
352                 operstate = LINK_OPERSTATE_DORMANT;
353         else if (link_has_carrier(link)) {
354                 Address *address;
355                 uint8_t scope = RT_SCOPE_NOWHERE;
356
357                 /* if we have carrier, check what addresses we have */
358                 SET_FOREACH(address, link->addresses, i) {
359                         if (!address_is_ready(address))
360                                 continue;
361
362                         if (address->scope < scope)
363                                 scope = address->scope;
364                 }
365
366                 /* for operstate we also take foreign addresses into account */
367                 SET_FOREACH(address, link->addresses_foreign, i) {
368                         if (!address_is_ready(address))
369                                 continue;
370
371                         if (address->scope < scope)
372                                 scope = address->scope;
373                 }
374
375                 if (scope < RT_SCOPE_SITE)
376                         /* universally accessible addresses found */
377                         operstate = LINK_OPERSTATE_ROUTABLE;
378                 else if (scope < RT_SCOPE_HOST)
379                         /* only link or site local addresses found */
380                         operstate = LINK_OPERSTATE_DEGRADED;
381                 else
382                         /* no useful addresses found */
383                         operstate = LINK_OPERSTATE_CARRIER;
384         } else if (link->flags & IFF_UP)
385                 operstate = LINK_OPERSTATE_NO_CARRIER;
386         else
387                 operstate = LINK_OPERSTATE_OFF;
388
389         if (IN_SET(operstate, LINK_OPERSTATE_DEGRADED, LINK_OPERSTATE_CARRIER) &&
390             link_is_enslaved(link))
391                 operstate = LINK_OPERSTATE_ENSLAVED;
392
393         if (operstate >= LINK_OPERSTATE_CARRIER) {
394                 Link *slave;
395
396                 SET_FOREACH(slave, link->slaves, i) {
397                         link_update_operstate(slave, false);
398
399                         if (slave->operstate < LINK_OPERSTATE_CARRIER)
400                                 operstate = LINK_OPERSTATE_DEGRADED_CARRIER;
401                 }
402         }
403
404         if (link->operstate != operstate) {
405                 link->operstate = operstate;
406                 link_send_changed(link, "OperationalState", NULL);
407                 link_dirty(link);
408         }
409
410         if (also_update_master && link->network) {
411                 link_update_master_operstate(link, link->network->bond);
412                 link_update_master_operstate(link, link->network->bridge);
413         }
414 }
415
416 #define FLAG_STRING(string, flag, old, new) \
417         (((old ^ new) & flag) \
418                 ? ((old & flag) ? (" -" string) : (" +" string)) \
419                 : "")
420
421 static int link_update_flags(Link *link, sd_netlink_message *m, bool force_update_operstate) {
422         unsigned flags, unknown_flags_added, unknown_flags_removed, unknown_flags;
423         uint8_t operstate;
424         int r;
425
426         assert(link);
427
428         r = sd_rtnl_message_link_get_flags(m, &flags);
429         if (r < 0)
430                 return log_link_warning_errno(link, r, "Could not get link flags: %m");
431
432         r = sd_netlink_message_read_u8(m, IFLA_OPERSTATE, &operstate);
433         if (r < 0)
434                 /* if we got a message without operstate, take it to mean
435                    the state was unchanged */
436                 operstate = link->kernel_operstate;
437
438         if (!force_update_operstate && (link->flags == flags) && (link->kernel_operstate == operstate))
439                 return 0;
440
441         if (link->flags != flags) {
442                 log_link_debug(link, "Flags change:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
443                                FLAG_STRING("LOOPBACK", IFF_LOOPBACK, link->flags, flags),
444                                FLAG_STRING("MASTER", IFF_MASTER, link->flags, flags),
445                                FLAG_STRING("SLAVE", IFF_SLAVE, link->flags, flags),
446                                FLAG_STRING("UP", IFF_UP, link->flags, flags),
447                                FLAG_STRING("DORMANT", IFF_DORMANT, link->flags, flags),
448                                FLAG_STRING("LOWER_UP", IFF_LOWER_UP, link->flags, flags),
449                                FLAG_STRING("RUNNING", IFF_RUNNING, link->flags, flags),
450                                FLAG_STRING("MULTICAST", IFF_MULTICAST, link->flags, flags),
451                                FLAG_STRING("BROADCAST", IFF_BROADCAST, link->flags, flags),
452                                FLAG_STRING("POINTOPOINT", IFF_POINTOPOINT, link->flags, flags),
453                                FLAG_STRING("PROMISC", IFF_PROMISC, link->flags, flags),
454                                FLAG_STRING("ALLMULTI", IFF_ALLMULTI, link->flags, flags),
455                                FLAG_STRING("PORTSEL", IFF_PORTSEL, link->flags, flags),
456                                FLAG_STRING("AUTOMEDIA", IFF_AUTOMEDIA, link->flags, flags),
457                                FLAG_STRING("DYNAMIC", IFF_DYNAMIC, link->flags, flags),
458                                FLAG_STRING("NOARP", IFF_NOARP, link->flags, flags),
459                                FLAG_STRING("NOTRAILERS", IFF_NOTRAILERS, link->flags, flags),
460                                FLAG_STRING("DEBUG", IFF_DEBUG, link->flags, flags),
461                                FLAG_STRING("ECHO", IFF_ECHO, link->flags, flags));
462
463                 unknown_flags = ~(IFF_LOOPBACK | IFF_MASTER | IFF_SLAVE | IFF_UP |
464                                   IFF_DORMANT | IFF_LOWER_UP | IFF_RUNNING |
465                                   IFF_MULTICAST | IFF_BROADCAST | IFF_POINTOPOINT |
466                                   IFF_PROMISC | IFF_ALLMULTI | IFF_PORTSEL |
467                                   IFF_AUTOMEDIA | IFF_DYNAMIC | IFF_NOARP |
468                                   IFF_NOTRAILERS | IFF_DEBUG | IFF_ECHO);
469                 unknown_flags_added = ((link->flags ^ flags) & flags & unknown_flags);
470                 unknown_flags_removed = ((link->flags ^ flags) & link->flags & unknown_flags);
471
472                 /* link flags are currently at most 18 bits, let's align to
473                  * printing 20 */
474                 if (unknown_flags_added)
475                         log_link_debug(link,
476                                        "Unknown link flags gained: %#.5x (ignoring)",
477                                        unknown_flags_added);
478
479                 if (unknown_flags_removed)
480                         log_link_debug(link,
481                                        "Unknown link flags lost: %#.5x (ignoring)",
482                                        unknown_flags_removed);
483         }
484
485         link->flags = flags;
486         link->kernel_operstate = operstate;
487
488         link_update_operstate(link, true);
489
490         return 0;
491 }
492
493 static int link_new(Manager *manager, sd_netlink_message *message, Link **ret) {
494         _cleanup_(link_unrefp) Link *link = NULL;
495         uint16_t type;
496         const char *ifname, *kind = NULL;
497         int r, ifindex;
498         unsigned short iftype;
499
500         assert(manager);
501         assert(message);
502         assert(ret);
503
504         /* check for link kind */
505         r = sd_netlink_message_enter_container(message, IFLA_LINKINFO);
506         if (r == 0) {
507                 (void) sd_netlink_message_read_string(message, IFLA_INFO_KIND, &kind);
508                 r = sd_netlink_message_exit_container(message);
509                 if (r < 0)
510                         return r;
511         }
512
513         r = sd_netlink_message_get_type(message, &type);
514         if (r < 0)
515                 return r;
516         else if (type != RTM_NEWLINK)
517                 return -EINVAL;
518
519         r = sd_rtnl_message_link_get_ifindex(message, &ifindex);
520         if (r < 0)
521                 return r;
522         else if (ifindex <= 0)
523                 return -EINVAL;
524
525         r = sd_rtnl_message_link_get_type(message, &iftype);
526         if (r < 0)
527                 return r;
528
529         r = sd_netlink_message_read_string(message, IFLA_IFNAME, &ifname);
530         if (r < 0)
531                 return r;
532
533         link = new(Link, 1);
534         if (!link)
535                 return -ENOMEM;
536
537         *link = (Link) {
538                 .n_ref = 1,
539                 .manager = manager,
540                 .state = LINK_STATE_PENDING,
541                 .rtnl_extended_attrs = true,
542                 .ifindex = ifindex,
543                 .iftype = iftype,
544         };
545
546         link->ifname = strdup(ifname);
547         if (!link->ifname)
548                 return -ENOMEM;
549
550         if (kind) {
551                 link->kind = strdup(kind);
552                 if (!link->kind)
553                         return -ENOMEM;
554         }
555
556         r = sd_netlink_message_read_u32(message, IFLA_MASTER, (uint32_t *)&link->master_ifindex);
557         if (r < 0)
558                 log_link_debug_errno(link, r, "New device has no master, continuing without");
559
560         r = sd_netlink_message_read_ether_addr(message, IFLA_ADDRESS, &link->mac);
561         if (r < 0)
562                 log_link_debug_errno(link, r, "MAC address not found for new device, continuing without");
563
564         if (asprintf(&link->state_file, "/run/systemd/netif/links/%d", link->ifindex) < 0)
565                 return -ENOMEM;
566
567         if (asprintf(&link->lease_file, "/run/systemd/netif/leases/%d", link->ifindex) < 0)
568                 return -ENOMEM;
569
570         if (asprintf(&link->lldp_file, "/run/systemd/netif/lldp/%d", link->ifindex) < 0)
571                 return -ENOMEM;
572
573         r = hashmap_ensure_allocated(&manager->links, NULL);
574         if (r < 0)
575                 return r;
576
577         r = hashmap_put(manager->links, INT_TO_PTR(link->ifindex), link);
578         if (r < 0)
579                 return r;
580
581         r = link_update_flags(link, message, false);
582         if (r < 0)
583                 return r;
584
585         *ret = TAKE_PTR(link);
586
587         return 0;
588 }
589
590 static Link *link_free(Link *link) {
591         Address *address;
592
593         assert(link);
594
595         link->routes = set_free_with_destructor(link->routes, route_free);
596         link->routes_foreign = set_free_with_destructor(link->routes_foreign, route_free);
597
598         link->addresses = set_free_with_destructor(link->addresses, address_free);
599         link->addresses_foreign = set_free_with_destructor(link->addresses_foreign, address_free);
600
601         while ((address = link->pool_addresses)) {
602                 LIST_REMOVE(addresses, link->pool_addresses, address);
603                 address_free(address);
604         }
605
606         sd_dhcp_server_unref(link->dhcp_server);
607         sd_dhcp_client_unref(link->dhcp_client);
608         sd_dhcp_lease_unref(link->dhcp_lease);
609
610         link_lldp_emit_stop(link);
611
612         free(link->lease_file);
613
614         sd_lldp_unref(link->lldp);
615         free(link->lldp_file);
616
617         ndisc_flush(link);
618
619         sd_ipv4ll_unref(link->ipv4ll);
620         sd_dhcp6_client_unref(link->dhcp6_client);
621         sd_ndisc_unref(link->ndisc);
622         sd_radv_unref(link->radv);
623
624         free(link->ifname);
625         free(link->kind);
626
627         (void) unlink(link->state_file);
628         free(link->state_file);
629
630         sd_device_unref(link->sd_device);
631
632         hashmap_free(link->bound_to_links);
633         hashmap_free(link->bound_by_links);
634
635         set_free_with_destructor(link->slaves, link_unref);
636
637         network_unref(link->network);
638
639         return mfree(link);
640 }
641
642 DEFINE_TRIVIAL_REF_UNREF_FUNC(Link, link, link_free);
643
644 int link_get(Manager *m, int ifindex, Link **ret) {
645         Link *link;
646
647         assert(m);
648         assert(ifindex);
649         assert(ret);
650
651         link = hashmap_get(m->links, INT_TO_PTR(ifindex));
652         if (!link)
653                 return -ENODEV;
654
655         *ret = link;
656
657         return 0;
658 }
659
660 void link_set_state(Link *link, LinkState state) {
661         assert(link);
662
663         if (link->state == state)
664                 return;
665
666         log_link_debug(link, "State changed: %s -> %s",
667                        link_state_to_string(link->state),
668                        link_state_to_string(state));
669
670         link->state = state;
671
672         link_send_changed(link, "AdministrativeState", NULL);
673 }
674
675 static void link_enter_unmanaged(Link *link) {
676         assert(link);
677
678         link_set_state(link, LINK_STATE_UNMANAGED);
679
680         link_dirty(link);
681 }
682
683 int link_stop_clients(Link *link, bool may_keep_dhcp) {
684         int r = 0, k;
685
686         assert(link);
687         assert(link->manager);
688         assert(link->manager->event);
689
690         dhcp4_release_old_lease(link);
691
692         if (link->dhcp_client && (!may_keep_dhcp || !link->network ||
693                                   !FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_DHCP_ON_STOP))) {
694                 k = sd_dhcp_client_stop(link->dhcp_client);
695                 if (k < 0)
696                         r = log_link_warning_errno(link, k, "Could not stop DHCPv4 client: %m");
697         }
698
699         if (link->ipv4ll) {
700                 k = sd_ipv4ll_stop(link->ipv4ll);
701                 if (k < 0)
702                         r = log_link_warning_errno(link, k, "Could not stop IPv4 link-local: %m");
703         }
704
705         if (link->dhcp6_client) {
706                 k = sd_dhcp6_client_stop(link->dhcp6_client);
707                 if (k < 0)
708                         r = log_link_warning_errno(link, k, "Could not stop DHCPv6 client: %m");
709         }
710
711         if (link->ndisc) {
712                 k = sd_ndisc_stop(link->ndisc);
713                 if (k < 0)
714                         r = log_link_warning_errno(link, k, "Could not stop IPv6 Router Discovery: %m");
715         }
716
717         if (link->radv) {
718                 k = sd_radv_stop(link->radv);
719                 if (k < 0)
720                         r = log_link_warning_errno(link, k, "Could not stop IPv6 Router Advertisement: %m");
721         }
722
723         link_lldp_emit_stop(link);
724         return r;
725 }
726
727 void link_enter_failed(Link *link) {
728         assert(link);
729
730         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
731                 return;
732
733         log_link_warning(link, "Failed");
734
735         link_set_state(link, LINK_STATE_FAILED);
736
737         link_stop_clients(link, false);
738
739         link_dirty(link);
740 }
741
742 static Address* link_find_dhcp_server_address(Link *link) {
743         Address *address;
744
745         assert(link);
746         assert(link->network);
747
748         /* The first statically configured address if there is any */
749         LIST_FOREACH(addresses, address, link->network->static_addresses) {
750
751                 if (address->family != AF_INET)
752                         continue;
753
754                 if (in_addr_is_null(address->family, &address->in_addr))
755                         continue;
756
757                 return address;
758         }
759
760         /* If that didn't work, find a suitable address we got from the pool */
761         LIST_FOREACH(addresses, address, link->pool_addresses) {
762                 if (address->family != AF_INET)
763                         continue;
764
765                 return address;
766         }
767
768         return NULL;
769 }
770
771 static int link_join_netdevs_after_configured(Link *link) {
772         NetDev *netdev;
773         Iterator i;
774         int r;
775
776         HASHMAP_FOREACH(netdev, link->network->stacked_netdevs, i) {
777                 if (netdev->ifindex > 0)
778                         /* Assume already enslaved. */
779                         continue;
780
781                 if (netdev_get_create_type(netdev) != NETDEV_CREATE_AFTER_CONFIGURED)
782                         continue;
783
784                 log_struct(LOG_DEBUG,
785                            LOG_LINK_INTERFACE(link),
786                            LOG_NETDEV_INTERFACE(netdev),
787                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", netdev->ifname));
788
789                 r = netdev_join(netdev, link, NULL);
790                 if (r < 0)
791                         return log_struct_errno(LOG_WARNING, r,
792                                                 LOG_LINK_INTERFACE(link),
793                                                 LOG_NETDEV_INTERFACE(netdev),
794                                                 LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", netdev->ifname));
795         }
796
797         return 0;
798 }
799
800 static void link_enter_configured(Link *link) {
801         assert(link);
802         assert(link->network);
803
804         if (link->state != LINK_STATE_CONFIGURING)
805                 return;
806
807         log_link_info(link, "Configured");
808
809         link_set_state(link, LINK_STATE_CONFIGURED);
810
811         (void) link_join_netdevs_after_configured(link);
812
813         link_dirty(link);
814 }
815
816 static int link_request_set_routing_policy_rule(Link *link) {
817         RoutingPolicyRule *rule, *rrule = NULL;
818         int r;
819
820         assert(link);
821         assert(link->network);
822
823         link_set_state(link, LINK_STATE_CONFIGURING);
824         link->routing_policy_rules_configured = false;
825
826         LIST_FOREACH(rules, rule, link->network->rules) {
827                 r = routing_policy_rule_get(link->manager, rule->family, &rule->from, rule->from_prefixlen, &rule->to,
828                                             rule->to_prefixlen, rule->tos, rule->fwmark, rule->table, rule->iif, rule->oif,
829                                             rule->protocol, &rule->sport, &rule->dport, &rrule);
830                 if (r == 0) {
831                         (void) routing_policy_rule_make_local(link->manager, rrule);
832                         continue;
833                 }
834
835                 r = routing_policy_rule_configure(rule, link, NULL);
836                 if (r < 0) {
837                         log_link_warning_errno(link, r, "Could not set routing policy rules: %m");
838                         link_enter_failed(link);
839                         return r;
840                 }
841                 if (r > 0)
842                         link->routing_policy_rule_messages++;
843         }
844
845         routing_policy_rule_purge(link->manager, link);
846         if (link->routing_policy_rule_messages == 0) {
847                 link->routing_policy_rules_configured = true;
848                 link_check_ready(link);
849         } else
850                 log_link_debug(link, "Setting routing policy rules");
851
852         return 0;
853 }
854
855 static int route_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
856         int r;
857
858         assert(link);
859         assert(link->route_messages > 0);
860         assert(IN_SET(link->state, LINK_STATE_CONFIGURING,
861                       LINK_STATE_FAILED, LINK_STATE_LINGER));
862
863         link->route_messages--;
864
865         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
866                 return 1;
867
868         r = sd_netlink_message_get_errno(m);
869         if (r < 0 && r != -EEXIST)
870                 log_link_warning_errno(link, r, "Could not set route: %m");
871
872         if (link->route_messages == 0) {
873                 log_link_debug(link, "Routes set");
874                 link->static_routes_configured = true;
875                 link_check_ready(link);
876         }
877
878         return 1;
879 }
880
881 int link_request_set_routes(Link *link) {
882         enum {
883                 PHASE_NON_GATEWAY, /* First phase: Routes without a gateway */
884                 PHASE_GATEWAY,     /* Second phase: Routes with a gateway */
885                 _PHASE_MAX
886         } phase;
887         Route *rt;
888         int r;
889
890         assert(link);
891         assert(link->network);
892         assert(link->addresses_configured);
893         assert(link->address_messages == 0);
894         assert(link->state != _LINK_STATE_INVALID);
895
896         link_set_state(link, LINK_STATE_CONFIGURING);
897         link->static_routes_configured = false;
898
899         r = link_request_set_routing_policy_rule(link);
900         if (r < 0)
901                 return r;
902
903         /* First add the routes that enable us to talk to gateways, then add in the others that need a gateway. */
904         for (phase = 0; phase < _PHASE_MAX; phase++)
905                 LIST_FOREACH(routes, rt, link->network->static_routes) {
906
907                         if (in_addr_is_null(rt->family, &rt->gw) != (phase == PHASE_NON_GATEWAY))
908                                 continue;
909
910                         r = route_configure(rt, link, route_handler);
911                         if (r < 0) {
912                                 log_link_warning_errno(link, r, "Could not set routes: %m");
913                                 link_enter_failed(link);
914                                 return r;
915                         }
916                         if (r > 0)
917                                 link->route_messages++;
918                 }
919
920         if (link->route_messages == 0) {
921                 link->static_routes_configured = true;
922                 link_check_ready(link);
923         } else
924                 log_link_debug(link, "Setting routes");
925
926         return 0;
927 }
928
929 void link_check_ready(Link *link) {
930         Address *a;
931         Iterator i;
932
933         assert(link);
934
935         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
936                 return;
937
938         if (!link->network)
939                 return;
940
941         if (!link->addresses_configured)
942                 return;
943
944         if (!link->neighbors_configured)
945                 return;
946
947         SET_FOREACH(a, link->addresses, i)
948                 if (!address_is_ready(a))
949                         return;
950
951         if (!link->addresses_ready) {
952                 link->addresses_ready = true;
953                 link_request_set_routes(link);
954                 return;
955         }
956
957         if (!link->static_routes_configured)
958                 return;
959
960         if (!link->routing_policy_rules_configured)
961                 return;
962
963         if (link_ipv4ll_enabled(link, ADDRESS_FAMILY_IPV4) && !(link->ipv4ll_address && link->ipv4ll_route))
964                 return;
965
966         if (link_ipv6ll_enabled(link) &&
967             in_addr_is_null(AF_INET6, (const union in_addr_union*) &link->ipv6ll_address))
968                 return;
969
970         if ((link_dhcp4_enabled(link) || link_dhcp6_enabled(link)) &&
971             !link->dhcp4_configured &&
972             !link->dhcp6_configured &&
973             !(link_ipv4ll_enabled(link, ADDRESS_FAMILY_FALLBACK_IPV4) && link->ipv4ll_address && link->ipv4ll_route))
974                 /* When DHCP is enabled, at least one protocol must provide an address, or
975                  * an IPv4ll fallback address must be configured. */
976                 return;
977
978         if (link_ipv6_accept_ra_enabled(link) && !link->ndisc_configured)
979                 return;
980
981         if (link->state != LINK_STATE_CONFIGURED)
982                 link_enter_configured(link);
983
984         return;
985 }
986
987 static int link_request_set_neighbors(Link *link) {
988         Neighbor *neighbor;
989         int r;
990
991         assert(link);
992         assert(link->network);
993         assert(link->state != _LINK_STATE_INVALID);
994
995         link_set_state(link, LINK_STATE_CONFIGURING);
996         link->neighbors_configured = false;
997
998         LIST_FOREACH(neighbors, neighbor, link->network->neighbors) {
999                 r = neighbor_configure(neighbor, link, NULL);
1000                 if (r < 0) {
1001                         log_link_warning_errno(link, r, "Could not set neighbor: %m");
1002                         link_enter_failed(link);
1003                         return r;
1004                 }
1005         }
1006
1007         if (link->neighbor_messages == 0) {
1008                 link->neighbors_configured = true;
1009                 link_check_ready(link);
1010         } else
1011                 log_link_debug(link, "Setting neighbors");
1012
1013         return 0;
1014 }
1015
1016 static int address_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1017         int r;
1018
1019         assert(rtnl);
1020         assert(m);
1021         assert(link);
1022         assert(link->ifname);
1023         assert(link->address_messages > 0);
1024         assert(IN_SET(link->state, LINK_STATE_CONFIGURING,
1025                LINK_STATE_FAILED, LINK_STATE_LINGER));
1026
1027         link->address_messages--;
1028
1029         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1030                 return 1;
1031
1032         r = sd_netlink_message_get_errno(m);
1033         if (r < 0 && r != -EEXIST)
1034                 log_link_warning_errno(link, r, "could not set address: %m");
1035         else if (r >= 0)
1036                 manager_rtnl_process_address(rtnl, m, link->manager);
1037
1038         if (link->address_messages == 0) {
1039                 log_link_debug(link, "Addresses set");
1040                 link->addresses_configured = true;
1041                 link_check_ready(link);
1042         }
1043
1044         return 1;
1045 }
1046
1047 static int link_push_uplink_dns_to_dhcp_server(Link *link, sd_dhcp_server *s) {
1048         _cleanup_free_ struct in_addr *addresses = NULL;
1049         size_t n_addresses = 0, n_allocated = 0;
1050         unsigned i;
1051
1052         log_debug("Copying DNS server information from %s", link->ifname);
1053
1054         if (!link->network)
1055                 return 0;
1056
1057         for (i = 0; i < link->network->n_dns; i++) {
1058                 struct in_addr ia;
1059
1060                 /* Only look for IPv4 addresses */
1061                 if (link->network->dns[i].family != AF_INET)
1062                         continue;
1063
1064                 ia = link->network->dns[i].address.in;
1065
1066                 /* Never propagate obviously borked data */
1067                 if (in4_addr_is_null(&ia) || in4_addr_is_localhost(&ia))
1068                         continue;
1069
1070                 if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1))
1071                         return log_oom();
1072
1073                 addresses[n_addresses++] = ia;
1074         }
1075
1076         if (link->network->dhcp_use_dns && link->dhcp_lease) {
1077                 const struct in_addr *da = NULL;
1078                 int j, n;
1079
1080                 n = sd_dhcp_lease_get_dns(link->dhcp_lease, &da);
1081                 if (n > 0) {
1082
1083                         if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + n))
1084                                 return log_oom();
1085
1086                         for (j = 0; j < n; j++)
1087                                 if (in4_addr_is_non_local(&da[j]))
1088                                         addresses[n_addresses++] = da[j];
1089                 }
1090         }
1091
1092         if (n_addresses <= 0)
1093                 return 0;
1094
1095         return sd_dhcp_server_set_dns(s, addresses, n_addresses);
1096 }
1097
1098 static int link_push_uplink_ntp_to_dhcp_server(Link *link, sd_dhcp_server *s) {
1099         _cleanup_free_ struct in_addr *addresses = NULL;
1100         size_t n_addresses = 0, n_allocated = 0;
1101         char **a;
1102
1103         if (!link->network)
1104                 return 0;
1105
1106         log_debug("Copying NTP server information from %s", link->ifname);
1107
1108         STRV_FOREACH(a, link->network->ntp) {
1109                 union in_addr_union ia;
1110
1111                 /* Only look for IPv4 addresses */
1112                 if (in_addr_from_string(AF_INET, *a, &ia) <= 0)
1113                         continue;
1114
1115                 /* Never propagate obviously borked data */
1116                 if (in4_addr_is_null(&ia.in) || in4_addr_is_localhost(&ia.in))
1117                         continue;
1118
1119                 if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1))
1120                         return log_oom();
1121
1122                 addresses[n_addresses++] = ia.in;
1123         }
1124
1125         if (link->network->dhcp_use_ntp && link->dhcp_lease) {
1126                 const struct in_addr *da = NULL;
1127                 int j, n;
1128
1129                 n = sd_dhcp_lease_get_ntp(link->dhcp_lease, &da);
1130                 if (n > 0) {
1131
1132                         if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + n))
1133                                 return log_oom();
1134
1135                         for (j = 0; j < n; j++)
1136                                 if (in4_addr_is_non_local(&da[j]))
1137                                         addresses[n_addresses++] = da[j];
1138                 }
1139         }
1140
1141         if (n_addresses <= 0)
1142                 return 0;
1143
1144         return sd_dhcp_server_set_ntp(s, addresses, n_addresses);
1145 }
1146
1147 static int link_set_bridge_fdb(Link *link) {
1148         FdbEntry *fdb_entry;
1149         int r;
1150
1151         LIST_FOREACH(static_fdb_entries, fdb_entry, link->network->static_fdb_entries) {
1152                 r = fdb_entry_configure(link, fdb_entry);
1153                 if (r < 0)
1154                         return log_link_error_errno(link, r, "Failed to add MAC entry to static MAC table: %m");
1155         }
1156
1157         return 0;
1158 }
1159
1160 static int link_request_set_addresses(Link *link) {
1161         AddressLabel *label;
1162         Address *ad;
1163         int r;
1164
1165         assert(link);
1166         assert(link->network);
1167         assert(link->state != _LINK_STATE_INVALID);
1168
1169         link_set_state(link, LINK_STATE_CONFIGURING);
1170
1171         /* Reset all *_configured flags we are configuring. */
1172         link->addresses_configured = false;
1173         link->addresses_ready = false;
1174         link->neighbors_configured = false;
1175         link->static_routes_configured = false;
1176         link->routing_policy_rules_configured = false;
1177
1178         r = link_set_bridge_fdb(link);
1179         if (r < 0)
1180                 return r;
1181
1182         r = link_request_set_neighbors(link);
1183         if (r < 0)
1184                 return r;
1185
1186         LIST_FOREACH(addresses, ad, link->network->static_addresses) {
1187                 bool update;
1188
1189                 update = address_get(link, ad->family, &ad->in_addr, ad->prefixlen, NULL) > 0;
1190
1191                 r = address_configure(ad, link, address_handler, update);
1192                 if (r < 0) {
1193                         log_link_warning_errno(link, r, "Could not set addresses: %m");
1194                         link_enter_failed(link);
1195                         return r;
1196                 }
1197                 if (r > 0)
1198                         link->address_messages++;
1199         }
1200
1201         LIST_FOREACH(labels, label, link->network->address_labels) {
1202                 r = address_label_configure(label, link, NULL, false);
1203                 if (r < 0) {
1204                         log_link_warning_errno(link, r, "Could not set address label: %m");
1205                         link_enter_failed(link);
1206                         return r;
1207                 }
1208
1209                 link->address_label_messages++;
1210         }
1211
1212         /* now that we can figure out a default address for the dhcp server,
1213            start it */
1214         if (link_dhcp4_server_enabled(link) && (link->flags & IFF_UP)) {
1215                 Address *address;
1216                 Link *uplink = NULL;
1217                 bool acquired_uplink = false;
1218
1219                 address = link_find_dhcp_server_address(link);
1220                 if (!address) {
1221                         log_link_warning(link, "Failed to find suitable address for DHCPv4 server instance.");
1222                         link_enter_failed(link);
1223                         return 0;
1224                 }
1225
1226                 /* use the server address' subnet as the pool */
1227                 r = sd_dhcp_server_configure_pool(link->dhcp_server, &address->in_addr.in, address->prefixlen,
1228                                                   link->network->dhcp_server_pool_offset, link->network->dhcp_server_pool_size);
1229                 if (r < 0)
1230                         return r;
1231
1232                 /* TODO:
1233                 r = sd_dhcp_server_set_router(link->dhcp_server,
1234                                               &main_address->in_addr.in);
1235                 if (r < 0)
1236                         return r;
1237                 */
1238
1239                 if (link->network->dhcp_server_max_lease_time_usec > 0) {
1240                         r = sd_dhcp_server_set_max_lease_time(
1241                                         link->dhcp_server,
1242                                         DIV_ROUND_UP(link->network->dhcp_server_max_lease_time_usec, USEC_PER_SEC));
1243                         if (r < 0)
1244                                 return r;
1245                 }
1246
1247                 if (link->network->dhcp_server_default_lease_time_usec > 0) {
1248                         r = sd_dhcp_server_set_default_lease_time(
1249                                         link->dhcp_server,
1250                                         DIV_ROUND_UP(link->network->dhcp_server_default_lease_time_usec, USEC_PER_SEC));
1251                         if (r < 0)
1252                                 return r;
1253                 }
1254
1255                 if (link->network->dhcp_server_emit_dns) {
1256
1257                         if (link->network->n_dhcp_server_dns > 0)
1258                                 r = sd_dhcp_server_set_dns(link->dhcp_server, link->network->dhcp_server_dns, link->network->n_dhcp_server_dns);
1259                         else {
1260                                 uplink = manager_find_uplink(link->manager, link);
1261                                 acquired_uplink = true;
1262
1263                                 if (!uplink) {
1264                                         log_link_debug(link, "Not emitting DNS server information on link, couldn't find suitable uplink.");
1265                                         r = 0;
1266                                 } else
1267                                         r = link_push_uplink_dns_to_dhcp_server(uplink, link->dhcp_server);
1268                         }
1269                         if (r < 0)
1270                                 log_link_warning_errno(link, r, "Failed to set DNS server for DHCP server, ignoring: %m");
1271                 }
1272
1273                 if (link->network->dhcp_server_emit_ntp) {
1274
1275                         if (link->network->n_dhcp_server_ntp > 0)
1276                                 r = sd_dhcp_server_set_ntp(link->dhcp_server, link->network->dhcp_server_ntp, link->network->n_dhcp_server_ntp);
1277                         else {
1278                                 if (!acquired_uplink)
1279                                         uplink = manager_find_uplink(link->manager, link);
1280
1281                                 if (!uplink) {
1282                                         log_link_debug(link, "Not emitting NTP server information on link, couldn't find suitable uplink.");
1283                                         r = 0;
1284                                 } else
1285                                         r = link_push_uplink_ntp_to_dhcp_server(uplink, link->dhcp_server);
1286
1287                         }
1288                         if (r < 0)
1289                                 log_link_warning_errno(link, r, "Failed to set NTP server for DHCP server, ignoring: %m");
1290                 }
1291
1292                 r = sd_dhcp_server_set_emit_router(link->dhcp_server, link->network->dhcp_server_emit_router);
1293                 if (r < 0)
1294                         return log_link_warning_errno(link, r, "Failed to set router emission for DHCP server: %m");
1295
1296                 if (link->network->dhcp_server_emit_timezone) {
1297                         _cleanup_free_ char *buffer = NULL;
1298                         const char *tz = NULL;
1299
1300                         if (link->network->dhcp_server_timezone)
1301                                 tz = link->network->dhcp_server_timezone;
1302                         else {
1303                                 r = get_timezone(&buffer);
1304                                 if (r < 0)
1305                                         log_warning_errno(r, "Failed to determine timezone: %m");
1306                                 else
1307                                         tz = buffer;
1308                         }
1309
1310                         if (tz) {
1311                                 r = sd_dhcp_server_set_timezone(link->dhcp_server, tz);
1312                                 if (r < 0)
1313                                         return r;
1314                         }
1315                 }
1316                 if (!sd_dhcp_server_is_running(link->dhcp_server)) {
1317                         r = sd_dhcp_server_start(link->dhcp_server);
1318                         if (r < 0) {
1319                                 log_link_warning_errno(link, r, "Could not start DHCPv4 server instance: %m");
1320
1321                                 link_enter_failed(link);
1322
1323                                 return 0;
1324                         }
1325                 }
1326
1327                 log_link_debug(link, "Offering DHCPv4 leases");
1328         }
1329
1330         if (link->address_messages == 0) {
1331                 link->addresses_configured = true;
1332                 link_check_ready(link);
1333         } else
1334                 log_link_debug(link, "Setting addresses");
1335
1336         return 0;
1337 }
1338
1339 static int link_set_bridge_vlan(Link *link) {
1340         int r;
1341
1342         r = br_vlan_configure(link, link->network->pvid, link->network->br_vid_bitmap, link->network->br_untagged_bitmap);
1343         if (r < 0)
1344                 log_link_error_errno(link, r, "Failed to assign VLANs to bridge port: %m");
1345
1346         return r;
1347 }
1348
1349 static int link_set_proxy_arp(Link *link) {
1350         int r;
1351
1352         if (!link_proxy_arp_enabled(link))
1353                 return 0;
1354
1355         r = sysctl_write_ip_property_boolean(AF_INET, link->ifname, "proxy_arp", link->network->proxy_arp > 0);
1356         if (r < 0)
1357                 log_link_warning_errno(link, r, "Cannot configure proxy ARP for interface: %m");
1358
1359         return 0;
1360 }
1361
1362 static int link_configure_after_setting_mtu(Link *link);
1363
1364 static int set_mtu_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1365         int r;
1366
1367         assert(m);
1368         assert(link);
1369         assert(link->ifname);
1370
1371         link->setting_mtu = false;
1372
1373         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1374                 return 1;
1375
1376         r = sd_netlink_message_get_errno(m);
1377         if (r < 0) {
1378                 log_link_warning_errno(link, r, "Could not set MTU: %m");
1379                 return 1;
1380         }
1381
1382         log_link_debug(link, "Setting MTU done.");
1383
1384         if (link->state == LINK_STATE_INITIALIZED)
1385                 (void) link_configure_after_setting_mtu(link);
1386
1387         return 1;
1388 }
1389
1390 int link_set_mtu(Link *link, uint32_t mtu) {
1391         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1392         int r;
1393
1394         assert(link);
1395         assert(link->manager);
1396         assert(link->manager->rtnl);
1397
1398         if (mtu == 0 || link->setting_mtu)
1399                 return 0;
1400
1401         if (link->mtu == mtu)
1402                 return 0;
1403
1404         log_link_debug(link, "Setting MTU: %" PRIu32, mtu);
1405
1406         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1407         if (r < 0)
1408                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1409
1410         /* If IPv6 not configured (no static IPv6 address and IPv6LL autoconfiguration is disabled)
1411          * for this interface, then disable IPv6 else enable it. */
1412         (void) link_enable_ipv6(link);
1413
1414         /* IPv6 protocol requires a minimum MTU of IPV6_MTU_MIN(1280) bytes
1415          * on the interface. Bump up MTU bytes to IPV6_MTU_MIN. */
1416         if (link_ipv6_enabled(link) && mtu < IPV6_MIN_MTU) {
1417
1418                 log_link_warning(link, "Bumping MTU to " STRINGIFY(IPV6_MIN_MTU) ", as "
1419                                  "IPv6 is requested and requires a minimum MTU of " STRINGIFY(IPV6_MIN_MTU) " bytes: %m");
1420
1421                 mtu = IPV6_MIN_MTU;
1422         }
1423
1424         r = sd_netlink_message_append_u32(req, IFLA_MTU, mtu);
1425         if (r < 0)
1426                 return log_link_error_errno(link, r, "Could not append MTU: %m");
1427
1428         r = netlink_call_async(link->manager->rtnl, NULL, req, set_mtu_handler,
1429                                link_netlink_destroy_callback, link);
1430         if (r < 0)
1431                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1432
1433         link_ref(link);
1434         link->setting_mtu = true;
1435
1436         return 0;
1437 }
1438
1439 static bool link_reduces_vlan_mtu(Link *link) {
1440         /* See netif_reduces_vlan_mtu() in kernel. */
1441         return streq_ptr(link->kind, "macsec");
1442 }
1443
1444 static uint32_t link_get_requested_mtu_by_stacked_netdevs(Link *link) {
1445         uint32_t mtu = 0;
1446         NetDev *dev;
1447         Iterator i;
1448
1449         HASHMAP_FOREACH(dev, link->network->stacked_netdevs, i)
1450                 if (dev->kind == NETDEV_KIND_VLAN && dev->mtu > 0)
1451                         /* See vlan_dev_change_mtu() in kernel. */
1452                         mtu = MAX(mtu, link_reduces_vlan_mtu(link) ? dev->mtu + 4 : dev->mtu);
1453
1454                 else if (dev->kind == NETDEV_KIND_MACVLAN && dev->mtu > mtu)
1455                         /* See macvlan_change_mtu() in kernel. */
1456                         mtu = dev->mtu;
1457
1458         return mtu;
1459 }
1460
1461 static int link_configure_mtu(Link *link) {
1462         uint32_t mtu;
1463
1464         assert(link);
1465         assert(link->network);
1466
1467         if (link->network->mtu > 0)
1468                 return link_set_mtu(link, link->network->mtu);
1469
1470         mtu = link_get_requested_mtu_by_stacked_netdevs(link);
1471         if (link->mtu >= mtu)
1472                 return 0;
1473
1474         log_link_notice(link, "Bumping MTU bytes from %"PRIu32" to %"PRIu32" because of stacked device. "
1475                         "If it is not desired, then please explicitly specify MTUBytes= setting.",
1476                         link->mtu, mtu);
1477
1478         return link_set_mtu(link, mtu);
1479 }
1480
1481 static int set_flags_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1482         int r;
1483
1484         assert(m);
1485         assert(link);
1486         assert(link->ifname);
1487
1488         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1489                 return 1;
1490
1491         r = sd_netlink_message_get_errno(m);
1492         if (r < 0)
1493                 log_link_warning_errno(link, r, "Could not set link flags: %m");
1494
1495         return 1;
1496 }
1497
1498 static int link_set_flags(Link *link) {
1499         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1500         unsigned ifi_change = 0;
1501         unsigned ifi_flags = 0;
1502         int r;
1503
1504         assert(link);
1505         assert(link->manager);
1506         assert(link->manager->rtnl);
1507
1508         if (link->flags & IFF_LOOPBACK)
1509                 return 0;
1510
1511         if (!link->network)
1512                 return 0;
1513
1514         if (link->network->arp < 0 && link->network->multicast < 0 && link->network->allmulticast < 0)
1515                 return 0;
1516
1517         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1518         if (r < 0)
1519                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1520
1521         if (link->network->arp >= 0) {
1522                 ifi_change |= IFF_NOARP;
1523                 SET_FLAG(ifi_flags, IFF_NOARP, link->network->arp == 0);
1524         }
1525
1526         if (link->network->multicast >= 0) {
1527                 ifi_change |= IFF_MULTICAST;
1528                 SET_FLAG(ifi_flags, IFF_MULTICAST, link->network->multicast);
1529         }
1530
1531         if (link->network->allmulticast >= 0) {
1532                 ifi_change |= IFF_ALLMULTI;
1533                 SET_FLAG(ifi_flags, IFF_ALLMULTI, link->network->allmulticast);
1534         }
1535
1536         r = sd_rtnl_message_link_set_flags(req, ifi_flags, ifi_change);
1537         if (r < 0)
1538                 return log_link_error_errno(link, r, "Could not set link flags: %m");
1539
1540         r = netlink_call_async(link->manager->rtnl, NULL, req, set_flags_handler,
1541                                link_netlink_destroy_callback, link);
1542         if (r < 0)
1543                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1544
1545         link_ref(link);
1546
1547         return 0;
1548 }
1549
1550 static int link_acquire_ipv6_conf(Link *link) {
1551         int r;
1552
1553         assert(link);
1554
1555         if (link_ipv6_accept_ra_enabled(link)) {
1556                 assert(link->ndisc);
1557
1558                 log_link_debug(link, "Discovering IPv6 routers");
1559
1560                 r = sd_ndisc_start(link->ndisc);
1561                 if (r < 0 && r != -EBUSY)
1562                         return log_link_warning_errno(link, r, "Could not start IPv6 Router Discovery: %m");
1563         }
1564
1565         if (link_radv_enabled(link)) {
1566                 assert(link->radv);
1567                 assert(in_addr_is_link_local(AF_INET6, (const union in_addr_union*)&link->ipv6ll_address) > 0);
1568
1569                 log_link_debug(link, "Starting IPv6 Router Advertisements");
1570
1571                 r = sd_radv_start(link->radv);
1572                 if (r < 0 && r != -EBUSY)
1573                         return log_link_warning_errno(link, r, "Could not start IPv6 Router Advertisement: %m");
1574         }
1575
1576         (void) dhcp6_request_prefix_delegation(link);
1577
1578         return 0;
1579 }
1580
1581 static int link_acquire_ipv4_conf(Link *link) {
1582         int r;
1583
1584         assert(link);
1585         assert(link->manager);
1586         assert(link->manager->event);
1587
1588         if (link_ipv4ll_enabled(link, ADDRESS_FAMILY_IPV4)) {
1589                 assert(link->ipv4ll);
1590
1591                 log_link_debug(link, "Acquiring IPv4 link-local address");
1592
1593                 r = sd_ipv4ll_start(link->ipv4ll);
1594                 if (r < 0)
1595                         return log_link_warning_errno(link, r, "Could not acquire IPv4 link-local address: %m");
1596         }
1597
1598         if (link_dhcp4_enabled(link)) {
1599                 assert(link->dhcp_client);
1600
1601                 log_link_debug(link, "Acquiring DHCPv4 lease");
1602
1603                 r = sd_dhcp_client_start(link->dhcp_client);
1604                 if (r < 0)
1605                         return log_link_warning_errno(link, r, "Could not acquire DHCPv4 lease: %m");
1606         }
1607
1608         return 0;
1609 }
1610
1611 static int link_acquire_conf(Link *link) {
1612         int r;
1613
1614         assert(link);
1615
1616         r = link_acquire_ipv4_conf(link);
1617         if (r < 0)
1618                 return r;
1619
1620         if (!in_addr_is_null(AF_INET6, (const union in_addr_union*) &link->ipv6ll_address)) {
1621                 r = link_acquire_ipv6_conf(link);
1622                 if (r < 0)
1623                         return r;
1624         }
1625
1626         if (link_lldp_emit_enabled(link)) {
1627                 r = link_lldp_emit_start(link);
1628                 if (r < 0)
1629                         return log_link_warning_errno(link, r, "Failed to start LLDP transmission: %m");
1630         }
1631
1632         return 0;
1633 }
1634
1635 bool link_has_carrier(Link *link) {
1636         /* see Documentation/networking/operstates.txt in the kernel sources */
1637
1638         if (link->kernel_operstate == IF_OPER_UP)
1639                 return true;
1640
1641         if (link->kernel_operstate == IF_OPER_UNKNOWN)
1642                 /* operstate may not be implemented, so fall back to flags */
1643                 if (FLAGS_SET(link->flags, IFF_LOWER_UP | IFF_RUNNING) &&
1644                     !FLAGS_SET(link->flags, IFF_DORMANT))
1645                         return true;
1646
1647         return false;
1648 }
1649
1650 static int link_address_genmode_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1651         int r;
1652
1653         assert(link);
1654
1655         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1656                 return 1;
1657
1658         r = sd_netlink_message_get_errno(m);
1659         if (r < 0)
1660                 log_link_warning_errno(link, r, "Could not set address genmode for interface: %m");
1661
1662         return 1;
1663 }
1664
1665 static int link_configure_addrgen_mode(Link *link) {
1666         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1667         uint8_t ipv6ll_mode;
1668         int r;
1669
1670         assert(link);
1671         assert(link->network);
1672         assert(link->manager);
1673         assert(link->manager->rtnl);
1674
1675         if (!socket_ipv6_is_supported())
1676                 return 0;
1677
1678         log_link_debug(link, "Setting address genmode for link");
1679
1680         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1681         if (r < 0)
1682                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1683
1684         r = sd_netlink_message_open_container(req, IFLA_AF_SPEC);
1685         if (r < 0)
1686                 return log_link_error_errno(link, r, "Could not open IFLA_AF_SPEC container: %m");
1687
1688         r = sd_netlink_message_open_container(req, AF_INET6);
1689         if (r < 0)
1690                 return log_link_error_errno(link, r, "Could not open AF_INET6 container: %m");
1691
1692         if (!link_ipv6ll_enabled(link))
1693                 ipv6ll_mode = IN6_ADDR_GEN_MODE_NONE;
1694         else if (sysctl_read_ip_property(AF_INET6, link->ifname, "stable_secret", NULL) < 0)
1695                 /* The file may not exist. And event if it exists, when stable_secret is unset,
1696                  * reading the file fails with EIO. */
1697                 ipv6ll_mode = IN6_ADDR_GEN_MODE_EUI64;
1698         else
1699                 ipv6ll_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
1700
1701         r = sd_netlink_message_append_u8(req, IFLA_INET6_ADDR_GEN_MODE, ipv6ll_mode);
1702         if (r < 0)
1703                 return log_link_error_errno(link, r, "Could not append IFLA_INET6_ADDR_GEN_MODE: %m");
1704
1705         r = sd_netlink_message_close_container(req);
1706         if (r < 0)
1707                 return log_link_error_errno(link, r, "Could not close AF_INET6 container: %m");
1708
1709         r = sd_netlink_message_close_container(req);
1710         if (r < 0)
1711                 return log_link_error_errno(link, r, "Could not close IFLA_AF_SPEC container: %m");
1712
1713         r = netlink_call_async(link->manager->rtnl, NULL, req, link_address_genmode_handler,
1714                                link_netlink_destroy_callback, link);
1715         if (r < 0)
1716                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1717
1718         link_ref(link);
1719
1720         return 0;
1721 }
1722
1723 static int link_up_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1724         int r;
1725
1726         assert(link);
1727
1728         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1729                 return 1;
1730
1731         r = sd_netlink_message_get_errno(m);
1732         if (r < 0)
1733                 /* we warn but don't fail the link, as it may be brought up later */
1734                 log_link_warning_errno(link, r, "Could not bring up interface: %m");
1735
1736         return 1;
1737 }
1738
1739 static int link_up(Link *link) {
1740         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1741         int r;
1742
1743         assert(link);
1744         assert(link->network);
1745         assert(link->manager);
1746         assert(link->manager->rtnl);
1747
1748         log_link_debug(link, "Bringing link up");
1749
1750         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1751         if (r < 0)
1752                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1753
1754         /* set it free if not enslaved with networkd */
1755         if (!link->network->bridge && !link->network->bond && !link->network->vrf) {
1756                 r = sd_netlink_message_append_u32(req, IFLA_MASTER, 0);
1757                 if (r < 0)
1758                         return log_link_error_errno(link, r, "Could not append IFLA_MASTER attribute: %m");
1759         }
1760
1761         r = sd_rtnl_message_link_set_flags(req, IFF_UP, IFF_UP);
1762         if (r < 0)
1763                 return log_link_error_errno(link, r, "Could not set link flags: %m");
1764
1765         if (link->network->mac) {
1766                 r = sd_netlink_message_append_ether_addr(req, IFLA_ADDRESS, link->network->mac);
1767                 if (r < 0)
1768                         return log_link_error_errno(link, r, "Could not set MAC address: %m");
1769         }
1770
1771         r = netlink_call_async(link->manager->rtnl, NULL, req, link_up_handler,
1772                                link_netlink_destroy_callback, link);
1773         if (r < 0)
1774                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1775
1776         link_ref(link);
1777
1778         return 0;
1779 }
1780
1781 static int link_down_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1782         int r;
1783
1784         assert(link);
1785
1786         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1787                 return 1;
1788
1789         r = sd_netlink_message_get_errno(m);
1790         if (r < 0)
1791                 log_link_warning_errno(link, r, "Could not bring down interface: %m");
1792
1793         return 1;
1794 }
1795
1796 int link_down(Link *link, link_netlink_message_handler_t callback) {
1797         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1798         int r;
1799
1800         assert(link);
1801         assert(link->manager);
1802         assert(link->manager->rtnl);
1803
1804         log_link_debug(link, "Bringing link down");
1805
1806         r = sd_rtnl_message_new_link(link->manager->rtnl, &req,
1807                                      RTM_SETLINK, link->ifindex);
1808         if (r < 0)
1809                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1810
1811         r = sd_rtnl_message_link_set_flags(req, 0, IFF_UP);
1812         if (r < 0)
1813                 return log_link_error_errno(link, r, "Could not set link flags: %m");
1814
1815         r = netlink_call_async(link->manager->rtnl, NULL, req,
1816                                callback ?: link_down_handler,
1817                                link_netlink_destroy_callback, link);
1818         if (r < 0)
1819                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1820
1821         link_ref(link);
1822
1823         return 0;
1824 }
1825
1826 static int link_handle_bound_to_list(Link *link) {
1827         Link *l;
1828         Iterator i;
1829         int r;
1830         bool required_up = false;
1831         bool link_is_up = false;
1832
1833         assert(link);
1834
1835         if (hashmap_isempty(link->bound_to_links))
1836                 return 0;
1837
1838         if (link->flags & IFF_UP)
1839                 link_is_up = true;
1840
1841         HASHMAP_FOREACH (l, link->bound_to_links, i)
1842                 if (link_has_carrier(l)) {
1843                         required_up = true;
1844                         break;
1845                 }
1846
1847         if (!required_up && link_is_up) {
1848                 r = link_down(link, NULL);
1849                 if (r < 0)
1850                         return r;
1851         } else if (required_up && !link_is_up) {
1852                 r = link_up(link);
1853                 if (r < 0)
1854                         return r;
1855         }
1856
1857         return 0;
1858 }
1859
1860 static int link_handle_bound_by_list(Link *link) {
1861         Iterator i;
1862         Link *l;
1863         int r;
1864
1865         assert(link);
1866
1867         if (hashmap_isempty(link->bound_by_links))
1868                 return 0;
1869
1870         HASHMAP_FOREACH (l, link->bound_by_links, i) {
1871                 r = link_handle_bound_to_list(l);
1872                 if (r < 0)
1873                         return r;
1874         }
1875
1876         return 0;
1877 }
1878
1879 static int link_put_carrier(Link *link, Link *carrier, Hashmap **h) {
1880         int r;
1881
1882         assert(link);
1883         assert(carrier);
1884
1885         if (link == carrier)
1886                 return 0;
1887
1888         if (hashmap_get(*h, INT_TO_PTR(carrier->ifindex)))
1889                 return 0;
1890
1891         r = hashmap_ensure_allocated(h, NULL);
1892         if (r < 0)
1893                 return r;
1894
1895         r = hashmap_put(*h, INT_TO_PTR(carrier->ifindex), carrier);
1896         if (r < 0)
1897                 return r;
1898
1899         return 0;
1900 }
1901
1902 static int link_new_bound_by_list(Link *link) {
1903         Manager *m;
1904         Link *carrier;
1905         Iterator i;
1906         int r;
1907         bool list_updated = false;
1908
1909         assert(link);
1910         assert(link->manager);
1911
1912         m = link->manager;
1913
1914         HASHMAP_FOREACH(carrier, m->links, i) {
1915                 if (!carrier->network)
1916                         continue;
1917
1918                 if (strv_isempty(carrier->network->bind_carrier))
1919                         continue;
1920
1921                 if (strv_fnmatch(carrier->network->bind_carrier, link->ifname, 0)) {
1922                         r = link_put_carrier(link, carrier, &link->bound_by_links);
1923                         if (r < 0)
1924                                 return r;
1925
1926                         list_updated = true;
1927                 }
1928         }
1929
1930         if (list_updated)
1931                 link_dirty(link);
1932
1933         HASHMAP_FOREACH(carrier, link->bound_by_links, i) {
1934                 r = link_put_carrier(carrier, link, &carrier->bound_to_links);
1935                 if (r < 0)
1936                         return r;
1937
1938                 link_dirty(carrier);
1939         }
1940
1941         return 0;
1942 }
1943
1944 static int link_new_bound_to_list(Link *link) {
1945         Manager *m;
1946         Link *carrier;
1947         Iterator i;
1948         int r;
1949         bool list_updated = false;
1950
1951         assert(link);
1952         assert(link->manager);
1953
1954         if (!link->network)
1955                 return 0;
1956
1957         if (strv_isempty(link->network->bind_carrier))
1958                 return 0;
1959
1960         m = link->manager;
1961
1962         HASHMAP_FOREACH (carrier, m->links, i) {
1963                 if (strv_fnmatch(link->network->bind_carrier, carrier->ifname, 0)) {
1964                         r = link_put_carrier(link, carrier, &link->bound_to_links);
1965                         if (r < 0)
1966                                 return r;
1967
1968                         list_updated = true;
1969                 }
1970         }
1971
1972         if (list_updated)
1973                 link_dirty(link);
1974
1975         HASHMAP_FOREACH (carrier, link->bound_to_links, i) {
1976                 r = link_put_carrier(carrier, link, &carrier->bound_by_links);
1977                 if (r < 0)
1978                         return r;
1979
1980                 link_dirty(carrier);
1981         }
1982
1983         return 0;
1984 }
1985
1986 static int link_new_carrier_maps(Link *link) {
1987         int r;
1988
1989         r = link_new_bound_by_list(link);
1990         if (r < 0)
1991                 return r;
1992
1993         r = link_handle_bound_by_list(link);
1994         if (r < 0)
1995                 return r;
1996
1997         r = link_new_bound_to_list(link);
1998         if (r < 0)
1999                 return r;
2000
2001         r = link_handle_bound_to_list(link);
2002         if (r < 0)
2003                 return r;
2004
2005         return 0;
2006 }
2007
2008 static void link_free_bound_to_list(Link *link) {
2009         Link *bound_to;
2010         Iterator i;
2011
2012         HASHMAP_FOREACH (bound_to, link->bound_to_links, i) {
2013                 hashmap_remove(link->bound_to_links, INT_TO_PTR(bound_to->ifindex));
2014
2015                 if (hashmap_remove(bound_to->bound_by_links, INT_TO_PTR(link->ifindex)))
2016                         link_dirty(bound_to);
2017         }
2018
2019         return;
2020 }
2021
2022 static void link_free_bound_by_list(Link *link) {
2023         Link *bound_by;
2024         Iterator i;
2025
2026         HASHMAP_FOREACH (bound_by, link->bound_by_links, i) {
2027                 hashmap_remove(link->bound_by_links, INT_TO_PTR(bound_by->ifindex));
2028
2029                 if (hashmap_remove(bound_by->bound_to_links, INT_TO_PTR(link->ifindex))) {
2030                         link_dirty(bound_by);
2031                         link_handle_bound_to_list(bound_by);
2032                 }
2033         }
2034
2035         return;
2036 }
2037
2038 static void link_free_carrier_maps(Link *link) {
2039         bool list_updated = false;
2040
2041         assert(link);
2042
2043         if (!hashmap_isempty(link->bound_to_links)) {
2044                 link_free_bound_to_list(link);
2045                 list_updated = true;
2046         }
2047
2048         if (!hashmap_isempty(link->bound_by_links)) {
2049                 link_free_bound_by_list(link);
2050                 list_updated = true;
2051         }
2052
2053         if (list_updated)
2054                 link_dirty(link);
2055
2056         return;
2057 }
2058
2059 static int link_append_to_master(Link *link, NetDev *netdev) {
2060         Link *master;
2061         int r;
2062
2063         assert(link);
2064         assert(netdev);
2065
2066         r = link_get(link->manager, netdev->ifindex, &master);
2067         if (r < 0)
2068                 return r;
2069
2070         r = set_ensure_allocated(&master->slaves, NULL);
2071         if (r < 0)
2072                 return r;
2073
2074         r = set_put(master->slaves, link);
2075         if (r < 0)
2076                 return r;
2077
2078         link_ref(link);
2079         return 0;
2080 }
2081
2082 static void link_drop_from_master(Link *link, NetDev *netdev) {
2083         Link *master;
2084
2085         assert(link);
2086
2087         if (!link->manager || !netdev)
2088                 return;
2089
2090         if (link_get(link->manager, netdev->ifindex, &master) < 0)
2091                 return;
2092
2093         link_unref(set_remove(master->slaves, link));
2094 }
2095
2096 static void link_detach_from_manager(Link *link) {
2097         if (!link || !link->manager)
2098                 return;
2099
2100         link_unref(set_remove(link->manager->links_requesting_uuid, link));
2101         link_clean(link);
2102
2103         /* The following must be called at last. */
2104         assert_se(hashmap_remove(link->manager->links, INT_TO_PTR(link->ifindex)) == link);
2105         link_unref(link);
2106 }
2107
2108 void link_drop(Link *link) {
2109         if (!link || link->state == LINK_STATE_LINGER)
2110                 return;
2111
2112         link_set_state(link, LINK_STATE_LINGER);
2113
2114         link_free_carrier_maps(link);
2115
2116         if (link->network) {
2117                 link_drop_from_master(link, link->network->bridge);
2118                 link_drop_from_master(link, link->network->bond);
2119         }
2120
2121         log_link_debug(link, "Link removed");
2122
2123         (void) unlink(link->state_file);
2124         link_detach_from_manager(link);
2125 }
2126
2127 static int link_joined(Link *link) {
2128         int r;
2129
2130         assert(link);
2131         assert(link->network);
2132
2133         if (!hashmap_isempty(link->bound_to_links)) {
2134                 r = link_handle_bound_to_list(link);
2135                 if (r < 0)
2136                         return r;
2137         } else if (!(link->flags & IFF_UP)) {
2138                 r = link_up(link);
2139                 if (r < 0) {
2140                         link_enter_failed(link);
2141                         return r;
2142                 }
2143         }
2144
2145         if (link->network->bridge) {
2146                 r = link_set_bridge(link);
2147                 if (r < 0)
2148                         log_link_error_errno(link, r, "Could not set bridge message: %m");
2149
2150                 r = link_append_to_master(link, link->network->bridge);
2151                 if (r < 0)
2152                         log_link_error_errno(link, r, "Failed to add to bridge master's slave list: %m");
2153         }
2154
2155         if (link->network->bond) {
2156                 r = link_set_bond(link);
2157                 if (r < 0)
2158                         log_link_error_errno(link, r, "Could not set bond message: %m");
2159
2160                 r = link_append_to_master(link, link->network->bond);
2161                 if (r < 0)
2162                         log_link_error_errno(link, r, "Failed to add to bond master's slave list: %m");
2163         }
2164
2165         if (link->network->use_br_vlan &&
2166             (link->network->bridge || streq_ptr("bridge", link->kind))) {
2167                 r = link_set_bridge_vlan(link);
2168                 if (r < 0)
2169                         log_link_error_errno(link, r, "Could not set bridge vlan: %m");
2170         }
2171
2172         /* Skip setting up addresses until it gets carrier,
2173            or it would try to set addresses twice,
2174            which is bad for non-idempotent steps. */
2175         if (!link_has_carrier(link) && !link->network->configure_without_carrier)
2176                 return 0;
2177
2178         return link_request_set_addresses(link);
2179 }
2180
2181 static int netdev_join_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
2182         int r;
2183
2184         assert(link);
2185         assert(link->network);
2186         assert(link->enslaving > 0);
2187
2188         link->enslaving--;
2189
2190         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
2191                 return 1;
2192
2193         r = sd_netlink_message_get_errno(m);
2194         if (r < 0 && r != -EEXIST) {
2195                 log_link_error_errno(link, r, "Could not join netdev: %m");
2196                 link_enter_failed(link);
2197                 return 1;
2198         } else
2199                 log_link_debug(link, "Joined netdev");
2200
2201         if (link->enslaving == 0) {
2202                 link_joined(link);
2203         }
2204
2205         return 1;
2206 }
2207
2208 static int link_enter_join_netdev(Link *link) {
2209         NetDev *netdev;
2210         Iterator i;
2211         int r;
2212
2213         assert(link);
2214         assert(link->network);
2215         assert(link->state == LINK_STATE_INITIALIZED);
2216
2217         link_set_state(link, LINK_STATE_CONFIGURING);
2218
2219         link_dirty(link);
2220         link->enslaving = 0;
2221
2222         if (link->network->bond) {
2223                 if (link->network->bond->state == NETDEV_STATE_READY &&
2224                     link->network->bond->ifindex == link->master_ifindex)
2225                         return link_joined(link);
2226
2227                 log_struct(LOG_DEBUG,
2228                            LOG_LINK_INTERFACE(link),
2229                            LOG_NETDEV_INTERFACE(link->network->bond),
2230                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", link->network->bond->ifname));
2231
2232                 link->enslaving++;
2233
2234                 r = netdev_join(link->network->bond, link, netdev_join_handler);
2235                 if (r < 0) {
2236                         log_struct_errno(LOG_WARNING, r,
2237                                          LOG_LINK_INTERFACE(link),
2238                                          LOG_NETDEV_INTERFACE(link->network->bond),
2239                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", link->network->bond->ifname));
2240                         link_enter_failed(link);
2241                         return r;
2242                 }
2243         }
2244
2245         if (link->network->bridge) {
2246                 log_struct(LOG_DEBUG,
2247                            LOG_LINK_INTERFACE(link),
2248                            LOG_NETDEV_INTERFACE(link->network->bridge),
2249                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", link->network->bridge->ifname));
2250
2251                 link->enslaving++;
2252
2253                 r = netdev_join(link->network->bridge, link, netdev_join_handler);
2254                 if (r < 0) {
2255                         log_struct_errno(LOG_WARNING, r,
2256                                          LOG_LINK_INTERFACE(link),
2257                                          LOG_NETDEV_INTERFACE(link->network->bridge),
2258                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", link->network->bridge->ifname));
2259                         link_enter_failed(link);
2260                         return r;
2261                 }
2262         }
2263
2264         if (link->network->vrf) {
2265                 log_struct(LOG_DEBUG,
2266                            LOG_LINK_INTERFACE(link),
2267                            LOG_NETDEV_INTERFACE(link->network->vrf),
2268                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", link->network->vrf->ifname));
2269
2270                 link->enslaving++;
2271
2272                 r = netdev_join(link->network->vrf, link, netdev_join_handler);
2273                 if (r < 0) {
2274                         log_struct_errno(LOG_WARNING, r,
2275                                          LOG_LINK_INTERFACE(link),
2276                                          LOG_NETDEV_INTERFACE(link->network->vrf),
2277                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", link->network->vrf->ifname));
2278                         link_enter_failed(link);
2279                         return r;
2280                 }
2281         }
2282
2283         HASHMAP_FOREACH(netdev, link->network->stacked_netdevs, i) {
2284
2285                 if (netdev->ifindex > 0)
2286                         /* Assume already enslaved. */
2287                         continue;
2288
2289                 if (netdev_get_create_type(netdev) != NETDEV_CREATE_STACKED)
2290                         continue;
2291
2292                 log_struct(LOG_DEBUG,
2293                            LOG_LINK_INTERFACE(link),
2294                            LOG_NETDEV_INTERFACE(netdev),
2295                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", netdev->ifname));
2296
2297                 link->enslaving++;
2298
2299                 r = netdev_join(netdev, link, netdev_join_handler);
2300                 if (r < 0) {
2301                         log_struct_errno(LOG_WARNING, r,
2302                                          LOG_LINK_INTERFACE(link),
2303                                          LOG_NETDEV_INTERFACE(netdev),
2304                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", netdev->ifname));
2305                         link_enter_failed(link);
2306                         return r;
2307                 }
2308         }
2309
2310         if (link->enslaving == 0)
2311                 return link_joined(link);
2312
2313         return 0;
2314 }
2315
2316 static int link_set_ipv4_forward(Link *link) {
2317         int r;
2318
2319         if (!link_ipv4_forward_enabled(link))
2320                 return 0;
2321
2322         /* We propagate the forwarding flag from one interface to the
2323          * global setting one way. This means: as long as at least one
2324          * interface was configured at any time that had IP forwarding
2325          * enabled the setting will stay on for good. We do this
2326          * primarily to keep IPv4 and IPv6 packet forwarding behaviour
2327          * somewhat in sync (see below). */
2328
2329         r = sysctl_write_ip_property(AF_INET, NULL, "ip_forward", "1");
2330         if (r < 0)
2331                 log_link_warning_errno(link, r, "Cannot turn on IPv4 packet forwarding, ignoring: %m");
2332
2333         return 0;
2334 }
2335
2336 static int link_set_ipv6_forward(Link *link) {
2337         int r;
2338
2339         if (!link_ipv6_forward_enabled(link))
2340                 return 0;
2341
2342         /* On Linux, the IPv6 stack does not know a per-interface
2343          * packet forwarding setting: either packet forwarding is on
2344          * for all, or off for all. We hence don't bother with a
2345          * per-interface setting, but simply propagate the interface
2346          * flag, if it is set, to the global flag, one-way. Note that
2347          * while IPv4 would allow a per-interface flag, we expose the
2348          * same behaviour there and also propagate the setting from
2349          * one to all, to keep things simple (see above). */
2350
2351         r = sysctl_write_ip_property(AF_INET6, "all", "forwarding", "1");
2352         if (r < 0)
2353                 log_link_warning_errno(link, r, "Cannot configure IPv6 packet forwarding, ignoring: %m");
2354
2355         return 0;
2356 }
2357
2358 static int link_set_ipv6_privacy_extensions(Link *link) {
2359         IPv6PrivacyExtensions s;
2360         int r;
2361
2362         s = link_ipv6_privacy_extensions(link);
2363         if (s < 0)
2364                 return 0;
2365
2366         r = sysctl_write_ip_property_int(AF_INET6, link->ifname, "use_tempaddr", (int) link->network->ipv6_privacy_extensions);
2367         if (r < 0)
2368                 log_link_warning_errno(link, r, "Cannot configure IPv6 privacy extension for interface: %m");
2369
2370         return 0;
2371 }
2372
2373 static int link_set_ipv6_accept_ra(Link *link) {
2374         int r;
2375
2376         /* Make this a NOP if IPv6 is not available */
2377         if (!socket_ipv6_is_supported())
2378                 return 0;
2379
2380         if (link->flags & IFF_LOOPBACK)
2381                 return 0;
2382
2383         if (!link->network)
2384                 return 0;
2385
2386         r = sysctl_write_ip_property(AF_INET6, link->ifname, "accept_ra", "0");
2387         if (r < 0)
2388                 log_link_warning_errno(link, r, "Cannot disable kernel IPv6 accept_ra for interface: %m");
2389
2390         return 0;
2391 }
2392
2393 static int link_set_ipv6_dad_transmits(Link *link) {
2394         int r;
2395
2396         /* Make this a NOP if IPv6 is not available */
2397         if (!socket_ipv6_is_supported())
2398                 return 0;
2399
2400         if (link->flags & IFF_LOOPBACK)
2401                 return 0;
2402
2403         if (!link->network)
2404                 return 0;
2405
2406         if (link->network->ipv6_dad_transmits < 0)
2407                 return 0;
2408
2409         r = sysctl_write_ip_property_int(AF_INET6, link->ifname, "dad_transmits", link->network->ipv6_dad_transmits);
2410         if (r < 0)
2411                 log_link_warning_errno(link, r, "Cannot set IPv6 dad transmits for interface: %m");
2412
2413         return 0;
2414 }
2415
2416 static int link_set_ipv6_hop_limit(Link *link) {
2417         int r;
2418
2419         /* Make this a NOP if IPv6 is not available */
2420         if (!socket_ipv6_is_supported())
2421                 return 0;
2422
2423         if (link->flags & IFF_LOOPBACK)
2424                 return 0;
2425
2426         if (!link->network)
2427                 return 0;
2428
2429         if (link->network->ipv6_hop_limit < 0)
2430                 return 0;
2431
2432         r = sysctl_write_ip_property_int(AF_INET6, link->ifname, "hop_limit", link->network->ipv6_hop_limit);
2433         if (r < 0)
2434                 log_link_warning_errno(link, r, "Cannot set IPv6 hop limit for interface: %m");
2435
2436         return 0;
2437 }
2438
2439 static int link_set_ipv6_mtu(Link *link) {
2440         int r;
2441
2442         /* Make this a NOP if IPv6 is not available */
2443         if (!socket_ipv6_is_supported())
2444                 return 0;
2445
2446         if (link->flags & IFF_LOOPBACK)
2447                 return 0;
2448
2449         if (link->network->ipv6_mtu == 0)
2450                 return 0;
2451
2452         r = sysctl_write_ip_property_uint32(AF_INET6, link->ifname, "mtu", link->network->ipv6_mtu);
2453         if (r < 0)
2454                 log_link_warning_errno(link, r, "Cannot set IPv6 MTU for interface: %m");
2455
2456         return 0;
2457 }
2458
2459 static bool link_is_static_address_configured(Link *link, Address *address) {
2460         Address *net_address;
2461
2462         assert(link);
2463         assert(address);
2464
2465         if (!link->network)
2466                 return false;
2467
2468         LIST_FOREACH(addresses, net_address, link->network->static_addresses)
2469                 if (address_equal(net_address, address))
2470                         return true;
2471
2472         return false;
2473 }
2474
2475 static bool link_is_static_route_configured(Link *link, Route *route) {
2476         Route *net_route;
2477
2478         assert(link);
2479         assert(route);
2480
2481         if (!link->network)
2482                 return false;
2483
2484         LIST_FOREACH(routes, net_route, link->network->static_routes)
2485                 if (route_equal(net_route, route))
2486                         return true;
2487
2488         return false;
2489 }
2490
2491 static bool link_address_is_dynamic(Link *link, Address *address) {
2492         Route *route;
2493         Iterator i;
2494
2495         assert(link);
2496         assert(address);
2497
2498         if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME)
2499                 return true;
2500
2501         /* Even when the address is leased from a DHCP server, networkd assign the address
2502          * without lifetime when KeepConfiguration=dhcp. So, let's check that we have
2503          * corresponding routes with RTPROT_DHCP. */
2504         SET_FOREACH(route, link->routes_foreign, i) {
2505                 if (route->protocol != RTPROT_DHCP)
2506                         continue;
2507
2508                 if (address->family != route->family)
2509                         continue;
2510
2511                 if (in_addr_equal(address->family, &address->in_addr, &route->prefsrc))
2512                         return true;
2513         }
2514
2515         return false;
2516 }
2517
2518 static int link_drop_foreign_config(Link *link) {
2519         Address *address;
2520         Route *route;
2521         Iterator i;
2522         int r;
2523
2524         SET_FOREACH(address, link->addresses_foreign, i) {
2525                 /* we consider IPv6LL addresses to be managed by the kernel */
2526                 if (address->family == AF_INET6 && in_addr_is_link_local(AF_INET6, &address->in_addr) == 1)
2527                         continue;
2528
2529                 if (link_address_is_dynamic(link, address)) {
2530                         if (FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_DHCP))
2531                                 continue;
2532                 } else if (FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_STATIC))
2533                         continue;
2534
2535                 if (link_is_static_address_configured(link, address)) {
2536                         r = address_add(link, address->family, &address->in_addr, address->prefixlen, NULL);
2537                         if (r < 0)
2538                                 return log_link_error_errno(link, r, "Failed to add address: %m");
2539                 } else {
2540                         r = address_remove(address, link, NULL);
2541                         if (r < 0)
2542                                 return r;
2543                 }
2544         }
2545
2546         SET_FOREACH(route, link->routes_foreign, i) {
2547                 /* do not touch routes managed by the kernel */
2548                 if (route->protocol == RTPROT_KERNEL)
2549                         continue;
2550
2551                 if (route->protocol == RTPROT_STATIC &&
2552                     FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_STATIC))
2553                         continue;
2554
2555                 if (route->protocol == RTPROT_DHCP &&
2556                     FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_DHCP))
2557                         continue;
2558
2559                 if (link_is_static_route_configured(link, route)) {
2560                         r = route_add(link, route->family, &route->dst, route->dst_prefixlen, route->tos, route->priority, route->table, NULL);
2561                         if (r < 0)
2562                                 return r;
2563                 } else {
2564                         r = route_remove(route, link, NULL);
2565                         if (r < 0)
2566                                 return r;
2567                 }
2568         }
2569
2570         return 0;
2571 }
2572
2573 static int link_drop_config(Link *link) {
2574         Address *address, *pool_address;
2575         Route *route;
2576         Iterator i;
2577         int r;
2578
2579         SET_FOREACH(address, link->addresses, i) {
2580                 /* we consider IPv6LL addresses to be managed by the kernel */
2581                 if (address->family == AF_INET6 && in_addr_is_link_local(AF_INET6, &address->in_addr) == 1)
2582                         continue;
2583
2584                 r = address_remove(address, link, NULL);
2585                 if (r < 0)
2586                         return r;
2587
2588                 /* If this address came from an address pool, clean up the pool */
2589                 LIST_FOREACH(addresses, pool_address, link->pool_addresses) {
2590                         if (address_equal(address, pool_address)) {
2591                                 LIST_REMOVE(addresses, link->pool_addresses, pool_address);
2592                                 address_free(pool_address);
2593                                 break;
2594                         }
2595                 }
2596         }
2597
2598         SET_FOREACH(route, link->routes, i) {
2599                 /* do not touch routes managed by the kernel */
2600                 if (route->protocol == RTPROT_KERNEL)
2601                         continue;
2602
2603                 r = route_remove(route, link, NULL);
2604                 if (r < 0)
2605                         return r;
2606         }
2607
2608         ndisc_flush(link);
2609
2610         return 0;
2611 }
2612
2613 static int link_configure(Link *link) {
2614         int r;
2615
2616         assert(link);
2617         assert(link->network);
2618         assert(link->state == LINK_STATE_INITIALIZED);
2619
2620         if (STRPTR_IN_SET(link->kind, "can", "vcan", "vxcan"))
2621                 return link_configure_can(link);
2622
2623         /* Drop foreign config, but ignore loopback or critical devices.
2624          * We do not want to remove loopback address or addresses used for root NFS. */
2625         if (!(link->flags & IFF_LOOPBACK) &&
2626             link->network->keep_configuration != KEEP_CONFIGURATION_YES) {
2627                 r = link_drop_foreign_config(link);
2628                 if (r < 0)
2629                         return r;
2630         }
2631
2632         r = link_set_proxy_arp(link);
2633         if (r < 0)
2634                return r;
2635
2636         r = ipv6_proxy_ndp_addresses_configure(link);
2637         if (r < 0)
2638                 return r;
2639
2640         r = link_set_ipv4_forward(link);
2641         if (r < 0)
2642                 return r;
2643
2644         r = link_set_ipv6_forward(link);
2645         if (r < 0)
2646                 return r;
2647
2648         r = link_set_ipv6_privacy_extensions(link);
2649         if (r < 0)
2650                 return r;
2651
2652         r = link_set_ipv6_accept_ra(link);
2653         if (r < 0)
2654                 return r;
2655
2656         r = link_set_ipv6_dad_transmits(link);
2657         if (r < 0)
2658                 return r;
2659
2660         r = link_set_ipv6_hop_limit(link);
2661         if (r < 0)
2662                 return r;
2663
2664         r = link_set_flags(link);
2665         if (r < 0)
2666                 return r;
2667
2668         r = link_set_ipv6_mtu(link);
2669         if (r < 0)
2670                 return r;
2671
2672         if (link_ipv4ll_enabled(link, ADDRESS_FAMILY_IPV4 | ADDRESS_FAMILY_FALLBACK_IPV4)) {
2673                 r = ipv4ll_configure(link);
2674                 if (r < 0)
2675                         return r;
2676         }
2677
2678         if (link_dhcp4_enabled(link)) {
2679                 r = dhcp4_set_promote_secondaries(link);
2680                 if (r < 0)
2681                         return r;
2682
2683                 r = dhcp4_configure(link);
2684                 if (r < 0)
2685                         return r;
2686         }
2687
2688         if (link_dhcp4_server_enabled(link)) {
2689                 r = sd_dhcp_server_new(&link->dhcp_server, link->ifindex);
2690                 if (r < 0)
2691                         return r;
2692
2693                 r = sd_dhcp_server_attach_event(link->dhcp_server, NULL, 0);
2694                 if (r < 0)
2695                         return r;
2696         }
2697
2698         if (link_dhcp6_enabled(link) ||
2699             link_ipv6_accept_ra_enabled(link)) {
2700                 r = dhcp6_configure(link);
2701                 if (r < 0)
2702                         return r;
2703         }
2704
2705         if (link_ipv6_accept_ra_enabled(link)) {
2706                 r = ndisc_configure(link);
2707                 if (r < 0)
2708                         return r;
2709         }
2710
2711         if (link_radv_enabled(link)) {
2712                 r = radv_configure(link);
2713                 if (r < 0)
2714                         return r;
2715         }
2716
2717         if (link_lldp_rx_enabled(link)) {
2718                 r = link_lldp_rx_configure(link);
2719                 if (r < 0)
2720                         return r;
2721         }
2722
2723         r = link_configure_mtu(link);
2724         if (r < 0)
2725                 return r;
2726
2727         r = link_configure_addrgen_mode(link);
2728         if (r < 0)
2729                 return r;
2730
2731         return link_configure_after_setting_mtu(link);
2732 }
2733
2734 static int link_configure_after_setting_mtu(Link *link) {
2735         int r;
2736
2737         assert(link);
2738         assert(link->network);
2739         assert(link->state == LINK_STATE_INITIALIZED);
2740
2741         if (link->setting_mtu)
2742                 return 0;
2743
2744         if (link_has_carrier(link) || link->network->configure_without_carrier) {
2745                 r = link_acquire_conf(link);
2746                 if (r < 0)
2747                         return r;
2748         }
2749
2750         return link_enter_join_netdev(link);
2751 }
2752
2753 static int duid_set_uuid(DUID *duid, sd_id128_t uuid) {
2754         assert(duid);
2755
2756         if (duid->raw_data_len > 0)
2757                 return 0;
2758
2759         if (duid->type != DUID_TYPE_UUID)
2760                 return -EINVAL;
2761
2762         memcpy(&duid->raw_data, &uuid, sizeof(sd_id128_t));
2763         duid->raw_data_len = sizeof(sd_id128_t);
2764
2765         return 1;
2766 }
2767
2768 int get_product_uuid_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
2769         Manager *manager = userdata;
2770         const sd_bus_error *e;
2771         const void *a;
2772         size_t sz;
2773         DUID *duid;
2774         Link *link;
2775         int r;
2776
2777         assert(m);
2778         assert(manager);
2779
2780         e = sd_bus_message_get_error(m);
2781         if (e) {
2782                 log_error_errno(sd_bus_error_get_errno(e),
2783                                 "Could not get product UUID. Falling back to use machine-app-specific ID as DUID-UUID: %s",
2784                                 e->message);
2785                 goto configure;
2786         }
2787
2788         r = sd_bus_message_read_array(m, 'y', &a, &sz);
2789         if (r < 0)
2790                 goto configure;
2791
2792         if (sz != sizeof(sd_id128_t)) {
2793                 log_error("Invalid product UUID. Falling back to use machine-app-specific ID as DUID-UUID.");
2794                 goto configure;
2795         }
2796
2797         memcpy(&manager->product_uuid, a, sz);
2798         while ((duid = set_steal_first(manager->duids_requesting_uuid)))
2799                 (void) duid_set_uuid(duid, manager->product_uuid);
2800
2801         manager->duids_requesting_uuid = set_free(manager->duids_requesting_uuid);
2802
2803 configure:
2804         while ((link = set_steal_first(manager->links_requesting_uuid))) {
2805                 r = link_configure(link);
2806                 if (r < 0)
2807                         log_link_error_errno(link, r, "Failed to configure link: %m");
2808         }
2809
2810         manager->links_requesting_uuid = set_free(manager->links_requesting_uuid);
2811
2812         /* To avoid calling GetProductUUID() bus method so frequently, set the flag below
2813          * even if the method fails. */
2814         manager->has_product_uuid = true;
2815
2816         return 1;
2817 }
2818
2819 static bool link_requires_uuid(Link *link) {
2820         const DUID *duid;
2821
2822         assert(link);
2823         assert(link->manager);
2824         assert(link->network);
2825
2826         duid = link_get_duid(link);
2827         if (duid->type != DUID_TYPE_UUID || duid->raw_data_len != 0)
2828                 return false;
2829
2830         if (link_dhcp4_enabled(link) && IN_SET(link->network->dhcp_client_identifier, DHCP_CLIENT_ID_DUID, DHCP_CLIENT_ID_DUID_ONLY))
2831                 return true;
2832
2833         if (link_dhcp6_enabled(link) || link_ipv6_accept_ra_enabled(link))
2834                 return true;
2835
2836         return false;
2837 }
2838
2839 static int link_configure_duid(Link *link) {
2840         Manager *m;
2841         DUID *duid;
2842         int r;
2843
2844         assert(link);
2845         assert(link->manager);
2846         assert(link->network);
2847
2848         m = link->manager;
2849         duid = link_get_duid(link);
2850
2851         if (!link_requires_uuid(link))
2852                 return 1;
2853
2854         if (m->has_product_uuid) {
2855                 (void) duid_set_uuid(duid, m->product_uuid);
2856                 return 1;
2857         }
2858
2859         if (!m->links_requesting_uuid) {
2860                 r = manager_request_product_uuid(m, link);
2861                 if (r < 0) {
2862                         if (r == -ENOMEM)
2863                                 return r;
2864
2865                         log_link_warning_errno(link, r,
2866                                                "Failed to get product UUID. Falling back to use machine-app-specific ID as DUID-UUID: %m");
2867                         return 1;
2868                 }
2869         } else {
2870                 r = set_put(m->links_requesting_uuid, link);
2871                 if (r < 0)
2872                         return log_oom();
2873
2874                 r = set_put(m->duids_requesting_uuid, duid);
2875                 if (r < 0)
2876                         return log_oom();
2877         }
2878
2879         return 0;
2880 }
2881
2882 static int link_initialized_and_synced(Link *link) {
2883         Network *network;
2884         int r;
2885
2886         assert(link);
2887         assert(link->ifname);
2888         assert(link->manager);
2889
2890         /* We may get called either from the asynchronous netlink callback,
2891          * or directly for link_add() if running in a container. See link_add(). */
2892         if (!IN_SET(link->state, LINK_STATE_PENDING, LINK_STATE_INITIALIZED))
2893                 return 0;
2894
2895         log_link_debug(link, "Link state is up-to-date");
2896         link_set_state(link, LINK_STATE_INITIALIZED);
2897
2898         r = link_new_bound_by_list(link);
2899         if (r < 0)
2900                 return r;
2901
2902         r = link_handle_bound_by_list(link);
2903         if (r < 0)
2904                 return r;
2905
2906         if (!link->network) {
2907                 r = network_get(link->manager, link->sd_device, link->ifname,
2908                                 &link->mac, &network);
2909                 if (r == -ENOENT) {
2910                         link_enter_unmanaged(link);
2911                         return 0;
2912                 } else if (r == 0 && network->unmanaged) {
2913                         link_enter_unmanaged(link);
2914                         return 0;
2915                 } else if (r < 0)
2916                         return r;
2917
2918                 if (link->flags & IFF_LOOPBACK) {
2919                         if (network->link_local != ADDRESS_FAMILY_NO)
2920                                 log_link_debug(link, "Ignoring link-local autoconfiguration for loopback link");
2921
2922                         if (network->dhcp != ADDRESS_FAMILY_NO)
2923                                 log_link_debug(link, "Ignoring DHCP clients for loopback link");
2924
2925                         if (network->dhcp_server)
2926                                 log_link_debug(link, "Ignoring DHCP server for loopback link");
2927                 }
2928
2929                 r = network_apply(network, link);
2930                 if (r < 0)
2931                         return r;
2932         }
2933
2934         r = link_new_bound_to_list(link);
2935         if (r < 0)
2936                 return r;
2937
2938         /* link_configure_duid() returns 0 if it requests product UUID. In that case,
2939          * link_configure() is called later asynchronously. */
2940         r = link_configure_duid(link);
2941         if (r <= 0)
2942                 return r;
2943
2944         r = link_configure(link);
2945         if (r < 0)
2946                 return r;
2947
2948         return 0;
2949 }
2950
2951 static int link_initialized_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
2952         (void) link_initialized_and_synced(link);
2953         return 1;
2954 }
2955
2956 int link_initialized(Link *link, sd_device *device) {
2957         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
2958         int r;
2959
2960         assert(link);
2961         assert(link->manager);
2962         assert(link->manager->rtnl);
2963         assert(device);
2964
2965         if (link->state != LINK_STATE_PENDING)
2966                 return 0;
2967
2968         if (link->sd_device)
2969                 return 0;
2970
2971         log_link_debug(link, "udev initialized link");
2972         link_set_state(link, LINK_STATE_INITIALIZED);
2973
2974         link->sd_device = sd_device_ref(device);
2975
2976         /* udev has initialized the link, but we don't know if we have yet
2977          * processed the NEWLINK messages with the latest state. Do a GETLINK,
2978          * when it returns we know that the pending NEWLINKs have already been
2979          * processed and that we are up-to-date */
2980
2981         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_GETLINK,
2982                                      link->ifindex);
2983         if (r < 0)
2984                 return r;
2985
2986         r = netlink_call_async(link->manager->rtnl, NULL, req, link_initialized_handler,
2987                                link_netlink_destroy_callback, link);
2988         if (r < 0)
2989                 return r;
2990
2991         link_ref(link);
2992
2993         return 0;
2994 }
2995
2996 static int link_load(Link *link) {
2997         _cleanup_free_ char *network_file = NULL,
2998                             *addresses = NULL,
2999                             *routes = NULL,
3000                             *dhcp4_address = NULL,
3001                             *ipv4ll_address = NULL;
3002         union in_addr_union address;
3003         union in_addr_union route_dst;
3004         const char *p;
3005         int r;
3006
3007         assert(link);
3008
3009         r = parse_env_file(NULL, link->state_file,
3010                            "NETWORK_FILE", &network_file,
3011                            "ADDRESSES", &addresses,
3012                            "ROUTES", &routes,
3013                            "DHCP4_ADDRESS", &dhcp4_address,
3014                            "IPV4LL_ADDRESS", &ipv4ll_address);
3015         if (r < 0 && r != -ENOENT)
3016                 return log_link_error_errno(link, r, "Failed to read %s: %m", link->state_file);
3017
3018         if (network_file) {
3019                 Network *network;
3020                 char *suffix;
3021
3022                 /* drop suffix */
3023                 suffix = strrchr(network_file, '.');
3024                 if (!suffix) {
3025                         log_link_debug(link, "Failed to get network name from %s", network_file);
3026                         goto network_file_fail;
3027                 }
3028                 *suffix = '\0';
3029
3030                 r = network_get_by_name(link->manager, basename(network_file), &network);
3031                 if (r < 0) {
3032                         log_link_debug_errno(link, r, "Failed to get network %s: %m", basename(network_file));
3033                         goto network_file_fail;
3034                 }
3035
3036                 r = network_apply(network, link);
3037                 if (r < 0)
3038                         return log_link_error_errno(link, r, "Failed to apply network %s: %m", basename(network_file));
3039         }
3040
3041 network_file_fail:
3042
3043         if (addresses) {
3044                 p = addresses;
3045
3046                 for (;;) {
3047                         _cleanup_free_ char *address_str = NULL;
3048                         char *prefixlen_str;
3049                         int family;
3050                         unsigned char prefixlen;
3051
3052                         r = extract_first_word(&p, &address_str, NULL, 0);
3053                         if (r < 0) {
3054                                 log_link_debug_errno(link, r, "Failed to extract next address string: %m");
3055                                 continue;
3056                         }
3057                         if (r == 0)
3058                                 break;
3059
3060                         prefixlen_str = strchr(address_str, '/');
3061                         if (!prefixlen_str) {
3062                                 log_link_debug(link, "Failed to parse address and prefix length %s", address_str);
3063                                 continue;
3064                         }
3065
3066                         *prefixlen_str++ = '\0';
3067
3068                         r = sscanf(prefixlen_str, "%hhu", &prefixlen);
3069                         if (r != 1) {
3070                                 log_link_error(link, "Failed to parse prefixlen %s", prefixlen_str);
3071                                 continue;
3072                         }
3073
3074                         r = in_addr_from_string_auto(address_str, &family, &address);
3075                         if (r < 0) {
3076                                 log_link_debug_errno(link, r, "Failed to parse address %s: %m", address_str);
3077                                 continue;
3078                         }
3079
3080                         r = address_add(link, family, &address, prefixlen, NULL);
3081                         if (r < 0)
3082                                 return log_link_error_errno(link, r, "Failed to add address: %m");
3083                 }
3084         }
3085
3086         if (routes) {
3087                 p = routes;
3088
3089                 for (;;) {
3090                         Route *route;
3091                         _cleanup_free_ char *route_str = NULL;
3092                         _cleanup_(sd_event_source_unrefp) sd_event_source *expire = NULL;
3093                         usec_t lifetime;
3094                         char *prefixlen_str;
3095                         int family;
3096                         unsigned char prefixlen, tos, table;
3097                         uint32_t priority;
3098
3099                         r = extract_first_word(&p, &route_str, NULL, 0);
3100                         if (r < 0) {
3101                                 log_link_debug_errno(link, r, "Failed to extract next route string: %m");
3102                                 continue;
3103                         }
3104                         if (r == 0)
3105                                 break;
3106
3107                         prefixlen_str = strchr(route_str, '/');
3108                         if (!prefixlen_str) {
3109                                 log_link_debug(link, "Failed to parse route %s", route_str);
3110                                 continue;
3111                         }
3112
3113                         *prefixlen_str++ = '\0';
3114
3115                         r = sscanf(prefixlen_str, "%hhu/%hhu/%"SCNu32"/%hhu/"USEC_FMT, &prefixlen, &tos, &priority, &table, &lifetime);
3116                         if (r != 5) {
3117                                 log_link_debug(link,
3118                                                "Failed to parse destination prefix length, tos, priority, table or expiration %s",
3119                                                prefixlen_str);
3120                                 continue;
3121                         }
3122
3123                         r = in_addr_from_string_auto(route_str, &family, &route_dst);
3124                         if (r < 0) {
3125                                 log_link_debug_errno(link, r, "Failed to parse route destination %s: %m", route_str);
3126                                 continue;
3127                         }
3128
3129                         r = route_add(link, family, &route_dst, prefixlen, tos, priority, table, &route);
3130                         if (r < 0)
3131                                 return log_link_error_errno(link, r, "Failed to add route: %m");
3132
3133                         if (lifetime != USEC_INFINITY && !kernel_route_expiration_supported()) {
3134                                 r = sd_event_add_time(link->manager->event, &expire, clock_boottime_or_monotonic(), lifetime,
3135                                                       0, route_expire_handler, route);
3136                                 if (r < 0)
3137                                         log_link_warning_errno(link, r, "Could not arm route expiration handler: %m");
3138                         }
3139
3140                         route->lifetime = lifetime;
3141                         sd_event_source_unref(route->expire);
3142                         route->expire = TAKE_PTR(expire);
3143                 }
3144         }
3145
3146         if (dhcp4_address) {
3147                 r = in_addr_from_string(AF_INET, dhcp4_address, &address);
3148                 if (r < 0) {
3149                         log_link_debug_errno(link, r, "Failed to parse DHCPv4 address %s: %m", dhcp4_address);
3150                         goto dhcp4_address_fail;
3151                 }
3152
3153                 r = sd_dhcp_client_new(&link->dhcp_client, link->network ? link->network->dhcp_anonymize : 0);
3154                 if (r < 0)
3155                         return log_link_error_errno(link, r, "Failed to create DHCPv4 client: %m");
3156
3157                 r = sd_dhcp_client_set_request_address(link->dhcp_client, &address.in);
3158                 if (r < 0)
3159                         return log_link_error_errno(link, r, "Failed to set initial DHCPv4 address %s: %m", dhcp4_address);
3160         }
3161
3162 dhcp4_address_fail:
3163
3164         if (ipv4ll_address) {
3165                 r = in_addr_from_string(AF_INET, ipv4ll_address, &address);
3166                 if (r < 0) {
3167                         log_link_debug_errno(link, r, "Failed to parse IPv4LL address %s: %m", ipv4ll_address);
3168                         goto ipv4ll_address_fail;
3169                 }
3170
3171                 r = sd_ipv4ll_new(&link->ipv4ll);
3172                 if (r < 0)
3173                         return log_link_error_errno(link, r, "Failed to create IPv4LL client: %m");
3174
3175                 r = sd_ipv4ll_set_address(link->ipv4ll, &address.in);
3176                 if (r < 0)
3177                         return log_link_error_errno(link, r, "Failed to set initial IPv4LL address %s: %m", ipv4ll_address);
3178         }
3179
3180 ipv4ll_address_fail:
3181
3182         return 0;
3183 }
3184
3185 int link_add(Manager *m, sd_netlink_message *message, Link **ret) {
3186         _cleanup_(sd_device_unrefp) sd_device *device = NULL;
3187         char ifindex_str[2 + DECIMAL_STR_MAX(int)];
3188         Link *link;
3189         int r;
3190
3191         assert(m);
3192         assert(m->rtnl);
3193         assert(message);
3194         assert(ret);
3195
3196         r = link_new(m, message, ret);
3197         if (r < 0)
3198                 return r;
3199
3200         link = *ret;
3201
3202         log_link_debug(link, "Link %d added", link->ifindex);
3203
3204         r = link_load(link);
3205         if (r < 0)
3206                 return r;
3207
3208         if (detect_container() <= 0) {
3209                 /* not in a container, udev will be around */
3210                 sprintf(ifindex_str, "n%d", link->ifindex);
3211                 r = sd_device_new_from_device_id(&device, ifindex_str);
3212                 if (r < 0) {
3213                         log_link_warning_errno(link, r, "Could not find device: %m");
3214                         goto failed;
3215                 }
3216
3217                 r = sd_device_get_is_initialized(device);
3218                 if (r < 0) {
3219                         log_link_warning_errno(link, r, "Could not determine whether the device is initialized or not: %m");
3220                         goto failed;
3221                 }
3222                 if (r == 0) {
3223                         /* not yet ready */
3224                         log_link_debug(link, "link pending udev initialization...");
3225                         return 0;
3226                 }
3227
3228                 r = device_is_renaming(device);
3229                 if (r < 0) {
3230                         log_link_warning_errno(link, r, "Failed to determine the device is renamed or not: %m");
3231                         goto failed;
3232                 }
3233                 if (r > 0) {
3234                         log_link_debug(link, "Interface is under renaming, pending initialization.");
3235                         return 0;
3236                 }
3237
3238                 r = link_initialized(link, device);
3239                 if (r < 0)
3240                         goto failed;
3241         } else {
3242                 r = link_initialized_and_synced(link);
3243                 if (r < 0)
3244                         goto failed;
3245         }
3246
3247         return 0;
3248 failed:
3249         link_enter_failed(link);
3250         return r;
3251 }
3252
3253 int link_ipv6ll_gained(Link *link, const struct in6_addr *address) {
3254         int r;
3255
3256         assert(link);
3257
3258         log_link_info(link, "Gained IPv6LL");
3259
3260         link->ipv6ll_address = *address;
3261         link_check_ready(link);
3262
3263         if (IN_SET(link->state, LINK_STATE_CONFIGURING, LINK_STATE_CONFIGURED)) {
3264                 r = link_acquire_ipv6_conf(link);
3265                 if (r < 0) {
3266                         link_enter_failed(link);
3267                         return r;
3268                 }
3269         }
3270
3271         return 0;
3272 }
3273
3274 static int link_carrier_gained(Link *link) {
3275         int r;
3276
3277         assert(link);
3278
3279         if (IN_SET(link->state, LINK_STATE_CONFIGURING, LINK_STATE_CONFIGURED)) {
3280                 r = link_acquire_conf(link);
3281                 if (r < 0) {
3282                         link_enter_failed(link);
3283                         return r;
3284                 }
3285
3286                 r = link_request_set_addresses(link);
3287                 if (r < 0)
3288                         return r;
3289         }
3290
3291         r = link_handle_bound_by_list(link);
3292         if (r < 0)
3293                 return r;
3294
3295         return 0;
3296 }
3297
3298 static int link_carrier_lost(Link *link) {
3299         int r;
3300
3301         assert(link);
3302
3303         if (link->network && link->network->ignore_carrier_loss)
3304                 return 0;
3305
3306         /* Some devices reset itself while setting the MTU. This causes the DHCP client fall into a loop.
3307          * setting_mtu keep track whether the device got reset because of setting MTU and does not drop the
3308          * configuration and stop the clients as well. */
3309         if (link->setting_mtu)
3310                 return 0;
3311
3312         r = link_stop_clients(link, false);
3313         if (r < 0) {
3314                 link_enter_failed(link);
3315                 return r;
3316         }
3317
3318         if (link_dhcp4_server_enabled(link))
3319                 (void) sd_dhcp_server_stop(link->dhcp_server);
3320
3321         r = link_drop_config(link);
3322         if (r < 0)
3323                 return r;
3324
3325         if (!IN_SET(link->state, LINK_STATE_UNMANAGED, LINK_STATE_PENDING)) {
3326                 log_link_debug(link, "State is %s, dropping config", link_state_to_string(link->state));
3327                 r = link_drop_foreign_config(link);
3328                 if (r < 0)
3329                         return r;
3330         }
3331
3332         r = link_handle_bound_by_list(link);
3333         if (r < 0)
3334                 return r;
3335
3336         return 0;
3337 }
3338
3339 int link_carrier_reset(Link *link) {
3340         int r;
3341
3342         assert(link);
3343
3344         if (link_has_carrier(link)) {
3345                 r = link_carrier_lost(link);
3346                 if (r < 0)
3347                         return r;
3348
3349                 r = link_carrier_gained(link);
3350                 if (r < 0)
3351                         return r;
3352
3353                 log_link_info(link, "Reset carrier");
3354         }
3355
3356         return 0;
3357 }
3358
3359 int link_update(Link *link, sd_netlink_message *m) {
3360         struct ether_addr mac;
3361         const char *ifname;
3362         uint32_t mtu;
3363         bool had_carrier, carrier_gained, carrier_lost;
3364         int old_master, r;
3365
3366         assert(link);
3367         assert(link->ifname);
3368         assert(m);
3369
3370         if (link->state == LINK_STATE_LINGER) {
3371                 log_link_info(link, "Link re-added");
3372                 link_set_state(link, LINK_STATE_CONFIGURING);
3373
3374                 r = link_new_carrier_maps(link);
3375                 if (r < 0)
3376                         return r;
3377         }
3378
3379         r = sd_netlink_message_read_string(m, IFLA_IFNAME, &ifname);
3380         if (r >= 0 && !streq(ifname, link->ifname)) {
3381                 Manager *manager = link->manager;
3382
3383                 log_link_info(link, "Interface name change detected, %s has been renamed to %s.", link->ifname, ifname);
3384
3385                 link_drop(link);
3386                 r = link_add(manager, m, &link);
3387                 if (r < 0)
3388                         return r;
3389         }
3390
3391         r = sd_netlink_message_read_u32(m, IFLA_MTU, &mtu);
3392         if (r >= 0 && mtu > 0) {
3393                 link->mtu = mtu;
3394                 if (link->original_mtu == 0) {
3395                         link->original_mtu = mtu;
3396                         log_link_debug(link, "Saved original MTU: %" PRIu32, link->original_mtu);
3397                 }
3398
3399                 if (link->dhcp_client) {
3400                         r = sd_dhcp_client_set_mtu(link->dhcp_client,
3401                                                    link->mtu);
3402                         if (r < 0)
3403                                 return log_link_warning_errno(link, r, "Could not update MTU in DHCP client: %m");
3404                 }
3405
3406                 if (link->radv) {
3407                         r = sd_radv_set_mtu(link->radv, link->mtu);
3408                         if (r < 0)
3409                                 return log_link_warning_errno(link, r, "Could not set MTU for Router Advertisement: %m");
3410                 }
3411         }
3412
3413         /* The kernel may broadcast NEWLINK messages without the MAC address
3414            set, simply ignore them. */
3415         r = sd_netlink_message_read_ether_addr(m, IFLA_ADDRESS, &mac);
3416         if (r >= 0) {
3417                 if (memcmp(link->mac.ether_addr_octet, mac.ether_addr_octet,
3418                            ETH_ALEN)) {
3419
3420                         memcpy(link->mac.ether_addr_octet, mac.ether_addr_octet,
3421                                ETH_ALEN);
3422
3423                         log_link_debug(link, "MAC address: "
3424                                        "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
3425                                        mac.ether_addr_octet[0],
3426                                        mac.ether_addr_octet[1],
3427                                        mac.ether_addr_octet[2],
3428                                        mac.ether_addr_octet[3],
3429                                        mac.ether_addr_octet[4],
3430                                        mac.ether_addr_octet[5]);
3431
3432                         if (link->ipv4ll) {
3433                                 r = sd_ipv4ll_set_mac(link->ipv4ll, &link->mac);
3434                                 if (r < 0)
3435                                         return log_link_warning_errno(link, r, "Could not update MAC address in IPv4LL client: %m");
3436                         }
3437
3438                         if (link->dhcp_client) {
3439                                 r = sd_dhcp_client_set_mac(link->dhcp_client,
3440                                                            (const uint8_t *) &link->mac,
3441                                                            sizeof (link->mac),
3442                                                            ARPHRD_ETHER);
3443                                 if (r < 0)
3444                                         return log_link_warning_errno(link, r, "Could not update MAC address in DHCP client: %m");
3445
3446                                 r = dhcp4_set_client_identifier(link);
3447                                 if (r < 0)
3448                                         return r;
3449                         }
3450
3451                         if (link->dhcp6_client) {
3452                                 const DUID* duid = link_get_duid(link);
3453
3454                                 r = sd_dhcp6_client_set_mac(link->dhcp6_client,
3455                                                             (const uint8_t *) &link->mac,
3456                                                             sizeof (link->mac),
3457                                                             ARPHRD_ETHER);
3458                                 if (r < 0)
3459                                         return log_link_warning_errno(link, r, "Could not update MAC address in DHCPv6 client: %m");
3460
3461                                 if (link->network->iaid_set) {
3462                                         r = sd_dhcp6_client_set_iaid(link->dhcp6_client,
3463                                                                      link->network->iaid);
3464                                         if (r < 0)
3465                                                 return log_link_warning_errno(link, r, "Could not update DHCPv6 IAID: %m");
3466                                 }
3467
3468                                 r = sd_dhcp6_client_set_duid(link->dhcp6_client,
3469                                                              duid->type,
3470                                                              duid->raw_data_len > 0 ? duid->raw_data : NULL,
3471                                                              duid->raw_data_len);
3472                                 if (r < 0)
3473                                         return log_link_warning_errno(link, r, "Could not update DHCPv6 DUID: %m");
3474                         }
3475
3476                         if (link->radv) {
3477                                 r = sd_radv_set_mac(link->radv, &link->mac);
3478                                 if (r < 0)
3479                                         return log_link_warning_errno(link, r, "Could not update MAC for Router Advertisement: %m");
3480                         }
3481
3482                         if (link->ndisc) {
3483                                 r = sd_ndisc_set_mac(link->ndisc, &link->mac);
3484                                 if (r < 0)
3485                                         return log_link_warning_errno(link, r, "Could not update MAC for ndisc: %m");
3486                         }
3487                 }
3488         }
3489
3490         old_master = link->master_ifindex;
3491         (void) sd_netlink_message_read_u32(m, IFLA_MASTER, (uint32_t *) &link->master_ifindex);
3492
3493         had_carrier = link_has_carrier(link);
3494
3495         r = link_update_flags(link, m, old_master != link->master_ifindex);
3496         if (r < 0)
3497                 return r;
3498
3499         r = link_update_lldp(link);
3500         if (r < 0)
3501                 return r;
3502
3503         carrier_gained = !had_carrier && link_has_carrier(link);
3504         carrier_lost = had_carrier && !link_has_carrier(link);
3505
3506         if (carrier_gained) {
3507                 log_link_info(link, "Gained carrier");
3508
3509                 r = link_carrier_gained(link);
3510                 if (r < 0)
3511                         return r;
3512         } else if (carrier_lost) {
3513                 log_link_info(link, "Lost carrier");
3514
3515                 r = link_carrier_lost(link);
3516                 if (r < 0)
3517                         return r;
3518         }
3519
3520         return 0;
3521 }
3522
3523 static void print_link_hashmap(FILE *f, const char *prefix, Hashmap* h) {
3524         bool space = false;
3525         Iterator i;
3526         Link *link;
3527
3528         assert(f);
3529         assert(prefix);
3530
3531         if (hashmap_isempty(h))
3532                 return;
3533
3534         fputs(prefix, f);
3535         HASHMAP_FOREACH(link, h, i) {
3536                 if (space)
3537                         fputc(' ', f);
3538
3539                 fprintf(f, "%i", link->ifindex);
3540                 space = true;
3541         }
3542
3543         fputc('\n', f);
3544 }
3545
3546 int link_save(Link *link) {
3547         _cleanup_free_ char *temp_path = NULL;
3548         _cleanup_fclose_ FILE *f = NULL;
3549         const char *admin_state, *oper_state;
3550         Address *a;
3551         Route *route;
3552         Iterator i;
3553         int r;
3554
3555         assert(link);
3556         assert(link->state_file);
3557         assert(link->lease_file);
3558         assert(link->manager);
3559
3560         if (link->state == LINK_STATE_LINGER) {
3561                 (void) unlink(link->state_file);
3562                 return 0;
3563         }
3564
3565         link_lldp_save(link);
3566
3567         admin_state = link_state_to_string(link->state);
3568         assert(admin_state);
3569
3570         oper_state = link_operstate_to_string(link->operstate);
3571         assert(oper_state);
3572
3573         r = fopen_temporary(link->state_file, &f, &temp_path);
3574         if (r < 0)
3575                 goto fail;
3576
3577         (void) fchmod(fileno(f), 0644);
3578
3579         fprintf(f,
3580                 "# This is private data. Do not parse.\n"
3581                 "ADMIN_STATE=%s\n"
3582                 "OPER_STATE=%s\n",
3583                 admin_state, oper_state);
3584
3585         if (link->network) {
3586                 char **dhcp6_domains = NULL, **dhcp_domains = NULL;
3587                 const char *dhcp_domainname = NULL, *p;
3588                 sd_dhcp6_lease *dhcp6_lease = NULL;
3589                 unsigned j;
3590                 bool space;
3591
3592                 fprintf(f, "REQUIRED_FOR_ONLINE=%s\n",
3593                         yes_no(link->network->required_for_online));
3594
3595                 fprintf(f, "REQUIRED_OPER_STATE_FOR_ONLINE=%s\n",
3596                         strempty(link_operstate_to_string(link->network->required_operstate_for_online)));
3597
3598                 if (link->dhcp6_client) {
3599                         r = sd_dhcp6_client_get_lease(link->dhcp6_client, &dhcp6_lease);
3600                         if (r < 0 && r != -ENOMSG)
3601                                 log_link_debug(link, "No DHCPv6 lease");
3602                 }
3603
3604                 fprintf(f, "NETWORK_FILE=%s\n", link->network->filename);
3605
3606                 fputs("DNS=", f);
3607                 space = false;
3608
3609                 for (j = 0; j < link->network->n_dns; j++) {
3610                         _cleanup_free_ char *b = NULL;
3611
3612                         r = in_addr_to_string(link->network->dns[j].family,
3613                                               &link->network->dns[j].address,  &b);
3614                         if (r < 0) {
3615                                 log_debug_errno(r, "Failed to format address, ignoring: %m");
3616                                 continue;
3617                         }
3618
3619                         if (space)
3620                                 fputc(' ', f);
3621                         fputs(b, f);
3622                         space = true;
3623                 }
3624
3625                 if (link->network->dhcp_use_dns &&
3626                     link->dhcp_lease) {
3627                         const struct in_addr *addresses;
3628
3629                         r = sd_dhcp_lease_get_dns(link->dhcp_lease, &addresses);
3630                         if (r > 0)
3631                                 if (serialize_in_addrs(f, addresses, r, space, in4_addr_is_non_local) > 0)
3632                                         space = true;
3633                 }
3634
3635                 if (link->network->dhcp_use_dns && dhcp6_lease) {
3636                         struct in6_addr *in6_addrs;
3637
3638                         r = sd_dhcp6_lease_get_dns(dhcp6_lease, &in6_addrs);
3639                         if (r > 0) {
3640                                 if (space)
3641                                         fputc(' ', f);
3642                                 serialize_in6_addrs(f, in6_addrs, r);
3643                                 space = true;
3644                         }
3645                 }
3646
3647                 /* Make sure to flush out old entries before we use the NDISC data */
3648                 ndisc_vacuum(link);
3649
3650                 if (link->network->ipv6_accept_ra_use_dns && link->ndisc_rdnss) {
3651                         NDiscRDNSS *dd;
3652
3653                         SET_FOREACH(dd, link->ndisc_rdnss, i) {
3654                                 if (space)
3655                                         fputc(' ', f);
3656
3657                                 serialize_in6_addrs(f, &dd->address, 1);
3658                                 space = true;
3659                         }
3660                 }
3661
3662                 fputc('\n', f);
3663
3664                 fputs("NTP=", f);
3665                 space = false;
3666                 fputstrv(f, link->network->ntp, NULL, &space);
3667
3668                 if (link->network->dhcp_use_ntp &&
3669                     link->dhcp_lease) {
3670                         const struct in_addr *addresses;
3671
3672                         r = sd_dhcp_lease_get_ntp(link->dhcp_lease, &addresses);
3673                         if (r > 0)
3674                                 if (serialize_in_addrs(f, addresses, r, space, in4_addr_is_non_local) > 0)
3675                                         space = true;
3676                 }
3677
3678                 if (link->network->dhcp_use_ntp && dhcp6_lease) {
3679                         struct in6_addr *in6_addrs;
3680                         char **hosts;
3681
3682                         r = sd_dhcp6_lease_get_ntp_addrs(dhcp6_lease,
3683                                                          &in6_addrs);
3684                         if (r > 0) {
3685                                 if (space)
3686                                         fputc(' ', f);
3687                                 serialize_in6_addrs(f, in6_addrs, r);
3688                                 space = true;
3689                         }
3690
3691                         r = sd_dhcp6_lease_get_ntp_fqdn(dhcp6_lease, &hosts);
3692                         if (r > 0)
3693                                 fputstrv(f, hosts, NULL, &space);
3694                 }
3695
3696                 fputc('\n', f);
3697
3698                 if (link->network->dhcp_use_domains != DHCP_USE_DOMAINS_NO) {
3699                         if (link->dhcp_lease) {
3700                                 (void) sd_dhcp_lease_get_domainname(link->dhcp_lease, &dhcp_domainname);
3701                                 (void) sd_dhcp_lease_get_search_domains(link->dhcp_lease, &dhcp_domains);
3702                         }
3703                         if (dhcp6_lease)
3704                                 (void) sd_dhcp6_lease_get_domains(dhcp6_lease, &dhcp6_domains);
3705                 }
3706
3707                 fputs("DOMAINS=", f);
3708                 space = false;
3709                 ORDERED_SET_FOREACH(p, link->network->search_domains, i)
3710                         fputs_with_space(f, p, NULL, &space);
3711
3712                 if (link->network->dhcp_use_domains == DHCP_USE_DOMAINS_YES) {
3713                         NDiscDNSSL *dd;
3714
3715                         if (dhcp_domainname)
3716                                 fputs_with_space(f, dhcp_domainname, NULL, &space);
3717                         if (dhcp_domains)
3718                                 fputstrv(f, dhcp_domains, NULL, &space);
3719                         if (dhcp6_domains)
3720                                 fputstrv(f, dhcp6_domains, NULL, &space);
3721
3722                         SET_FOREACH(dd, link->ndisc_dnssl, i)
3723                                 fputs_with_space(f, NDISC_DNSSL_DOMAIN(dd), NULL, &space);
3724                 }
3725
3726                 fputc('\n', f);
3727
3728                 fputs("ROUTE_DOMAINS=", f);
3729                 space = false;
3730                 ORDERED_SET_FOREACH(p, link->network->route_domains, i)
3731                         fputs_with_space(f, p, NULL, &space);
3732
3733                 if (link->network->dhcp_use_domains == DHCP_USE_DOMAINS_ROUTE) {
3734                         NDiscDNSSL *dd;
3735
3736                         if (dhcp_domainname)
3737                                 fputs_with_space(f, dhcp_domainname, NULL, &space);
3738                         if (dhcp_domains)
3739                                 fputstrv(f, dhcp_domains, NULL, &space);
3740                         if (dhcp6_domains)
3741                                 fputstrv(f, dhcp6_domains, NULL, &space);
3742
3743                         SET_FOREACH(dd, link->ndisc_dnssl, i)
3744                                 fputs_with_space(f, NDISC_DNSSL_DOMAIN(dd), NULL, &space);
3745                 }
3746
3747                 fputc('\n', f);
3748
3749                 fprintf(f, "LLMNR=%s\n",
3750                         resolve_support_to_string(link->network->llmnr));
3751                 fprintf(f, "MDNS=%s\n",
3752                         resolve_support_to_string(link->network->mdns));
3753                 if (link->network->dns_default_route >= 0)
3754                   &