network: skip to check dynamic addresses when ConfigureWithoutCarrier=yes
[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_has_carrier(link) || !link->network->configure_without_carrier) {
964
965                 if (link_ipv4ll_enabled(link, ADDRESS_FAMILY_IPV4) && !(link->ipv4ll_address && link->ipv4ll_route))
966                         return;
967
968                 if (link_ipv6ll_enabled(link) &&
969                     in_addr_is_null(AF_INET6, (const union in_addr_union*) &link->ipv6ll_address))
970                         return;
971
972                 if ((link_dhcp4_enabled(link) || link_dhcp6_enabled(link)) &&
973                     !link->dhcp4_configured &&
974                     !link->dhcp6_configured &&
975                     !(link_ipv4ll_enabled(link, ADDRESS_FAMILY_FALLBACK_IPV4) && link->ipv4ll_address && link->ipv4ll_route))
976                         /* When DHCP is enabled, at least one protocol must provide an address, or
977                          * an IPv4ll fallback address must be configured. */
978                         return;
979
980                 if (link_ipv6_accept_ra_enabled(link) && !link->ndisc_configured)
981                         return;
982         }
983
984         if (link->state != LINK_STATE_CONFIGURED)
985                 link_enter_configured(link);
986
987         return;
988 }
989
990 static int link_request_set_neighbors(Link *link) {
991         Neighbor *neighbor;
992         int r;
993
994         assert(link);
995         assert(link->network);
996         assert(link->state != _LINK_STATE_INVALID);
997
998         link_set_state(link, LINK_STATE_CONFIGURING);
999         link->neighbors_configured = false;
1000
1001         LIST_FOREACH(neighbors, neighbor, link->network->neighbors) {
1002                 r = neighbor_configure(neighbor, link, NULL);
1003                 if (r < 0) {
1004                         log_link_warning_errno(link, r, "Could not set neighbor: %m");
1005                         link_enter_failed(link);
1006                         return r;
1007                 }
1008         }
1009
1010         if (link->neighbor_messages == 0) {
1011                 link->neighbors_configured = true;
1012                 link_check_ready(link);
1013         } else
1014                 log_link_debug(link, "Setting neighbors");
1015
1016         return 0;
1017 }
1018
1019 static int address_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1020         int r;
1021
1022         assert(rtnl);
1023         assert(m);
1024         assert(link);
1025         assert(link->ifname);
1026         assert(link->address_messages > 0);
1027         assert(IN_SET(link->state, LINK_STATE_CONFIGURING,
1028                LINK_STATE_FAILED, LINK_STATE_LINGER));
1029
1030         link->address_messages--;
1031
1032         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1033                 return 1;
1034
1035         r = sd_netlink_message_get_errno(m);
1036         if (r < 0 && r != -EEXIST)
1037                 log_link_warning_errno(link, r, "could not set address: %m");
1038         else if (r >= 0)
1039                 manager_rtnl_process_address(rtnl, m, link->manager);
1040
1041         if (link->address_messages == 0) {
1042                 log_link_debug(link, "Addresses set");
1043                 link->addresses_configured = true;
1044                 link_check_ready(link);
1045         }
1046
1047         return 1;
1048 }
1049
1050 static int link_push_uplink_dns_to_dhcp_server(Link *link, sd_dhcp_server *s) {
1051         _cleanup_free_ struct in_addr *addresses = NULL;
1052         size_t n_addresses = 0, n_allocated = 0;
1053         unsigned i;
1054
1055         log_debug("Copying DNS server information from %s", link->ifname);
1056
1057         if (!link->network)
1058                 return 0;
1059
1060         for (i = 0; i < link->network->n_dns; i++) {
1061                 struct in_addr ia;
1062
1063                 /* Only look for IPv4 addresses */
1064                 if (link->network->dns[i].family != AF_INET)
1065                         continue;
1066
1067                 ia = link->network->dns[i].address.in;
1068
1069                 /* Never propagate obviously borked data */
1070                 if (in4_addr_is_null(&ia) || in4_addr_is_localhost(&ia))
1071                         continue;
1072
1073                 if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1))
1074                         return log_oom();
1075
1076                 addresses[n_addresses++] = ia;
1077         }
1078
1079         if (link->network->dhcp_use_dns && link->dhcp_lease) {
1080                 const struct in_addr *da = NULL;
1081                 int j, n;
1082
1083                 n = sd_dhcp_lease_get_dns(link->dhcp_lease, &da);
1084                 if (n > 0) {
1085
1086                         if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + n))
1087                                 return log_oom();
1088
1089                         for (j = 0; j < n; j++)
1090                                 if (in4_addr_is_non_local(&da[j]))
1091                                         addresses[n_addresses++] = da[j];
1092                 }
1093         }
1094
1095         if (n_addresses <= 0)
1096                 return 0;
1097
1098         return sd_dhcp_server_set_dns(s, addresses, n_addresses);
1099 }
1100
1101 static int link_push_uplink_ntp_to_dhcp_server(Link *link, sd_dhcp_server *s) {
1102         _cleanup_free_ struct in_addr *addresses = NULL;
1103         size_t n_addresses = 0, n_allocated = 0;
1104         char **a;
1105
1106         if (!link->network)
1107                 return 0;
1108
1109         log_debug("Copying NTP server information from %s", link->ifname);
1110
1111         STRV_FOREACH(a, link->network->ntp) {
1112                 union in_addr_union ia;
1113
1114                 /* Only look for IPv4 addresses */
1115                 if (in_addr_from_string(AF_INET, *a, &ia) <= 0)
1116                         continue;
1117
1118                 /* Never propagate obviously borked data */
1119                 if (in4_addr_is_null(&ia.in) || in4_addr_is_localhost(&ia.in))
1120                         continue;
1121
1122                 if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1))
1123                         return log_oom();
1124
1125                 addresses[n_addresses++] = ia.in;
1126         }
1127
1128         if (link->network->dhcp_use_ntp && link->dhcp_lease) {
1129                 const struct in_addr *da = NULL;
1130                 int j, n;
1131
1132                 n = sd_dhcp_lease_get_ntp(link->dhcp_lease, &da);
1133                 if (n > 0) {
1134
1135                         if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + n))
1136                                 return log_oom();
1137
1138                         for (j = 0; j < n; j++)
1139                                 if (in4_addr_is_non_local(&da[j]))
1140                                         addresses[n_addresses++] = da[j];
1141                 }
1142         }
1143
1144         if (n_addresses <= 0)
1145                 return 0;
1146
1147         return sd_dhcp_server_set_ntp(s, addresses, n_addresses);
1148 }
1149
1150 static int link_set_bridge_fdb(Link *link) {
1151         FdbEntry *fdb_entry;
1152         int r;
1153
1154         LIST_FOREACH(static_fdb_entries, fdb_entry, link->network->static_fdb_entries) {
1155                 r = fdb_entry_configure(link, fdb_entry);
1156                 if (r < 0)
1157                         return log_link_error_errno(link, r, "Failed to add MAC entry to static MAC table: %m");
1158         }
1159
1160         return 0;
1161 }
1162
1163 static int link_request_set_addresses(Link *link) {
1164         AddressLabel *label;
1165         Address *ad;
1166         int r;
1167
1168         assert(link);
1169         assert(link->network);
1170         assert(link->state != _LINK_STATE_INVALID);
1171
1172         link_set_state(link, LINK_STATE_CONFIGURING);
1173
1174         /* Reset all *_configured flags we are configuring. */
1175         link->addresses_configured = false;
1176         link->addresses_ready = false;
1177         link->neighbors_configured = false;
1178         link->static_routes_configured = false;
1179         link->routing_policy_rules_configured = false;
1180
1181         r = link_set_bridge_fdb(link);
1182         if (r < 0)
1183                 return r;
1184
1185         r = link_request_set_neighbors(link);
1186         if (r < 0)
1187                 return r;
1188
1189         LIST_FOREACH(addresses, ad, link->network->static_addresses) {
1190                 bool update;
1191
1192                 update = address_get(link, ad->family, &ad->in_addr, ad->prefixlen, NULL) > 0;
1193
1194                 r = address_configure(ad, link, address_handler, update);
1195                 if (r < 0) {
1196                         log_link_warning_errno(link, r, "Could not set addresses: %m");
1197                         link_enter_failed(link);
1198                         return r;
1199                 }
1200                 if (r > 0)
1201                         link->address_messages++;
1202         }
1203
1204         LIST_FOREACH(labels, label, link->network->address_labels) {
1205                 r = address_label_configure(label, link, NULL, false);
1206                 if (r < 0) {
1207                         log_link_warning_errno(link, r, "Could not set address label: %m");
1208                         link_enter_failed(link);
1209                         return r;
1210                 }
1211
1212                 link->address_label_messages++;
1213         }
1214
1215         /* now that we can figure out a default address for the dhcp server,
1216            start it */
1217         if (link_dhcp4_server_enabled(link) && (link->flags & IFF_UP)) {
1218                 Address *address;
1219                 Link *uplink = NULL;
1220                 bool acquired_uplink = false;
1221
1222                 address = link_find_dhcp_server_address(link);
1223                 if (!address) {
1224                         log_link_warning(link, "Failed to find suitable address for DHCPv4 server instance.");
1225                         link_enter_failed(link);
1226                         return 0;
1227                 }
1228
1229                 /* use the server address' subnet as the pool */
1230                 r = sd_dhcp_server_configure_pool(link->dhcp_server, &address->in_addr.in, address->prefixlen,
1231                                                   link->network->dhcp_server_pool_offset, link->network->dhcp_server_pool_size);
1232                 if (r < 0)
1233                         return r;
1234
1235                 /* TODO:
1236                 r = sd_dhcp_server_set_router(link->dhcp_server,
1237                                               &main_address->in_addr.in);
1238                 if (r < 0)
1239                         return r;
1240                 */
1241
1242                 if (link->network->dhcp_server_max_lease_time_usec > 0) {
1243                         r = sd_dhcp_server_set_max_lease_time(
1244                                         link->dhcp_server,
1245                                         DIV_ROUND_UP(link->network->dhcp_server_max_lease_time_usec, USEC_PER_SEC));
1246                         if (r < 0)
1247                                 return r;
1248                 }
1249
1250                 if (link->network->dhcp_server_default_lease_time_usec > 0) {
1251                         r = sd_dhcp_server_set_default_lease_time(
1252                                         link->dhcp_server,
1253                                         DIV_ROUND_UP(link->network->dhcp_server_default_lease_time_usec, USEC_PER_SEC));
1254                         if (r < 0)
1255                                 return r;
1256                 }
1257
1258                 if (link->network->dhcp_server_emit_dns) {
1259
1260                         if (link->network->n_dhcp_server_dns > 0)
1261                                 r = sd_dhcp_server_set_dns(link->dhcp_server, link->network->dhcp_server_dns, link->network->n_dhcp_server_dns);
1262                         else {
1263                                 uplink = manager_find_uplink(link->manager, link);
1264                                 acquired_uplink = true;
1265
1266                                 if (!uplink) {
1267                                         log_link_debug(link, "Not emitting DNS server information on link, couldn't find suitable uplink.");
1268                                         r = 0;
1269                                 } else
1270                                         r = link_push_uplink_dns_to_dhcp_server(uplink, link->dhcp_server);
1271                         }
1272                         if (r < 0)
1273                                 log_link_warning_errno(link, r, "Failed to set DNS server for DHCP server, ignoring: %m");
1274                 }
1275
1276                 if (link->network->dhcp_server_emit_ntp) {
1277
1278                         if (link->network->n_dhcp_server_ntp > 0)
1279                                 r = sd_dhcp_server_set_ntp(link->dhcp_server, link->network->dhcp_server_ntp, link->network->n_dhcp_server_ntp);
1280                         else {
1281                                 if (!acquired_uplink)
1282                                         uplink = manager_find_uplink(link->manager, link);
1283
1284                                 if (!uplink) {
1285                                         log_link_debug(link, "Not emitting NTP server information on link, couldn't find suitable uplink.");
1286                                         r = 0;
1287                                 } else
1288                                         r = link_push_uplink_ntp_to_dhcp_server(uplink, link->dhcp_server);
1289
1290                         }
1291                         if (r < 0)
1292                                 log_link_warning_errno(link, r, "Failed to set NTP server for DHCP server, ignoring: %m");
1293                 }
1294
1295                 r = sd_dhcp_server_set_emit_router(link->dhcp_server, link->network->dhcp_server_emit_router);
1296                 if (r < 0)
1297                         return log_link_warning_errno(link, r, "Failed to set router emission for DHCP server: %m");
1298
1299                 if (link->network->dhcp_server_emit_timezone) {
1300                         _cleanup_free_ char *buffer = NULL;
1301                         const char *tz = NULL;
1302
1303                         if (link->network->dhcp_server_timezone)
1304                                 tz = link->network->dhcp_server_timezone;
1305                         else {
1306                                 r = get_timezone(&buffer);
1307                                 if (r < 0)
1308                                         log_warning_errno(r, "Failed to determine timezone: %m");
1309                                 else
1310                                         tz = buffer;
1311                         }
1312
1313                         if (tz) {
1314                                 r = sd_dhcp_server_set_timezone(link->dhcp_server, tz);
1315                                 if (r < 0)
1316                                         return r;
1317                         }
1318                 }
1319                 if (!sd_dhcp_server_is_running(link->dhcp_server)) {
1320                         r = sd_dhcp_server_start(link->dhcp_server);
1321                         if (r < 0) {
1322                                 log_link_warning_errno(link, r, "Could not start DHCPv4 server instance: %m");
1323
1324                                 link_enter_failed(link);
1325
1326                                 return 0;
1327                         }
1328                 }
1329
1330                 log_link_debug(link, "Offering DHCPv4 leases");
1331         }
1332
1333         if (link->address_messages == 0) {
1334                 link->addresses_configured = true;
1335                 link_check_ready(link);
1336         } else
1337                 log_link_debug(link, "Setting addresses");
1338
1339         return 0;
1340 }
1341
1342 static int link_set_bridge_vlan(Link *link) {
1343         int r;
1344
1345         r = br_vlan_configure(link, link->network->pvid, link->network->br_vid_bitmap, link->network->br_untagged_bitmap);
1346         if (r < 0)
1347                 log_link_error_errno(link, r, "Failed to assign VLANs to bridge port: %m");
1348
1349         return r;
1350 }
1351
1352 static int link_set_proxy_arp(Link *link) {
1353         int r;
1354
1355         if (!link_proxy_arp_enabled(link))
1356                 return 0;
1357
1358         r = sysctl_write_ip_property_boolean(AF_INET, link->ifname, "proxy_arp", link->network->proxy_arp > 0);
1359         if (r < 0)
1360                 log_link_warning_errno(link, r, "Cannot configure proxy ARP for interface: %m");
1361
1362         return 0;
1363 }
1364
1365 static int link_configure_after_setting_mtu(Link *link);
1366
1367 static int set_mtu_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1368         int r;
1369
1370         assert(m);
1371         assert(link);
1372         assert(link->ifname);
1373
1374         link->setting_mtu = false;
1375
1376         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1377                 return 1;
1378
1379         r = sd_netlink_message_get_errno(m);
1380         if (r < 0) {
1381                 log_link_warning_errno(link, r, "Could not set MTU: %m");
1382                 return 1;
1383         }
1384
1385         log_link_debug(link, "Setting MTU done.");
1386
1387         if (link->state == LINK_STATE_INITIALIZED)
1388                 (void) link_configure_after_setting_mtu(link);
1389
1390         return 1;
1391 }
1392
1393 int link_set_mtu(Link *link, uint32_t mtu) {
1394         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1395         int r;
1396
1397         assert(link);
1398         assert(link->manager);
1399         assert(link->manager->rtnl);
1400
1401         if (mtu == 0 || link->setting_mtu)
1402                 return 0;
1403
1404         if (link->mtu == mtu)
1405                 return 0;
1406
1407         log_link_debug(link, "Setting MTU: %" PRIu32, mtu);
1408
1409         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1410         if (r < 0)
1411                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1412
1413         /* If IPv6 not configured (no static IPv6 address and IPv6LL autoconfiguration is disabled)
1414          * for this interface, then disable IPv6 else enable it. */
1415         (void) link_enable_ipv6(link);
1416
1417         /* IPv6 protocol requires a minimum MTU of IPV6_MTU_MIN(1280) bytes
1418          * on the interface. Bump up MTU bytes to IPV6_MTU_MIN. */
1419         if (link_ipv6_enabled(link) && mtu < IPV6_MIN_MTU) {
1420
1421                 log_link_warning(link, "Bumping MTU to " STRINGIFY(IPV6_MIN_MTU) ", as "
1422                                  "IPv6 is requested and requires a minimum MTU of " STRINGIFY(IPV6_MIN_MTU) " bytes: %m");
1423
1424                 mtu = IPV6_MIN_MTU;
1425         }
1426
1427         r = sd_netlink_message_append_u32(req, IFLA_MTU, mtu);
1428         if (r < 0)
1429                 return log_link_error_errno(link, r, "Could not append MTU: %m");
1430
1431         r = netlink_call_async(link->manager->rtnl, NULL, req, set_mtu_handler,
1432                                link_netlink_destroy_callback, link);
1433         if (r < 0)
1434                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1435
1436         link_ref(link);
1437         link->setting_mtu = true;
1438
1439         return 0;
1440 }
1441
1442 static bool link_reduces_vlan_mtu(Link *link) {
1443         /* See netif_reduces_vlan_mtu() in kernel. */
1444         return streq_ptr(link->kind, "macsec");
1445 }
1446
1447 static uint32_t link_get_requested_mtu_by_stacked_netdevs(Link *link) {
1448         uint32_t mtu = 0;
1449         NetDev *dev;
1450         Iterator i;
1451
1452         HASHMAP_FOREACH(dev, link->network->stacked_netdevs, i)
1453                 if (dev->kind == NETDEV_KIND_VLAN && dev->mtu > 0)
1454                         /* See vlan_dev_change_mtu() in kernel. */
1455                         mtu = MAX(mtu, link_reduces_vlan_mtu(link) ? dev->mtu + 4 : dev->mtu);
1456
1457                 else if (dev->kind == NETDEV_KIND_MACVLAN && dev->mtu > mtu)
1458                         /* See macvlan_change_mtu() in kernel. */
1459                         mtu = dev->mtu;
1460
1461         return mtu;
1462 }
1463
1464 static int link_configure_mtu(Link *link) {
1465         uint32_t mtu;
1466
1467         assert(link);
1468         assert(link->network);
1469
1470         if (link->network->mtu > 0)
1471                 return link_set_mtu(link, link->network->mtu);
1472
1473         mtu = link_get_requested_mtu_by_stacked_netdevs(link);
1474         if (link->mtu >= mtu)
1475                 return 0;
1476
1477         log_link_notice(link, "Bumping MTU bytes from %"PRIu32" to %"PRIu32" because of stacked device. "
1478                         "If it is not desired, then please explicitly specify MTUBytes= setting.",
1479                         link->mtu, mtu);
1480
1481         return link_set_mtu(link, mtu);
1482 }
1483
1484 static int set_flags_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1485         int r;
1486
1487         assert(m);
1488         assert(link);
1489         assert(link->ifname);
1490
1491         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1492                 return 1;
1493
1494         r = sd_netlink_message_get_errno(m);
1495         if (r < 0)
1496                 log_link_warning_errno(link, r, "Could not set link flags: %m");
1497
1498         return 1;
1499 }
1500
1501 static int link_set_flags(Link *link) {
1502         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1503         unsigned ifi_change = 0;
1504         unsigned ifi_flags = 0;
1505         int r;
1506
1507         assert(link);
1508         assert(link->manager);
1509         assert(link->manager->rtnl);
1510
1511         if (link->flags & IFF_LOOPBACK)
1512                 return 0;
1513
1514         if (!link->network)
1515                 return 0;
1516
1517         if (link->network->arp < 0 && link->network->multicast < 0 && link->network->allmulticast < 0)
1518                 return 0;
1519
1520         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1521         if (r < 0)
1522                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1523
1524         if (link->network->arp >= 0) {
1525                 ifi_change |= IFF_NOARP;
1526                 SET_FLAG(ifi_flags, IFF_NOARP, link->network->arp == 0);
1527         }
1528
1529         if (link->network->multicast >= 0) {
1530                 ifi_change |= IFF_MULTICAST;
1531                 SET_FLAG(ifi_flags, IFF_MULTICAST, link->network->multicast);
1532         }
1533
1534         if (link->network->allmulticast >= 0) {
1535                 ifi_change |= IFF_ALLMULTI;
1536                 SET_FLAG(ifi_flags, IFF_ALLMULTI, link->network->allmulticast);
1537         }
1538
1539         r = sd_rtnl_message_link_set_flags(req, ifi_flags, ifi_change);
1540         if (r < 0)
1541                 return log_link_error_errno(link, r, "Could not set link flags: %m");
1542
1543         r = netlink_call_async(link->manager->rtnl, NULL, req, set_flags_handler,
1544                                link_netlink_destroy_callback, link);
1545         if (r < 0)
1546                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1547
1548         link_ref(link);
1549
1550         return 0;
1551 }
1552
1553 static int link_acquire_ipv6_conf(Link *link) {
1554         int r;
1555
1556         assert(link);
1557
1558         if (link_ipv6_accept_ra_enabled(link)) {
1559                 assert(link->ndisc);
1560
1561                 log_link_debug(link, "Discovering IPv6 routers");
1562
1563                 r = sd_ndisc_start(link->ndisc);
1564                 if (r < 0 && r != -EBUSY)
1565                         return log_link_warning_errno(link, r, "Could not start IPv6 Router Discovery: %m");
1566         }
1567
1568         if (link_radv_enabled(link)) {
1569                 assert(link->radv);
1570                 assert(in_addr_is_link_local(AF_INET6, (const union in_addr_union*)&link->ipv6ll_address) > 0);
1571
1572                 log_link_debug(link, "Starting IPv6 Router Advertisements");
1573
1574                 r = sd_radv_start(link->radv);
1575                 if (r < 0 && r != -EBUSY)
1576                         return log_link_warning_errno(link, r, "Could not start IPv6 Router Advertisement: %m");
1577         }
1578
1579         (void) dhcp6_request_prefix_delegation(link);
1580
1581         return 0;
1582 }
1583
1584 static int link_acquire_ipv4_conf(Link *link) {
1585         int r;
1586
1587         assert(link);
1588         assert(link->manager);
1589         assert(link->manager->event);
1590
1591         if (link_ipv4ll_enabled(link, ADDRESS_FAMILY_IPV4)) {
1592                 assert(link->ipv4ll);
1593
1594                 log_link_debug(link, "Acquiring IPv4 link-local address");
1595
1596                 r = sd_ipv4ll_start(link->ipv4ll);
1597                 if (r < 0)
1598                         return log_link_warning_errno(link, r, "Could not acquire IPv4 link-local address: %m");
1599         }
1600
1601         if (link_dhcp4_enabled(link)) {
1602                 assert(link->dhcp_client);
1603
1604                 log_link_debug(link, "Acquiring DHCPv4 lease");
1605
1606                 r = sd_dhcp_client_start(link->dhcp_client);
1607                 if (r < 0)
1608                         return log_link_warning_errno(link, r, "Could not acquire DHCPv4 lease: %m");
1609         }
1610
1611         return 0;
1612 }
1613
1614 static int link_acquire_conf(Link *link) {
1615         int r;
1616
1617         assert(link);
1618
1619         r = link_acquire_ipv4_conf(link);
1620         if (r < 0)
1621                 return r;
1622
1623         if (!in_addr_is_null(AF_INET6, (const union in_addr_union*) &link->ipv6ll_address)) {
1624                 r = link_acquire_ipv6_conf(link);
1625                 if (r < 0)
1626                         return r;
1627         }
1628
1629         if (link_lldp_emit_enabled(link)) {
1630                 r = link_lldp_emit_start(link);
1631                 if (r < 0)
1632                         return log_link_warning_errno(link, r, "Failed to start LLDP transmission: %m");
1633         }
1634
1635         return 0;
1636 }
1637
1638 bool link_has_carrier(Link *link) {
1639         /* see Documentation/networking/operstates.txt in the kernel sources */
1640
1641         if (link->kernel_operstate == IF_OPER_UP)
1642                 return true;
1643
1644         if (link->kernel_operstate == IF_OPER_UNKNOWN)
1645                 /* operstate may not be implemented, so fall back to flags */
1646                 if (FLAGS_SET(link->flags, IFF_LOWER_UP | IFF_RUNNING) &&
1647                     !FLAGS_SET(link->flags, IFF_DORMANT))
1648                         return true;
1649
1650         return false;
1651 }
1652
1653 static int link_address_genmode_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1654         int r;
1655
1656         assert(link);
1657
1658         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1659                 return 1;
1660
1661         r = sd_netlink_message_get_errno(m);
1662         if (r < 0)
1663                 log_link_warning_errno(link, r, "Could not set address genmode for interface: %m");
1664
1665         return 1;
1666 }
1667
1668 static int link_configure_addrgen_mode(Link *link) {
1669         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1670         uint8_t ipv6ll_mode;
1671         int r;
1672
1673         assert(link);
1674         assert(link->network);
1675         assert(link->manager);
1676         assert(link->manager->rtnl);
1677
1678         if (!socket_ipv6_is_supported())
1679                 return 0;
1680
1681         log_link_debug(link, "Setting address genmode for link");
1682
1683         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1684         if (r < 0)
1685                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1686
1687         r = sd_netlink_message_open_container(req, IFLA_AF_SPEC);
1688         if (r < 0)
1689                 return log_link_error_errno(link, r, "Could not open IFLA_AF_SPEC container: %m");
1690
1691         r = sd_netlink_message_open_container(req, AF_INET6);
1692         if (r < 0)
1693                 return log_link_error_errno(link, r, "Could not open AF_INET6 container: %m");
1694
1695         if (!link_ipv6ll_enabled(link))
1696                 ipv6ll_mode = IN6_ADDR_GEN_MODE_NONE;
1697         else if (sysctl_read_ip_property(AF_INET6, link->ifname, "stable_secret", NULL) < 0)
1698                 /* The file may not exist. And event if it exists, when stable_secret is unset,
1699                  * reading the file fails with EIO. */
1700                 ipv6ll_mode = IN6_ADDR_GEN_MODE_EUI64;
1701         else
1702                 ipv6ll_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
1703
1704         r = sd_netlink_message_append_u8(req, IFLA_INET6_ADDR_GEN_MODE, ipv6ll_mode);
1705         if (r < 0)
1706                 return log_link_error_errno(link, r, "Could not append IFLA_INET6_ADDR_GEN_MODE: %m");
1707
1708         r = sd_netlink_message_close_container(req);
1709         if (r < 0)
1710                 return log_link_error_errno(link, r, "Could not close AF_INET6 container: %m");
1711
1712         r = sd_netlink_message_close_container(req);
1713         if (r < 0)
1714                 return log_link_error_errno(link, r, "Could not close IFLA_AF_SPEC container: %m");
1715
1716         r = netlink_call_async(link->manager->rtnl, NULL, req, link_address_genmode_handler,
1717                                link_netlink_destroy_callback, link);
1718         if (r < 0)
1719                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1720
1721         link_ref(link);
1722
1723         return 0;
1724 }
1725
1726 static int link_up_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1727         int r;
1728
1729         assert(link);
1730
1731         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1732                 return 1;
1733
1734         r = sd_netlink_message_get_errno(m);
1735         if (r < 0)
1736                 /* we warn but don't fail the link, as it may be brought up later */
1737                 log_link_warning_errno(link, r, "Could not bring up interface: %m");
1738
1739         return 1;
1740 }
1741
1742 static int link_up(Link *link) {
1743         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1744         int r;
1745
1746         assert(link);
1747         assert(link->network);
1748         assert(link->manager);
1749         assert(link->manager->rtnl);
1750
1751         log_link_debug(link, "Bringing link up");
1752
1753         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_SETLINK, link->ifindex);
1754         if (r < 0)
1755                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1756
1757         /* set it free if not enslaved with networkd */
1758         if (!link->network->bridge && !link->network->bond && !link->network->vrf) {
1759                 r = sd_netlink_message_append_u32(req, IFLA_MASTER, 0);
1760                 if (r < 0)
1761                         return log_link_error_errno(link, r, "Could not append IFLA_MASTER attribute: %m");
1762         }
1763
1764         r = sd_rtnl_message_link_set_flags(req, IFF_UP, IFF_UP);
1765         if (r < 0)
1766                 return log_link_error_errno(link, r, "Could not set link flags: %m");
1767
1768         if (link->network->mac) {
1769                 r = sd_netlink_message_append_ether_addr(req, IFLA_ADDRESS, link->network->mac);
1770                 if (r < 0)
1771                         return log_link_error_errno(link, r, "Could not set MAC address: %m");
1772         }
1773
1774         r = netlink_call_async(link->manager->rtnl, NULL, req, link_up_handler,
1775                                link_netlink_destroy_callback, link);
1776         if (r < 0)
1777                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1778
1779         link_ref(link);
1780
1781         return 0;
1782 }
1783
1784 static int link_down_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
1785         int r;
1786
1787         assert(link);
1788
1789         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
1790                 return 1;
1791
1792         r = sd_netlink_message_get_errno(m);
1793         if (r < 0)
1794                 log_link_warning_errno(link, r, "Could not bring down interface: %m");
1795
1796         return 1;
1797 }
1798
1799 int link_down(Link *link, link_netlink_message_handler_t callback) {
1800         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
1801         int r;
1802
1803         assert(link);
1804         assert(link->manager);
1805         assert(link->manager->rtnl);
1806
1807         log_link_debug(link, "Bringing link down");
1808
1809         r = sd_rtnl_message_new_link(link->manager->rtnl, &req,
1810                                      RTM_SETLINK, link->ifindex);
1811         if (r < 0)
1812                 return log_link_error_errno(link, r, "Could not allocate RTM_SETLINK message: %m");
1813
1814         r = sd_rtnl_message_link_set_flags(req, 0, IFF_UP);
1815         if (r < 0)
1816                 return log_link_error_errno(link, r, "Could not set link flags: %m");
1817
1818         r = netlink_call_async(link->manager->rtnl, NULL, req,
1819                                callback ?: link_down_handler,
1820                                link_netlink_destroy_callback, link);
1821         if (r < 0)
1822                 return log_link_error_errno(link, r, "Could not send rtnetlink message: %m");
1823
1824         link_ref(link);
1825
1826         return 0;
1827 }
1828
1829 static int link_handle_bound_to_list(Link *link) {
1830         Link *l;
1831         Iterator i;
1832         int r;
1833         bool required_up = false;
1834         bool link_is_up = false;
1835
1836         assert(link);
1837
1838         if (hashmap_isempty(link->bound_to_links))
1839                 return 0;
1840
1841         if (link->flags & IFF_UP)
1842                 link_is_up = true;
1843
1844         HASHMAP_FOREACH (l, link->bound_to_links, i)
1845                 if (link_has_carrier(l)) {
1846                         required_up = true;
1847                         break;
1848                 }
1849
1850         if (!required_up && link_is_up) {
1851                 r = link_down(link, NULL);
1852                 if (r < 0)
1853                         return r;
1854         } else if (required_up && !link_is_up) {
1855                 r = link_up(link);
1856                 if (r < 0)
1857                         return r;
1858         }
1859
1860         return 0;
1861 }
1862
1863 static int link_handle_bound_by_list(Link *link) {
1864         Iterator i;
1865         Link *l;
1866         int r;
1867
1868         assert(link);
1869
1870         if (hashmap_isempty(link->bound_by_links))
1871                 return 0;
1872
1873         HASHMAP_FOREACH (l, link->bound_by_links, i) {
1874                 r = link_handle_bound_to_list(l);
1875                 if (r < 0)
1876                         return r;
1877         }
1878
1879         return 0;
1880 }
1881
1882 static int link_put_carrier(Link *link, Link *carrier, Hashmap **h) {
1883         int r;
1884
1885         assert(link);
1886         assert(carrier);
1887
1888         if (link == carrier)
1889                 return 0;
1890
1891         if (hashmap_get(*h, INT_TO_PTR(carrier->ifindex)))
1892                 return 0;
1893
1894         r = hashmap_ensure_allocated(h, NULL);
1895         if (r < 0)
1896                 return r;
1897
1898         r = hashmap_put(*h, INT_TO_PTR(carrier->ifindex), carrier);
1899         if (r < 0)
1900                 return r;
1901
1902         return 0;
1903 }
1904
1905 static int link_new_bound_by_list(Link *link) {
1906         Manager *m;
1907         Link *carrier;
1908         Iterator i;
1909         int r;
1910         bool list_updated = false;
1911
1912         assert(link);
1913         assert(link->manager);
1914
1915         m = link->manager;
1916
1917         HASHMAP_FOREACH(carrier, m->links, i) {
1918                 if (!carrier->network)
1919                         continue;
1920
1921                 if (strv_isempty(carrier->network->bind_carrier))
1922                         continue;
1923
1924                 if (strv_fnmatch(carrier->network->bind_carrier, link->ifname, 0)) {
1925                         r = link_put_carrier(link, carrier, &link->bound_by_links);
1926                         if (r < 0)
1927                                 return r;
1928
1929                         list_updated = true;
1930                 }
1931         }
1932
1933         if (list_updated)
1934                 link_dirty(link);
1935
1936         HASHMAP_FOREACH(carrier, link->bound_by_links, i) {
1937                 r = link_put_carrier(carrier, link, &carrier->bound_to_links);
1938                 if (r < 0)
1939                         return r;
1940
1941                 link_dirty(carrier);
1942         }
1943
1944         return 0;
1945 }
1946
1947 static int link_new_bound_to_list(Link *link) {
1948         Manager *m;
1949         Link *carrier;
1950         Iterator i;
1951         int r;
1952         bool list_updated = false;
1953
1954         assert(link);
1955         assert(link->manager);
1956
1957         if (!link->network)
1958                 return 0;
1959
1960         if (strv_isempty(link->network->bind_carrier))
1961                 return 0;
1962
1963         m = link->manager;
1964
1965         HASHMAP_FOREACH (carrier, m->links, i) {
1966                 if (strv_fnmatch(link->network->bind_carrier, carrier->ifname, 0)) {
1967                         r = link_put_carrier(link, carrier, &link->bound_to_links);
1968                         if (r < 0)
1969                                 return r;
1970
1971                         list_updated = true;
1972                 }
1973         }
1974
1975         if (list_updated)
1976                 link_dirty(link);
1977
1978         HASHMAP_FOREACH (carrier, link->bound_to_links, i) {
1979                 r = link_put_carrier(carrier, link, &carrier->bound_by_links);
1980                 if (r < 0)
1981                         return r;
1982
1983                 link_dirty(carrier);
1984         }
1985
1986         return 0;
1987 }
1988
1989 static int link_new_carrier_maps(Link *link) {
1990         int r;
1991
1992         r = link_new_bound_by_list(link);
1993         if (r < 0)
1994                 return r;
1995
1996         r = link_handle_bound_by_list(link);
1997         if (r < 0)
1998                 return r;
1999
2000         r = link_new_bound_to_list(link);
2001         if (r < 0)
2002                 return r;
2003
2004         r = link_handle_bound_to_list(link);
2005         if (r < 0)
2006                 return r;
2007
2008         return 0;
2009 }
2010
2011 static void link_free_bound_to_list(Link *link) {
2012         Link *bound_to;
2013         Iterator i;
2014
2015         HASHMAP_FOREACH (bound_to, link->bound_to_links, i) {
2016                 hashmap_remove(link->bound_to_links, INT_TO_PTR(bound_to->ifindex));
2017
2018                 if (hashmap_remove(bound_to->bound_by_links, INT_TO_PTR(link->ifindex)))
2019                         link_dirty(bound_to);
2020         }
2021
2022         return;
2023 }
2024
2025 static void link_free_bound_by_list(Link *link) {
2026         Link *bound_by;
2027         Iterator i;
2028
2029         HASHMAP_FOREACH (bound_by, link->bound_by_links, i) {
2030                 hashmap_remove(link->bound_by_links, INT_TO_PTR(bound_by->ifindex));
2031
2032                 if (hashmap_remove(bound_by->bound_to_links, INT_TO_PTR(link->ifindex))) {
2033                         link_dirty(bound_by);
2034                         link_handle_bound_to_list(bound_by);
2035                 }
2036         }
2037
2038         return;
2039 }
2040
2041 static void link_free_carrier_maps(Link *link) {
2042         bool list_updated = false;
2043
2044         assert(link);
2045
2046         if (!hashmap_isempty(link->bound_to_links)) {
2047                 link_free_bound_to_list(link);
2048                 list_updated = true;
2049         }
2050
2051         if (!hashmap_isempty(link->bound_by_links)) {
2052                 link_free_bound_by_list(link);
2053                 list_updated = true;
2054         }
2055
2056         if (list_updated)
2057                 link_dirty(link);
2058
2059         return;
2060 }
2061
2062 static int link_append_to_master(Link *link, NetDev *netdev) {
2063         Link *master;
2064         int r;
2065
2066         assert(link);
2067         assert(netdev);
2068
2069         r = link_get(link->manager, netdev->ifindex, &master);
2070         if (r < 0)
2071                 return r;
2072
2073         r = set_ensure_allocated(&master->slaves, NULL);
2074         if (r < 0)
2075                 return r;
2076
2077         r = set_put(master->slaves, link);
2078         if (r < 0)
2079                 return r;
2080
2081         link_ref(link);
2082         return 0;
2083 }
2084
2085 static void link_drop_from_master(Link *link, NetDev *netdev) {
2086         Link *master;
2087
2088         assert(link);
2089
2090         if (!link->manager || !netdev)
2091                 return;
2092
2093         if (link_get(link->manager, netdev->ifindex, &master) < 0)
2094                 return;
2095
2096         link_unref(set_remove(master->slaves, link));
2097 }
2098
2099 static void link_detach_from_manager(Link *link) {
2100         if (!link || !link->manager)
2101                 return;
2102
2103         link_unref(set_remove(link->manager->links_requesting_uuid, link));
2104         link_clean(link);
2105
2106         /* The following must be called at last. */
2107         assert_se(hashmap_remove(link->manager->links, INT_TO_PTR(link->ifindex)) == link);
2108         link_unref(link);
2109 }
2110
2111 void link_drop(Link *link) {
2112         if (!link || link->state == LINK_STATE_LINGER)
2113                 return;
2114
2115         link_set_state(link, LINK_STATE_LINGER);
2116
2117         link_free_carrier_maps(link);
2118
2119         if (link->network) {
2120                 link_drop_from_master(link, link->network->bridge);
2121                 link_drop_from_master(link, link->network->bond);
2122         }
2123
2124         log_link_debug(link, "Link removed");
2125
2126         (void) unlink(link->state_file);
2127         link_detach_from_manager(link);
2128 }
2129
2130 static int link_joined(Link *link) {
2131         int r;
2132
2133         assert(link);
2134         assert(link->network);
2135
2136         if (!hashmap_isempty(link->bound_to_links)) {
2137                 r = link_handle_bound_to_list(link);
2138                 if (r < 0)
2139                         return r;
2140         } else if (!(link->flags & IFF_UP)) {
2141                 r = link_up(link);
2142                 if (r < 0) {
2143                         link_enter_failed(link);
2144                         return r;
2145                 }
2146         }
2147
2148         if (link->network->bridge) {
2149                 r = link_set_bridge(link);
2150                 if (r < 0)
2151                         log_link_error_errno(link, r, "Could not set bridge message: %m");
2152
2153                 r = link_append_to_master(link, link->network->bridge);
2154                 if (r < 0)
2155                         log_link_error_errno(link, r, "Failed to add to bridge master's slave list: %m");
2156         }
2157
2158         if (link->network->bond) {
2159                 r = link_set_bond(link);
2160                 if (r < 0)
2161                         log_link_error_errno(link, r, "Could not set bond message: %m");
2162
2163                 r = link_append_to_master(link, link->network->bond);
2164                 if (r < 0)
2165                         log_link_error_errno(link, r, "Failed to add to bond master's slave list: %m");
2166         }
2167
2168         if (link->network->use_br_vlan &&
2169             (link->network->bridge || streq_ptr("bridge", link->kind))) {
2170                 r = link_set_bridge_vlan(link);
2171                 if (r < 0)
2172                         log_link_error_errno(link, r, "Could not set bridge vlan: %m");
2173         }
2174
2175         /* Skip setting up addresses until it gets carrier,
2176            or it would try to set addresses twice,
2177            which is bad for non-idempotent steps. */
2178         if (!link_has_carrier(link) && !link->network->configure_without_carrier)
2179                 return 0;
2180
2181         return link_request_set_addresses(link);
2182 }
2183
2184 static int netdev_join_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
2185         int r;
2186
2187         assert(link);
2188         assert(link->network);
2189         assert(link->enslaving > 0);
2190
2191         link->enslaving--;
2192
2193         if (IN_SET(link->state, LINK_STATE_FAILED, LINK_STATE_LINGER))
2194                 return 1;
2195
2196         r = sd_netlink_message_get_errno(m);
2197         if (r < 0 && r != -EEXIST) {
2198                 log_link_error_errno(link, r, "Could not join netdev: %m");
2199                 link_enter_failed(link);
2200                 return 1;
2201         } else
2202                 log_link_debug(link, "Joined netdev");
2203
2204         if (link->enslaving == 0) {
2205                 link_joined(link);
2206         }
2207
2208         return 1;
2209 }
2210
2211 static int link_enter_join_netdev(Link *link) {
2212         NetDev *netdev;
2213         Iterator i;
2214         int r;
2215
2216         assert(link);
2217         assert(link->network);
2218         assert(link->state == LINK_STATE_INITIALIZED);
2219
2220         link_set_state(link, LINK_STATE_CONFIGURING);
2221
2222         link_dirty(link);
2223         link->enslaving = 0;
2224
2225         if (link->network->bond) {
2226                 if (link->network->bond->state == NETDEV_STATE_READY &&
2227                     link->network->bond->ifindex == link->master_ifindex)
2228                         return link_joined(link);
2229
2230                 log_struct(LOG_DEBUG,
2231                            LOG_LINK_INTERFACE(link),
2232                            LOG_NETDEV_INTERFACE(link->network->bond),
2233                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", link->network->bond->ifname));
2234
2235                 link->enslaving++;
2236
2237                 r = netdev_join(link->network->bond, link, netdev_join_handler);
2238                 if (r < 0) {
2239                         log_struct_errno(LOG_WARNING, r,
2240                                          LOG_LINK_INTERFACE(link),
2241                                          LOG_NETDEV_INTERFACE(link->network->bond),
2242                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", link->network->bond->ifname));
2243                         link_enter_failed(link);
2244                         return r;
2245                 }
2246         }
2247
2248         if (link->network->bridge) {
2249                 log_struct(LOG_DEBUG,
2250                            LOG_LINK_INTERFACE(link),
2251                            LOG_NETDEV_INTERFACE(link->network->bridge),
2252                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", link->network->bridge->ifname));
2253
2254                 link->enslaving++;
2255
2256                 r = netdev_join(link->network->bridge, link, netdev_join_handler);
2257                 if (r < 0) {
2258                         log_struct_errno(LOG_WARNING, r,
2259                                          LOG_LINK_INTERFACE(link),
2260                                          LOG_NETDEV_INTERFACE(link->network->bridge),
2261                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", link->network->bridge->ifname));
2262                         link_enter_failed(link);
2263                         return r;
2264                 }
2265         }
2266
2267         if (link->network->vrf) {
2268                 log_struct(LOG_DEBUG,
2269                            LOG_LINK_INTERFACE(link),
2270                            LOG_NETDEV_INTERFACE(link->network->vrf),
2271                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", link->network->vrf->ifname));
2272
2273                 link->enslaving++;
2274
2275                 r = netdev_join(link->network->vrf, link, netdev_join_handler);
2276                 if (r < 0) {
2277                         log_struct_errno(LOG_WARNING, r,
2278                                          LOG_LINK_INTERFACE(link),
2279                                          LOG_NETDEV_INTERFACE(link->network->vrf),
2280                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", link->network->vrf->ifname));
2281                         link_enter_failed(link);
2282                         return r;
2283                 }
2284         }
2285
2286         HASHMAP_FOREACH(netdev, link->network->stacked_netdevs, i) {
2287
2288                 if (netdev->ifindex > 0)
2289                         /* Assume already enslaved. */
2290                         continue;
2291
2292                 if (netdev_get_create_type(netdev) != NETDEV_CREATE_STACKED)
2293                         continue;
2294
2295                 log_struct(LOG_DEBUG,
2296                            LOG_LINK_INTERFACE(link),
2297                            LOG_NETDEV_INTERFACE(netdev),
2298                            LOG_LINK_MESSAGE(link, "Enslaving by '%s'", netdev->ifname));
2299
2300                 link->enslaving++;
2301
2302                 r = netdev_join(netdev, link, netdev_join_handler);
2303                 if (r < 0) {
2304                         log_struct_errno(LOG_WARNING, r,
2305                                          LOG_LINK_INTERFACE(link),
2306                                          LOG_NETDEV_INTERFACE(netdev),
2307                                          LOG_LINK_MESSAGE(link, "Could not join netdev '%s': %m", netdev->ifname));
2308                         link_enter_failed(link);
2309                         return r;
2310                 }
2311         }
2312
2313         if (link->enslaving == 0)
2314                 return link_joined(link);
2315
2316         return 0;
2317 }
2318
2319 static int link_set_ipv4_forward(Link *link) {
2320         int r;
2321
2322         if (!link_ipv4_forward_enabled(link))
2323                 return 0;
2324
2325         /* We propagate the forwarding flag from one interface to the
2326          * global setting one way. This means: as long as at least one
2327          * interface was configured at any time that had IP forwarding
2328          * enabled the setting will stay on for good. We do this
2329          * primarily to keep IPv4 and IPv6 packet forwarding behaviour
2330          * somewhat in sync (see below). */
2331
2332         r = sysctl_write_ip_property(AF_INET, NULL, "ip_forward", "1");
2333         if (r < 0)
2334                 log_link_warning_errno(link, r, "Cannot turn on IPv4 packet forwarding, ignoring: %m");
2335
2336         return 0;
2337 }
2338
2339 static int link_set_ipv6_forward(Link *link) {
2340         int r;
2341
2342         if (!link_ipv6_forward_enabled(link))
2343                 return 0;
2344
2345         /* On Linux, the IPv6 stack does not know a per-interface
2346          * packet forwarding setting: either packet forwarding is on
2347          * for all, or off for all. We hence don't bother with a
2348          * per-interface setting, but simply propagate the interface
2349          * flag, if it is set, to the global flag, one-way. Note that
2350          * while IPv4 would allow a per-interface flag, we expose the
2351          * same behaviour there and also propagate the setting from
2352          * one to all, to keep things simple (see above). */
2353
2354         r = sysctl_write_ip_property(AF_INET6, "all", "forwarding", "1");
2355         if (r < 0)
2356                 log_link_warning_errno(link, r, "Cannot configure IPv6 packet forwarding, ignoring: %m");
2357
2358         return 0;
2359 }
2360
2361 static int link_set_ipv6_privacy_extensions(Link *link) {
2362         IPv6PrivacyExtensions s;
2363         int r;
2364
2365         s = link_ipv6_privacy_extensions(link);
2366         if (s < 0)
2367                 return 0;
2368
2369         r = sysctl_write_ip_property_int(AF_INET6, link->ifname, "use_tempaddr", (int) link->network->ipv6_privacy_extensions);
2370         if (r < 0)
2371                 log_link_warning_errno(link, r, "Cannot configure IPv6 privacy extension for interface: %m");
2372
2373         return 0;
2374 }
2375
2376 static int link_set_ipv6_accept_ra(Link *link) {
2377         int r;
2378
2379         /* Make this a NOP if IPv6 is not available */
2380         if (!socket_ipv6_is_supported())
2381                 return 0;
2382
2383         if (link->flags & IFF_LOOPBACK)
2384                 return 0;
2385
2386         if (!link->network)
2387                 return 0;
2388
2389         r = sysctl_write_ip_property(AF_INET6, link->ifname, "accept_ra", "0");
2390         if (r < 0)
2391                 log_link_warning_errno(link, r, "Cannot disable kernel IPv6 accept_ra for interface: %m");
2392
2393         return 0;
2394 }
2395
2396 static int link_set_ipv6_dad_transmits(Link *link) {
2397         int r;
2398
2399         /* Make this a NOP if IPv6 is not available */
2400         if (!socket_ipv6_is_supported())
2401                 return 0;
2402
2403         if (link->flags & IFF_LOOPBACK)
2404                 return 0;
2405
2406         if (!link->network)
2407                 return 0;
2408
2409         if (link->network->ipv6_dad_transmits < 0)
2410                 return 0;
2411
2412         r = sysctl_write_ip_property_int(AF_INET6, link->ifname, "dad_transmits", link->network->ipv6_dad_transmits);
2413         if (r < 0)
2414                 log_link_warning_errno(link, r, "Cannot set IPv6 dad transmits for interface: %m");
2415
2416         return 0;
2417 }
2418
2419 static int link_set_ipv6_hop_limit(Link *link) {
2420         int r;
2421
2422         /* Make this a NOP if IPv6 is not available */
2423         if (!socket_ipv6_is_supported())
2424                 return 0;
2425
2426         if (link->flags & IFF_LOOPBACK)
2427                 return 0;
2428
2429         if (!link->network)
2430                 return 0;
2431
2432         if (link->network->ipv6_hop_limit < 0)
2433                 return 0;
2434
2435         r = sysctl_write_ip_property_int(AF_INET6, link->ifname, "hop_limit", link->network->ipv6_hop_limit);
2436         if (r < 0)
2437                 log_link_warning_errno(link, r, "Cannot set IPv6 hop limit for interface: %m");
2438
2439         return 0;
2440 }
2441
2442 static int link_set_ipv6_mtu(Link *link) {
2443         int r;
2444
2445         /* Make this a NOP if IPv6 is not available */
2446         if (!socket_ipv6_is_supported())
2447                 return 0;
2448
2449         if (link->flags & IFF_LOOPBACK)
2450                 return 0;
2451
2452         if (link->network->ipv6_mtu == 0)
2453                 return 0;
2454
2455         r = sysctl_write_ip_property_uint32(AF_INET6, link->ifname, "mtu", link->network->ipv6_mtu);
2456         if (r < 0)
2457                 log_link_warning_errno(link, r, "Cannot set IPv6 MTU for interface: %m");
2458
2459         return 0;
2460 }
2461
2462 static bool link_is_static_address_configured(Link *link, Address *address) {
2463         Address *net_address;
2464
2465         assert(link);
2466         assert(address);
2467
2468         if (!link->network)
2469                 return false;
2470
2471         LIST_FOREACH(addresses, net_address, link->network->static_addresses)
2472                 if (address_equal(net_address, address))
2473                         return true;
2474
2475         return false;
2476 }
2477
2478 static bool link_is_static_route_configured(Link *link, Route *route) {
2479         Route *net_route;
2480
2481         assert(link);
2482         assert(route);
2483
2484         if (!link->network)
2485                 return false;
2486
2487         LIST_FOREACH(routes, net_route, link->network->static_routes)
2488                 if (route_equal(net_route, route))
2489                         return true;
2490
2491         return false;
2492 }
2493
2494 static bool link_address_is_dynamic(Link *link, Address *address) {
2495         Route *route;
2496         Iterator i;
2497
2498         assert(link);
2499         assert(address);
2500
2501         if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME)
2502                 return true;
2503
2504         /* Even when the address is leased from a DHCP server, networkd assign the address
2505          * without lifetime when KeepConfiguration=dhcp. So, let's check that we have
2506          * corresponding routes with RTPROT_DHCP. */
2507         SET_FOREACH(route, link->routes_foreign, i) {
2508                 if (route->protocol != RTPROT_DHCP)
2509                         continue;
2510
2511                 if (address->family != route->family)
2512                         continue;
2513
2514                 if (in_addr_equal(address->family, &address->in_addr, &route->prefsrc))
2515                         return true;
2516         }
2517
2518         return false;
2519 }
2520
2521 static int link_drop_foreign_config(Link *link) {
2522         Address *address;
2523         Route *route;
2524         Iterator i;
2525         int r;
2526
2527         SET_FOREACH(address, link->addresses_foreign, i) {
2528                 /* we consider IPv6LL addresses to be managed by the kernel */
2529                 if (address->family == AF_INET6 && in_addr_is_link_local(AF_INET6, &address->in_addr) == 1)
2530                         continue;
2531
2532                 if (link_address_is_dynamic(link, address)) {
2533                         if (FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_DHCP))
2534                                 continue;
2535                 } else if (FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_STATIC))
2536                         continue;
2537
2538                 if (link_is_static_address_configured(link, address)) {
2539                         r = address_add(link, address->family, &address->in_addr, address->prefixlen, NULL);
2540                         if (r < 0)
2541                                 return log_link_error_errno(link, r, "Failed to add address: %m");
2542                 } else {
2543                         r = address_remove(address, link, NULL);
2544                         if (r < 0)
2545                                 return r;
2546                 }
2547         }
2548
2549         SET_FOREACH(route, link->routes_foreign, i) {
2550                 /* do not touch routes managed by the kernel */
2551                 if (route->protocol == RTPROT_KERNEL)
2552                         continue;
2553
2554                 if (route->protocol == RTPROT_STATIC &&
2555                     FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_STATIC))
2556                         continue;
2557
2558                 if (route->protocol == RTPROT_DHCP &&
2559                     FLAGS_SET(link->network->keep_configuration, KEEP_CONFIGURATION_DHCP))
2560                         continue;
2561
2562                 if (link_is_static_route_configured(link, route)) {
2563                         r = route_add(link, route->family, &route->dst, route->dst_prefixlen, route->tos, route->priority, route->table, NULL);
2564                         if (r < 0)
2565                                 return r;
2566                 } else {
2567                         r = route_remove(route, link, NULL);
2568                         if (r < 0)
2569                                 return r;
2570                 }
2571         }
2572
2573         return 0;
2574 }
2575
2576 static int link_drop_config(Link *link) {
2577         Address *address, *pool_address;
2578         Route *route;
2579         Iterator i;
2580         int r;
2581
2582         SET_FOREACH(address, link->addresses, i) {
2583                 /* we consider IPv6LL addresses to be managed by the kernel */
2584                 if (address->family == AF_INET6 && in_addr_is_link_local(AF_INET6, &address->in_addr) == 1)
2585                         continue;
2586
2587                 r = address_remove(address, link, NULL);
2588                 if (r < 0)
2589                         return r;
2590
2591                 /* If this address came from an address pool, clean up the pool */
2592                 LIST_FOREACH(addresses, pool_address, link->pool_addresses) {
2593                         if (address_equal(address, pool_address)) {
2594                                 LIST_REMOVE(addresses, link->pool_addresses, pool_address);
2595                                 address_free(pool_address);
2596                                 break;
2597                         }
2598                 }
2599         }
2600
2601         SET_FOREACH(route, link->routes, i) {
2602                 /* do not touch routes managed by the kernel */
2603                 if (route->protocol == RTPROT_KERNEL)
2604                         continue;
2605
2606                 r = route_remove(route, link, NULL);
2607                 if (r < 0)
2608                         return r;
2609         }
2610
2611         ndisc_flush(link);
2612
2613         return 0;
2614 }
2615
2616 static int link_configure(Link *link) {
2617         int r;
2618
2619         assert(link);
2620         assert(link->network);
2621         assert(link->state == LINK_STATE_INITIALIZED);
2622
2623         if (STRPTR_IN_SET(link->kind, "can", "vcan", "vxcan"))
2624                 return link_configure_can(link);
2625
2626         /* Drop foreign config, but ignore loopback or critical devices.
2627          * We do not want to remove loopback address or addresses used for root NFS. */
2628         if (!(link->flags & IFF_LOOPBACK) &&
2629             link->network->keep_configuration != KEEP_CONFIGURATION_YES) {
2630                 r = link_drop_foreign_config(link);
2631                 if (r < 0)
2632                         return r;
2633         }
2634
2635         r = link_set_proxy_arp(link);
2636         if (r < 0)
2637                return r;
2638
2639         r = ipv6_proxy_ndp_addresses_configure(link);
2640         if (r < 0)
2641                 return r;
2642
2643         r = link_set_ipv4_forward(link);
2644         if (r < 0)
2645                 return r;
2646
2647         r = link_set_ipv6_forward(link);
2648         if (r < 0)
2649                 return r;
2650
2651         r = link_set_ipv6_privacy_extensions(link);
2652         if (r < 0)
2653                 return r;
2654
2655         r = link_set_ipv6_accept_ra(link);
2656         if (r < 0)
2657                 return r;
2658
2659         r = link_set_ipv6_dad_transmits(link);
2660         if (r < 0)
2661                 return r;
2662
2663         r = link_set_ipv6_hop_limit(link);
2664         if (r < 0)
2665                 return r;
2666
2667         r = link_set_flags(link);
2668         if (r < 0)
2669                 return r;
2670
2671         r = link_set_ipv6_mtu(link);
2672         if (r < 0)
2673                 return r;
2674
2675         if (link_ipv4ll_enabled(link, ADDRESS_FAMILY_IPV4 | ADDRESS_FAMILY_FALLBACK_IPV4)) {
2676                 r = ipv4ll_configure(link);
2677                 if (r < 0)
2678                         return r;
2679         }
2680
2681         if (link_dhcp4_enabled(link)) {
2682                 r = dhcp4_set_promote_secondaries(link);
2683                 if (r < 0)
2684                         return r;
2685
2686                 r = dhcp4_configure(link);
2687                 if (r < 0)
2688                         return r;
2689         }
2690
2691         if (link_dhcp4_server_enabled(link)) {
2692                 r = sd_dhcp_server_new(&link->dhcp_server, link->ifindex);
2693                 if (r < 0)
2694                         return r;
2695
2696                 r = sd_dhcp_server_attach_event(link->dhcp_server, NULL, 0);
2697                 if (r < 0)
2698                         return r;
2699         }
2700
2701         if (link_dhcp6_enabled(link) ||
2702             link_ipv6_accept_ra_enabled(link)) {
2703                 r = dhcp6_configure(link);
2704                 if (r < 0)
2705                         return r;
2706         }
2707
2708         if (link_ipv6_accept_ra_enabled(link)) {
2709                 r = ndisc_configure(link);
2710                 if (r < 0)
2711                         return r;
2712         }
2713
2714         if (link_radv_enabled(link)) {
2715                 r = radv_configure(link);
2716                 if (r < 0)
2717                         return r;
2718         }
2719
2720         if (link_lldp_rx_enabled(link)) {
2721                 r = link_lldp_rx_configure(link);
2722                 if (r < 0)
2723                         return r;
2724         }
2725
2726         r = link_configure_mtu(link);
2727         if (r < 0)
2728                 return r;
2729
2730         r = link_configure_addrgen_mode(link);
2731         if (r < 0)
2732                 return r;
2733
2734         return link_configure_after_setting_mtu(link);
2735 }
2736
2737 static int link_configure_after_setting_mtu(Link *link) {
2738         int r;
2739
2740         assert(link);
2741         assert(link->network);
2742         assert(link->state == LINK_STATE_INITIALIZED);
2743
2744         if (link->setting_mtu)
2745                 return 0;
2746
2747         if (link_has_carrier(link) || link->network->configure_without_carrier) {
2748                 r = link_acquire_conf(link);
2749                 if (r < 0)
2750                         return r;
2751         }
2752
2753         return link_enter_join_netdev(link);
2754 }
2755
2756 static int duid_set_uuid(DUID *duid, sd_id128_t uuid) {
2757         assert(duid);
2758
2759         if (duid->raw_data_len > 0)
2760                 return 0;
2761
2762         if (duid->type != DUID_TYPE_UUID)
2763                 return -EINVAL;
2764
2765         memcpy(&duid->raw_data, &uuid, sizeof(sd_id128_t));
2766         duid->raw_data_len = sizeof(sd_id128_t);
2767
2768         return 1;
2769 }
2770
2771 int get_product_uuid_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
2772         Manager *manager = userdata;
2773         const sd_bus_error *e;
2774         const void *a;
2775         size_t sz;
2776         DUID *duid;
2777         Link *link;
2778         int r;
2779
2780         assert(m);
2781         assert(manager);
2782
2783         e = sd_bus_message_get_error(m);
2784         if (e) {
2785                 log_error_errno(sd_bus_error_get_errno(e),
2786                                 "Could not get product UUID. Falling back to use machine-app-specific ID as DUID-UUID: %s",
2787                                 e->message);
2788                 goto configure;
2789         }
2790
2791         r = sd_bus_message_read_array(m, 'y', &a, &sz);
2792         if (r < 0)
2793                 goto configure;
2794
2795         if (sz != sizeof(sd_id128_t)) {
2796                 log_error("Invalid product UUID. Falling back to use machine-app-specific ID as DUID-UUID.");
2797                 goto configure;
2798         }
2799
2800         memcpy(&manager->product_uuid, a, sz);
2801         while ((duid = set_steal_first(manager->duids_requesting_uuid)))
2802                 (void) duid_set_uuid(duid, manager->product_uuid);
2803
2804         manager->duids_requesting_uuid = set_free(manager->duids_requesting_uuid);
2805
2806 configure:
2807         while ((link = set_steal_first(manager->links_requesting_uuid))) {
2808                 r = link_configure(link);
2809                 if (r < 0)
2810                         log_link_error_errno(link, r, "Failed to configure link: %m");
2811         }
2812
2813         manager->links_requesting_uuid = set_free(manager->links_requesting_uuid);
2814
2815         /* To avoid calling GetProductUUID() bus method so frequently, set the flag below
2816          * even if the method fails. */
2817         manager->has_product_uuid = true;
2818
2819         return 1;
2820 }
2821
2822 static bool link_requires_uuid(Link *link) {
2823         const DUID *duid;
2824
2825         assert(link);
2826         assert(link->manager);
2827         assert(link->network);
2828
2829         duid = link_get_duid(link);
2830         if (duid->type != DUID_TYPE_UUID || duid->raw_data_len != 0)
2831                 return false;
2832
2833         if (link_dhcp4_enabled(link) && IN_SET(link->network->dhcp_client_identifier, DHCP_CLIENT_ID_DUID, DHCP_CLIENT_ID_DUID_ONLY))
2834                 return true;
2835
2836         if (link_dhcp6_enabled(link) || link_ipv6_accept_ra_enabled(link))
2837                 return true;
2838
2839         return false;
2840 }
2841
2842 static int link_configure_duid(Link *link) {
2843         Manager *m;
2844         DUID *duid;
2845         int r;
2846
2847         assert(link);
2848         assert(link->manager);
2849         assert(link->network);
2850
2851         m = link->manager;
2852         duid = link_get_duid(link);
2853
2854         if (!link_requires_uuid(link))
2855                 return 1;
2856
2857         if (m->has_product_uuid) {
2858                 (void) duid_set_uuid(duid, m->product_uuid);
2859                 return 1;
2860         }
2861
2862         if (!m->links_requesting_uuid) {
2863                 r = manager_request_product_uuid(m, link);
2864                 if (r < 0) {
2865                         if (r == -ENOMEM)
2866                                 return r;
2867
2868                         log_link_warning_errno(link, r,
2869                                                "Failed to get product UUID. Falling back to use machine-app-specific ID as DUID-UUID: %m");
2870                         return 1;
2871                 }
2872         } else {
2873                 r = set_put(m->links_requesting_uuid, link);
2874                 if (r < 0)
2875                         return log_oom();
2876
2877                 r = set_put(m->duids_requesting_uuid, duid);
2878                 if (r < 0)
2879                         return log_oom();
2880         }
2881
2882         return 0;
2883 }
2884
2885 static int link_initialized_and_synced(Link *link) {
2886         Network *network;
2887         int r;
2888
2889         assert(link);
2890         assert(link->ifname);
2891         assert(link->manager);
2892
2893         /* We may get called either from the asynchronous netlink callback,
2894          * or directly for link_add() if running in a container. See link_add(). */
2895         if (!IN_SET(link->state, LINK_STATE_PENDING, LINK_STATE_INITIALIZED))
2896                 return 0;
2897
2898         log_link_debug(link, "Link state is up-to-date");
2899         link_set_state(link, LINK_STATE_INITIALIZED);
2900
2901         r = link_new_bound_by_list(link);
2902         if (r < 0)
2903                 return r;
2904
2905         r = link_handle_bound_by_list(link);
2906         if (r < 0)
2907                 return r;
2908
2909         if (!link->network) {
2910                 r = network_get(link->manager, link->sd_device, link->ifname,
2911                                 &link->mac, &network);
2912                 if (r == -ENOENT) {
2913                         link_enter_unmanaged(link);
2914                         return 0;
2915                 } else if (r == 0 && network->unmanaged) {
2916                         link_enter_unmanaged(link);
2917                         return 0;
2918                 } else if (r < 0)
2919                         return r;
2920
2921                 if (link->flags & IFF_LOOPBACK) {
2922                         if (network->link_local != ADDRESS_FAMILY_NO)
2923                                 log_link_debug(link, "Ignoring link-local autoconfiguration for loopback link");
2924
2925                         if (network->dhcp != ADDRESS_FAMILY_NO)
2926                                 log_link_debug(link, "Ignoring DHCP clients for loopback link");
2927
2928                         if (network->dhcp_server)
2929                                 log_link_debug(link, "Ignoring DHCP server for loopback link");
2930                 }
2931
2932                 r = network_apply(network, link);
2933                 if (r < 0)
2934                         return r;
2935         }
2936
2937         r = link_new_bound_to_list(link);
2938         if (r < 0)
2939                 return r;
2940
2941         /* link_configure_duid() returns 0 if it requests product UUID. In that case,
2942          * link_configure() is called later asynchronously. */
2943         r = link_configure_duid(link);
2944         if (r <= 0)
2945                 return r;
2946
2947         r = link_configure(link);
2948         if (r < 0)
2949                 return r;
2950
2951         return 0;
2952 }
2953
2954 static int link_initialized_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {
2955         (void) link_initialized_and_synced(link);
2956         return 1;
2957 }
2958
2959 int link_initialized(Link *link, sd_device *device) {
2960         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
2961         int r;
2962
2963         assert(link);
2964         assert(link->manager);
2965         assert(link->manager->rtnl);
2966         assert(device);
2967
2968         if (link->state != LINK_STATE_PENDING)
2969                 return 0;
2970
2971         if (link->sd_device)
2972                 return 0;
2973
2974         log_link_debug(link, "udev initialized link");
2975         link_set_state(link, LINK_STATE_INITIALIZED);
2976
2977         link->sd_device = sd_device_ref(device);
2978
2979         /* udev has initialized the link, but we don't know if we have yet
2980          * processed the NEWLINK messages with the latest state. Do a GETLINK,
2981          * when it returns we know that the pending NEWLINKs have already been
2982          * processed and that we are up-to-date */
2983
2984         r = sd_rtnl_message_new_link(link->manager->rtnl, &req, RTM_GETLINK,
2985                                      link->ifindex);
2986         if (r < 0)
2987                 return r;
2988
2989         r = netlink_call_async(link->manager->rtnl, NULL, req, link_initialized_handler,
2990                                link_netlink_destroy_callback, link);
2991         if (r < 0)
2992                 return r;
2993
2994         link_ref(link);
2995
2996         return 0;
2997 }
2998
2999 static int link_load(Link *link) {
3000         _cleanup_free_ char *network_file = NULL,
3001                             *addresses = NULL,
3002                             *routes = NULL,
3003                             *dhcp4_address = NULL,
3004                             *ipv4ll_address = NULL;
3005         union in_addr_union address;
3006         union in_addr_union route_dst;
3007         const char *p;
3008         int r;
3009
3010         assert(link);
3011
3012         r = parse_env_file(NULL, link->state_file,
3013                            "NETWORK_FILE", &network_file,
3014                            "ADDRESSES", &addresses,
3015                            "ROUTES", &routes,
3016                            "DHCP4_ADDRESS", &dhcp4_address,
3017                            "IPV4LL_ADDRESS", &ipv4ll_address);
3018         if (r < 0 && r != -ENOENT)
3019                 return log_link_error_errno(link, r, "Failed to read %s: %m", link->state_file);
3020
3021         if (network_file) {
3022                 Network *network;
3023                 char *suffix;
3024
3025                 /* drop suffix */
3026                 suffix = strrchr(network_file, '.');
3027                 if (!suffix) {
3028                         log_link_debug(link, "Failed to get network name from %s", network_file);
3029                         goto network_file_fail;
3030                 }
3031                 *suffix = '\0';
3032
3033                 r = network_get_by_name(link->manager, basename(network_file), &network);
3034                 if (r < 0) {
3035                         log_link_debug_errno(link, r, "Failed to get network %s: %m", basename(network_file));
3036                         goto network_file_fail;
3037                 }
3038
3039                 r = network_apply(network, link);
3040                 if (r < 0)
3041                         return log_link_error_errno(link, r, "Failed to apply network %s: %m", basename(network_file));
3042         }
3043
3044 network_file_fail:
3045
3046         if (addresses) {
3047                 p = addresses;
3048
3049                 for (;;) {
3050                         _cleanup_free_ char *address_str = NULL;
3051                         char *prefixlen_str;
3052                         int family;
3053                         unsigned char prefixlen;
3054
3055                         r = extract_first_word(&p, &address_str, NULL, 0);
3056                         if (r < 0) {
3057                                 log_link_debug_errno(link, r, "Failed to extract next address string: %m");
3058                                 continue;
3059                         }
3060                         if (r == 0)
3061                                 break;
3062
3063                         prefixlen_str = strchr(address_str, '/');
3064                         if (!prefixlen_str) {
3065                                 log_link_debug(link, "Failed to parse address and prefix length %s", address_str);
3066                                 continue;
3067                         }
3068
3069                         *prefixlen_str++ = '\0';
3070
3071                         r = sscanf(prefixlen_str, "%hhu", &prefixlen);
3072                         if (r != 1) {
3073                                 log_link_error(link, "Failed to parse prefixlen %s", prefixlen_str);
3074                                 continue;
3075                         }
3076
3077                         r = in_addr_from_string_auto(address_str, &family, &address);
3078                         if (r < 0) {
3079                                 log_link_debug_errno(link, r, "Failed to parse address %s: %m", address_str);
3080                                 continue;
3081                         }
3082
3083                         r = address_add(link, family, &address, prefixlen, NULL);
3084                         if (r < 0)
3085                                 return log_link_error_errno(link, r, "Failed to add address: %m");
3086                 }
3087         }
3088
3089         if (routes) {
3090                 p = routes;
3091
3092                 for (;;) {
3093                         Route *route;
3094                         _cleanup_free_ char *route_str = NULL;
3095                         _cleanup_(sd_event_source_unrefp) sd_event_source *expire = NULL;
3096                         usec_t lifetime;
3097                         char *prefixlen_str;
3098                         int family;
3099                         unsigned char prefixlen, tos, table;
3100                         uint32_t priority;
3101
3102                         r = extract_first_word(&p, &route_str, NULL, 0);
3103                         if (r < 0) {
3104                                 log_link_debug_errno(link, r, "Failed to extract next route string: %m");
3105                                 continue;
3106                         }
3107                         if (r == 0)
3108                                 break;
3109
3110                         prefixlen_str = strchr(route_str, '/');
3111                         if (!prefixlen_str) {
3112                                 log_link_debug(link, "Failed to parse route %s", route_str);
3113                                 continue;
3114                         }
3115
3116                         *prefixlen_str++ = '\0';
3117
3118                         r = sscanf(prefixlen_str, "%hhu/%hhu/%"SCNu32"/%hhu/"USEC_FMT, &prefixlen, &tos, &priority, &table, &lifetime);
3119                         if (r != 5) {
3120                                 log_link_debug(link,
3121                                                "Failed to parse destination prefix length, tos, priority, table or expiration %s",
3122                                                prefixlen_str);
3123                                 continue;
3124                         }
3125
3126                         r = in_addr_from_string_auto(route_str, &family, &route_dst);
3127                         if (r < 0) {
3128                                 log_link_debug_errno(link, r, "Failed to parse route destination %s: %m", route_str);
3129                                 continue;
3130                         }
3131
3132                         r = route_add(link, family, &route_dst, prefixlen, tos, priority, table, &route);
3133                         if (r < 0)
3134                                 return log_link_error_errno(link, r, "Failed to add route: %m");
3135
3136                         if (lifetime != USEC_INFINITY && !kernel_route_expiration_supported()) {
3137                                 r = sd_event_add_time(link->manager->event, &expire, clock_boottime_or_monotonic(), lifetime,
3138                                                       0, route_expire_handler, route);
3139                                 if (r < 0)
3140                                         log_link_warning_errno(link, r, "Could not arm route expiration handler: %m");
3141                         }
3142
3143                         route->lifetime = lifetime;
3144                         sd_event_source_unref(route->expire);
3145                         route->expire = TAKE_PTR(expire);
3146                 }
3147         }
3148
3149         if (dhcp4_address) {
3150                 r = in_addr_from_string(AF_INET, dhcp4_address, &address);
3151                 if (r < 0) {
3152                         log_link_debug_errno(link, r, "Failed to parse DHCPv4 address %s: %m", dhcp4_address);
3153                         goto dhcp4_address_fail;
3154                 }
3155
3156                 r = sd_dhcp_client_new(&link->dhcp_client, link->network ? link->network->dhcp_anonymize : 0);
3157                 if (r < 0)
3158                         return log_link_error_errno(link, r, "Failed to create DHCPv4 client: %m");
3159
3160                 r = sd_dhcp_client_set_request_address(link->dhcp_client, &address.in);
3161                 if (r < 0)
3162                         return log_link_error_errno(link, r, "Failed to set initial DHCPv4 address %s: %m", dhcp4_address);
3163         }
3164
3165 dhcp4_address_fail:
3166
3167         if (ipv4ll_address) {
3168                 r = in_addr_from_string(AF_INET, ipv4ll_address, &address);
3169                 if (r < 0) {
3170                         log_link_debug_errno(link, r, "Failed to parse IPv4LL address %s: %m", ipv4ll_address);
3171                         goto ipv4ll_address_fail;
3172                 }
3173
3174                 r = sd_ipv4ll_new(&link->ipv4ll);
3175                 if (r < 0)
3176                         return log_link_error_errno(link, r, "Failed to create IPv4LL client: %m");
3177
3178                 r = sd_ipv4ll_set_address(link->ipv4ll, &address.in);
3179                 if (r < 0)
3180                         return log_link_error_errno(link, r, "Failed to set initial IPv4LL address %s: %m", ipv4ll_address);
3181         }
3182
3183 ipv4ll_address_fail:
3184
3185         return 0;
3186 }
3187
3188 int link_add(Manager *m, sd_netlink_message *message, Link **ret) {
3189         _cleanup_(sd_device_unrefp) sd_device *device = NULL;
3190         char ifindex_str[2 + DECIMAL_STR_MAX(int)];
3191         Link *link;
3192         int r;
3193
3194         assert(m);
3195         assert(m->rtnl);
3196         assert(message);
3197         assert(ret);
3198
3199         r = link_new(m, message, ret);
3200         if (r < 0)
3201                 return r;
3202
3203         link = *ret;
3204
3205         log_link_debug(link, "Link %d added", link->ifindex);
3206
3207         r = link_load(link);
3208         if (r < 0)
3209                 return r;
3210
3211         if (detect_container() <= 0) {
3212                 /* not in a container, udev will be around */
3213                 sprintf(ifindex_str, "n%d", link->ifindex);
3214                 r = sd_device_new_from_device_id(&device, ifindex_str);
3215                 if (r < 0) {
3216                         log_link_warning_errno(link, r, "Could not find device: %m");
3217                         goto failed;
3218                 }
3219
3220                 r = sd_device_get_is_initialized(device);
3221                 if (r < 0) {
3222                         log_link_warning_errno(link, r, "Could not determine whether the device is initialized or not: %m");
3223                         goto failed;
3224                 }
3225                 if (r == 0) {
3226                         /* not yet ready */
3227                         log_link_debug(link, "link pending udev initialization...");
3228                         return 0;
3229                 }
3230
3231                 r = device_is_renaming(device);
3232                 if (r < 0) {
3233                         log_link_warning_errno(link, r, "Failed to determine the device is renamed or not: %m");
3234                         goto failed;
3235                 }
3236                 if (r > 0) {
3237                         log_link_debug(link, "Interface is under renaming, pending initialization.");
3238                         return 0;
3239                 }
3240
3241                 r = link_initialized(link, device);
3242                 if (r < 0)
3243                         goto failed;
3244         } else {
3245                 r = link_initialized_and_synced(link);
3246                 if (r < 0)
3247                         goto failed;
3248         }
3249
3250         return 0;
3251 failed:
3252         link_enter_failed(link);
3253         return r;
3254 }
3255
3256 int link_ipv6ll_gained(Link *link, const struct in6_addr *address) {
3257         int r;
3258
3259         assert(link);
3260
3261         log_link_info(link, "Gained IPv6LL");
3262
3263         link->ipv6ll_address = *address;
3264         link_check_ready(link);
3265
3266         if (IN_SET(link->state, LINK_STATE_CONFIGURING, LINK_STATE_CONFIGURED)) {
3267                 r = link_acquire_ipv6_conf(link);
3268                 if (r < 0) {
3269                         link_enter_failed(link);
3270                         return r;
3271                 }
3272         }
3273
3274         return 0;
3275 }
3276
3277 static int link_carrier_gained(Link *link) {
3278         int r;
3279
3280         assert(link);
3281