5035b7ce0895cfe0f2a3c12992ca0d1d57c06f24
[petitboot] / discover / network.c
1
2 #include <stdbool.h>
3 #include <stdint.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <errno.h>
7 #include <sys/socket.h>
8 #include <linux/if.h>
9 #include <linux/netlink.h>
10 #include <linux/rtnetlink.h>
11 #include <i18n/i18n.h>
12
13 #include <log/log.h>
14 #include <list/list.h>
15 #include <file/file.h>
16 #include <types/types.h>
17 #include <talloc/talloc.h>
18 #include <waiter/waiter.h>
19 #include <process/process.h>
20 #include <system/system.h>
21
22 #include "network.h"
23 #include "sysinfo.h"
24 #include "platform.h"
25 #include "device-handler.h"
26 #include "paths.h"
27
28 #define HWADDR_SIZE     6
29 #define PIDFILE_BASE    (LOCAL_STATE_DIR "/petitboot/")
30 #define INITIAL_BUFSIZE 4096
31
32 #define for_each_nlmsg(buf, nlmsg, len) \
33         for (nlmsg = (struct nlmsghdr *)buf; \
34                 NLMSG_OK(nlmsg, len) && nlmsg->nlmsg_type != NLMSG_DONE; \
35                 nlmsg = NLMSG_NEXT(nlmsg, len))
36
37 #define for_each_rta(buf, rta, attrlen) \
38         for (rta = (struct rtattr *)(buf); RTA_OK(rta, attrlen); \
39                         rta = RTA_NEXT(rta, attrlen))
40
41
42 struct interface {
43         int     ifindex;
44         char    name[IFNAMSIZ];
45         uint8_t hwaddr[HWADDR_SIZE];
46
47         enum {
48                 IFSTATE_NEW,
49                 IFSTATE_UP_WAITING_LINK,
50                 IFSTATE_CONFIGURED,
51                 IFSTATE_IGNORED,
52         } state;
53
54         struct list_item list;
55         struct process *udhcpc_process;
56         struct discover_device *dev;
57 };
58
59 struct network {
60         struct list             interfaces;
61         struct device_handler   *handler;
62         struct waiter           *waiter;
63         int                     netlink_sd;
64         void                    *netlink_buf;
65         unsigned int            netlink_buf_size;
66         bool                    manual_config;
67         bool                    dry_run;
68 };
69
70 static char *mac_bytes_to_string(void *ctx, uint8_t *addr, int len)
71 {
72         const int l = strlen("xx:");
73         char *buf;
74         int i;
75
76         if (len <= 0)
77                 return talloc_strdup(ctx, "");
78
79         buf = talloc_array(ctx, char, (len * l) + 1);
80
81         for (i = 0; i < len; i++)
82                 sprintf(buf + (l * i), "%02x:", addr[i]);
83
84         *(buf + (l * len) - 1) = '\0';
85
86         return buf;
87 }
88
89 static const struct interface_config *find_config_by_hwaddr(
90                 uint8_t *hwaddr)
91 {
92         const struct config *config;
93         unsigned int i;
94
95         config = config_get();
96         if (!config)
97                 return NULL;
98
99         for (i = 0; i < config->network.n_interfaces; i++) {
100                 struct interface_config *ifconf = config->network.interfaces[i];
101
102                 if (!memcmp(ifconf->hwaddr, hwaddr, HWADDR_SIZE))
103                         return ifconf;
104         }
105
106         return NULL;
107 }
108
109 static struct interface *find_interface_by_ifindex(struct network *network,
110                 int ifindex)
111 {
112         struct interface *interface;
113
114         list_for_each_entry(&network->interfaces, interface, list)
115                 if (interface->ifindex == ifindex)
116                         return interface;
117
118         return NULL;
119 }
120
121 static struct interface *find_interface_by_name(struct network *network,
122                 const char *name)
123 {
124         struct interface *interface;
125
126         list_for_each_entry(&network->interfaces, interface, list)
127                 if (!strcmp(interface->name, name))
128                         return interface;
129
130         return NULL;
131 }
132
133 static struct interface *find_interface_by_uuid(struct network *network,
134                 const char *uuid)
135 {
136         struct interface *interface;
137         char *mac;
138
139         list_for_each_entry(&network->interfaces, interface, list) {
140                 mac = mac_bytes_to_string(interface, interface->hwaddr,
141                                         sizeof(interface->hwaddr));
142                 if (!strcmp(mac, uuid)) {
143                         talloc_free(mac);
144                         return interface;
145                 }
146                 talloc_free(mac);
147         }
148
149         return NULL;
150 }
151
152 uint8_t *find_mac_by_name(void *ctx, struct network *network,
153                 const char *name)
154 {
155         struct interface *interface;
156
157         interface = find_interface_by_name(network, name);
158         if (!interface)
159                 return NULL;
160
161         return talloc_memdup(ctx, &interface->hwaddr,
162                              sizeof(uint8_t) * HWADDR_SIZE);
163 }
164
165 static int network_init_netlink(struct network *network)
166 {
167         struct sockaddr_nl addr;
168         int rc;
169
170         memset(&addr, 0, sizeof(addr));
171         addr.nl_family = AF_NETLINK;
172         addr.nl_groups = RTMGRP_LINK;
173
174         network->netlink_sd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
175         if (network->netlink_sd < 0) {
176                 perror("socket(AF_NETLINK)");
177                 return -1;
178         }
179
180         rc = bind(network->netlink_sd, (struct sockaddr *)&addr, sizeof(addr));
181         if (rc) {
182                 perror("bind(sockaddr_nl)");
183                 close(network->netlink_sd);
184                 return -1;
185         }
186
187         network->netlink_buf_size = INITIAL_BUFSIZE;
188         network->netlink_buf = talloc_array(network, char,
189                                 network->netlink_buf_size);
190
191         return 0;
192 }
193
194 static int network_send_link_query(struct network *network)
195 {
196         int rc;
197         struct {
198                 struct nlmsghdr nlmsg;
199                 struct rtgenmsg rtmsg;
200         } msg;
201
202         memset(&msg, 0, sizeof(msg));
203
204         msg.nlmsg.nlmsg_len = sizeof(msg);
205         msg.nlmsg.nlmsg_type = RTM_GETLINK;
206         msg.nlmsg.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT;
207         msg.nlmsg.nlmsg_seq = 0;
208         msg.nlmsg.nlmsg_pid = 0;
209         msg.rtmsg.rtgen_family = AF_UNSPEC;
210
211         rc = send(network->netlink_sd, &msg, sizeof(msg), MSG_NOSIGNAL);
212         if (rc != sizeof(msg))
213                 return -1;
214
215         return 0;
216 }
217
218 static void create_interface_dev(struct network *network,
219                 struct interface *interface)
220 {
221         char *uuid = mac_bytes_to_string(interface, interface->hwaddr,
222                                                 sizeof(interface->hwaddr));
223
224         interface->dev = discover_device_create(network->handler, uuid,
225                                                 interface->name);
226         interface->dev->device->type = DEVICE_TYPE_NETWORK;
227         device_handler_add_device(network->handler, interface->dev);
228         talloc_free(uuid);
229 }
230
231 static void remove_interface(struct network *network,
232                 struct interface *interface)
233 {
234         if (interface->dev)
235                 device_handler_remove(network->handler, interface->dev);
236         list_remove(&interface->list);
237         talloc_free(interface);
238 }
239
240 void network_register_device(struct network *network,
241                 struct discover_device *dev)
242 {
243         struct interface *iface;
244
245         if (dev->uuid)
246                 iface = find_interface_by_uuid(network, dev->uuid);
247         else
248                 iface = find_interface_by_name(network, dev->label);
249         if (!iface)
250                 return;
251
252         iface->dev = dev;
253         dev->uuid = mac_bytes_to_string(iface->dev, iface->hwaddr,
254                         sizeof(iface->hwaddr));
255 }
256
257 void network_unregister_device(struct network *network,
258                 struct discover_device *dev)
259 {
260         struct interface *iface;
261
262         iface = find_interface_by_uuid(network, dev->uuid);
263         if (!iface)
264                 return;
265
266         iface->dev = NULL;
267 }
268
269 static int interface_change(struct interface *interface, bool up)
270 {
271         const char *statestr = up ? "up" : "down";
272         int rc;
273
274         if (!up && interface->udhcpc_process) {
275                 /* we don't care about the callback from here */
276                 interface->udhcpc_process->exit_cb = NULL;
277                 interface->udhcpc_process->data = NULL;
278                 process_stop_async(interface->udhcpc_process);
279                 process_release(interface->udhcpc_process);
280         }
281
282         if (!up) {
283                 rc = process_run_simple(interface, pb_system_apps.ip,
284                                 "address", "flush", "dev", interface->name,
285                                 NULL);
286                 if (rc)
287                         pb_log("failed to flush addresses from interface %s\n",
288                                 interface->name);
289         }
290
291         rc = process_run_simple(interface, pb_system_apps.ip,
292                         "link", "set", interface->name, statestr, NULL);
293         if (rc) {
294                 pb_log("failed to bring interface %s %s\n", interface->name,
295                                 statestr);
296                 return -1;
297         }
298         return 0;
299 }
300
301 static int interface_up(struct interface *interface)
302 {
303         return interface_change(interface, true);
304 }
305
306 static int interface_down(struct interface *interface)
307 {
308         return interface_change(interface, false);
309 }
310
311 static void udhcpc_process_exit(struct process *process)
312 {
313         struct interface *interface = process->data;
314         pb_debug("udhcp client [pid %d] for interface %s exited, rc %d\n",
315                         process->pid, interface->name, process->exit_status);
316         interface->udhcpc_process = NULL;
317         process_release(process);
318 }
319
320 static void configure_interface_dhcp(struct network *network,
321                 struct interface *interface)
322 {
323         const struct platform *platform;
324         char pidfile[256], id[10];
325         struct process *process;
326         int rc;
327         const char *argv[] = {
328                 pb_system_apps.udhcpc,
329                 "-R",
330                 "-f",
331                 "-O", "pxeconffile",
332                 "-O", "pxepathprefix",
333                 "-p", pidfile,
334                 "-i", interface->name,
335                 "-x", id, /* [11,12] - dhcp client identifier */
336                 NULL,
337         };
338
339         device_handler_status_dev_info(network->handler, interface->dev,
340                         _("Configuring with DHCP"));
341
342         snprintf(pidfile, sizeof(pidfile), "%s/udhcpc-%s.pid",
343                         PIDFILE_BASE, interface->name);
344
345         platform = platform_get();
346         if (platform && platform->dhcp_arch_id != 0xffff)
347                 snprintf(id, sizeof(id), "0x5d:%04x", platform->dhcp_arch_id);
348         else
349                 argv[11] = NULL;
350
351         process = process_create(interface);
352
353         process->path = pb_system_apps.udhcpc;
354         process->argv = argv;
355         process->exit_cb = udhcpc_process_exit;
356         process->data = interface;
357
358         rc = process_run_async(process);
359
360         if (rc)
361                 process_release(process);
362         else
363                 interface->udhcpc_process = process;
364
365         return;
366 }
367
368 static void configure_interface_static(struct network *network,
369                 struct interface *interface,
370                 const struct interface_config *config)
371 {
372         int rc;
373
374         device_handler_status_dev_info(network->handler, interface->dev,
375                         _("Configuring with static address (ip: %s)"),
376                         config->static_config.address);
377
378         rc = process_run_simple(interface, pb_system_apps.ip,
379                         "address", "add", config->static_config.address,
380                         "dev", interface->name, NULL);
381
382
383         if (rc) {
384                 pb_log("failed to add address %s to interface %s\n",
385                                 config->static_config.address,
386                                 interface->name);
387                 return;
388         }
389
390         system_info_set_interface_address(sizeof(interface->hwaddr),
391                                 interface->hwaddr,
392                                 config->static_config.address);
393
394         /* we need the interface up before we can route through it */
395         rc = interface_up(interface);
396         if (rc)
397                 return;
398
399         if (config->static_config.gateway)
400                 rc = process_run_simple(interface, pb_system_apps.ip,
401                                 "route", "add", "default",
402                                 "via", config->static_config.gateway,
403                                 NULL);
404
405         if (rc) {
406                 pb_log("failed to add default route %s on interface %s\n",
407                                 config->static_config.gateway,
408                                 interface->name);
409         }
410
411         if (config->static_config.url) {
412                 pb_log("config URL %s\n", config->static_config.url);
413                 device_handler_process_url(network->handler,
414                                 config->static_config.url,
415                                 mac_bytes_to_string(interface->dev,
416                                                 interface->hwaddr,
417                                                 sizeof(interface->hwaddr)),
418                                 config->static_config.address);
419         }
420
421         return;
422 }
423
424 static void configure_interface(struct network *network,
425                 struct interface *interface, bool up, bool link)
426 {
427         const struct interface_config *config = NULL;
428
429         if (interface->state == IFSTATE_IGNORED)
430                 return;
431
432         /* old interface? check that we're still up and running */
433         if (interface->state == IFSTATE_CONFIGURED) {
434                 if (!up)
435                         interface->state = IFSTATE_NEW;
436                 else if (!link)
437                         interface->state = IFSTATE_UP_WAITING_LINK;
438                 else {
439                         pb_debug("network: skipping configured interface %s\n",
440                                         interface->name);
441                         return;
442                 }
443         }
444
445         /* always up the lookback, no other handling required */
446         if (!strcmp(interface->name, "lo")) {
447                 if (interface->state == IFSTATE_NEW)
448                         interface_up(interface);
449                 interface->state = IFSTATE_CONFIGURED;
450                 return;
451         }
452
453         config = find_config_by_hwaddr(interface->hwaddr);
454         if (config && config->ignore) {
455                 pb_log("network: ignoring interface %s\n", interface->name);
456                 interface->state = IFSTATE_IGNORED;
457                 return;
458         }
459
460         /* if we're in manual config mode, we need an interface configuration */
461         if (network->manual_config && !config) {
462                 interface->state = IFSTATE_IGNORED;
463                 pb_log("network: skipping %s: manual config mode, "
464                                 "but no config for this interface\n",
465                                 interface->name);
466                 return;
467         }
468
469         /* new interface? bring up to the point so we can detect a link */
470         if (interface->state == IFSTATE_NEW) {
471                 if (!up) {
472                         interface_up(interface);
473                         pb_log("network: bringing up interface %s\n",
474                                         interface->name);
475                         return;
476
477                 } else if (!link) {
478                         interface->state = IFSTATE_UP_WAITING_LINK;
479                 }
480         }
481
482         /* no link? wait for a notification */
483         if (interface->state == IFSTATE_UP_WAITING_LINK && !link)
484                 return;
485
486         pb_log("network: configuring interface %s\n", interface->name);
487
488         if (!config || config->method == CONFIG_METHOD_DHCP) {
489                 configure_interface_dhcp(network, interface);
490
491         } else if (config->method == CONFIG_METHOD_STATIC) {
492                 configure_interface_static(network, interface, config);
493                 /* Nothing left to do for static interfaces */
494                 pending_network_jobs_start();
495         }
496
497         interface->state = IFSTATE_CONFIGURED;
498 }
499
500 static int network_handle_nlmsg(struct network *network, struct nlmsghdr *nlmsg)
501 {
502         bool have_ifaddr, have_ifname;
503         struct interface *interface, *tmp;
504         struct ifinfomsg *info;
505         struct rtattr *attr;
506         unsigned int mtu;
507         uint8_t ifaddr[6];
508         char ifname[IFNAMSIZ+1];
509         int attrlen, type;
510
511
512         /* we're only interested in NEWLINK messages */
513         type = nlmsg->nlmsg_type;
514         if (!(type == RTM_NEWLINK || type == RTM_DELLINK))
515                 return 0;
516
517         info = NLMSG_DATA(nlmsg);
518
519         have_ifaddr = have_ifname = false;
520         mtu = 1;
521
522         attrlen = nlmsg->nlmsg_len - sizeof(*info);
523
524         /* extract the interface name and hardware address attributes */
525         for_each_rta(info + 1, attr, attrlen) {
526                 void *data = RTA_DATA(attr);
527
528                 switch (attr->rta_type) {
529                 case IFLA_ADDRESS:
530                         memcpy(ifaddr, data, sizeof(ifaddr));
531                         have_ifaddr = true;
532                         break;
533
534                 case IFLA_IFNAME:
535                         strncpy(ifname, data, IFNAMSIZ);
536                         have_ifname = true;
537                         break;
538
539                 case IFLA_MTU:
540                         mtu = *(unsigned int *)data;
541                         break;
542                 }
543         }
544
545         if (!have_ifaddr || !have_ifname)
546                 return -1;
547
548         if (type == RTM_DELLINK || mtu == 0) {
549                 interface = find_interface_by_ifindex(network, info->ifi_index);
550                 if (!interface)
551                         return 0;
552                 pb_log("network: interface %s removed\n", interface->name);
553                 remove_interface(network, interface);
554                 return 0;
555         }
556
557         /* ignore the default tun device in some environments */
558         if (strncmp(ifname, "tun", strlen("tun")) == 0)
559                 return 0;
560
561         interface = find_interface_by_ifindex(network, info->ifi_index);
562         if (!interface) {
563                 interface = talloc_zero(network, struct interface);
564                 interface->ifindex = info->ifi_index;
565                 interface->state = IFSTATE_NEW;
566                 memcpy(interface->hwaddr, ifaddr, sizeof(interface->hwaddr));
567                 strncpy(interface->name, ifname, sizeof(interface->name) - 1);
568
569                 list_for_each_entry(&network->interfaces, tmp, list)
570                         if (memcmp(interface->hwaddr, tmp->hwaddr,
571                                    sizeof(interface->hwaddr)) == 0) {
572                                 pb_log("%s: %s has duplicate MAC address, ignoring\n",
573                                        __func__, interface->name);
574                                 talloc_free(interface);
575                                 return -1;
576                         }
577
578                 list_add(&network->interfaces, &interface->list);
579                 create_interface_dev(network, interface);
580         }
581
582         /* A repeated RTM_NEWLINK can represent an interface name change */
583         if (strncmp(interface->name, ifname, IFNAMSIZ)) {
584                 pb_debug("ifname update: %s -> %s\n", interface->name, ifname);
585                 strncpy(interface->name, ifname, sizeof(interface->name) - 1);
586                 talloc_free(interface->dev->device->id);
587                 interface->dev->device->id =
588                         talloc_strdup(interface->dev->device, ifname);
589         }
590
591         /* notify the sysinfo code about changes to this interface */
592         if (strcmp(interface->name, "lo"))
593                 system_info_register_interface(
594                                 sizeof(interface->hwaddr),
595                                 interface->hwaddr, interface->name,
596                                 info->ifi_flags & IFF_LOWER_UP);
597
598         if (!interface->dev)
599                 create_interface_dev(network, interface);
600
601         configure_interface(network, interface,
602                         info->ifi_flags & IFF_UP,
603                         info->ifi_flags & IFF_LOWER_UP);
604
605         return 0;
606 }
607
608 static int network_netlink_process(void *arg)
609 {
610         struct network *network = arg;
611         struct nlmsghdr *nlmsg;
612         struct msghdr msg;
613         struct iovec iov;
614         unsigned int len;
615         int rc, flags;
616
617         memset(&msg, 0, sizeof(msg));
618         msg.msg_iov = &iov;
619         msg.msg_iovlen = 1;
620
621         flags = MSG_PEEK;
622
623 retry:
624         iov.iov_len = network->netlink_buf_size;
625         iov.iov_base = network->netlink_buf;
626
627         rc = recvmsg(network->netlink_sd, &msg, flags);
628
629         if (rc < 0) {
630                 perror("netlink recv header");
631                 return -1;
632         }
633
634         len = rc;
635
636         /* if the netlink message was larger than our buffer, realloc
637          * before reading again */
638         if (len > network->netlink_buf_size || msg.msg_flags & MSG_TRUNC) {
639                 network->netlink_buf_size *= 2;
640                 network->netlink_buf = talloc_realloc(network,
641                                         network->netlink_buf,
642                                         char *,
643                                         network->netlink_buf_size);
644                 goto retry;
645         }
646
647         /* otherwise, we're good to read the entire message without PEEK */
648         if (flags == MSG_PEEK) {
649                 flags = 0;
650                 goto retry;
651         }
652
653         for_each_nlmsg(network->netlink_buf, nlmsg, len)
654                 network_handle_nlmsg(network, nlmsg);
655
656         return 0;
657 }
658
659 static void network_init_dns(struct network *network)
660 {
661         const struct config *config;
662         unsigned int i;
663         int rc, len;
664         bool modified;
665         char *buf;
666
667         if (network->dry_run)
668                 return;
669
670         config = config_get();
671         if (!config || !config->network.n_dns_servers)
672                 return;
673
674         rc = read_file(network, "/etc/resolv.conf", &buf, &len);
675
676         if (rc) {
677                 buf = talloc_strdup(network, "");
678                 len = 0;
679         }
680
681         modified = false;
682
683         for (i = 0; i < config->network.n_dns_servers; i++) {
684                 int dns_conf_len;
685                 char *dns_conf;
686
687                 dns_conf = talloc_asprintf(network, "nameserver %s\n",
688                                 config->network.dns_servers[i]);
689
690                 if (strstr(buf, dns_conf)) {
691                         talloc_free(dns_conf);
692                         continue;
693                 }
694
695                 dns_conf_len = strlen(dns_conf);
696                 buf = talloc_realloc(network, buf, char, len + dns_conf_len + 1);
697                 memcpy(buf + len, dns_conf, dns_conf_len);
698                 len += dns_conf_len;
699                 buf[len] = '\0';
700                 modified = true;
701
702                 talloc_free(dns_conf);
703         }
704
705         if (modified) {
706                 rc = replace_file("/etc/resolv.conf", buf, len);
707                 if (rc)
708                         pb_log("error replacing resolv.conf: %s\n",
709                                         strerror(errno));
710         }
711
712         talloc_free(buf);
713 }
714
715 struct network *network_init(struct device_handler *handler,
716                 struct waitset *waitset, bool dry_run)
717 {
718         struct network *network;
719         int rc;
720
721         network = talloc(handler, struct network);
722         list_init(&network->interfaces);
723         network->handler = handler;
724         network->dry_run = dry_run;
725         network->manual_config = config_get()->network.n_interfaces != 0;
726
727         network_init_dns(network);
728
729         rc = network_init_netlink(network);
730         if (rc)
731                 goto err;
732
733         network->waiter = waiter_register_io(waitset, network->netlink_sd,
734                         WAIT_IN, network_netlink_process, network);
735
736         if (!network->waiter)
737                 goto err;
738
739         rc = network_send_link_query(network);
740         if (rc)
741                 goto err;
742
743         return network;
744
745 err:
746         network_shutdown(network);
747         return NULL;
748 }
749
750 int network_shutdown(struct network *network)
751 {
752         struct interface *interface;
753
754         if (network->waiter)
755                 waiter_remove(network->waiter);
756
757         list_for_each_entry(&network->interfaces, interface, list) {
758                 if (interface->state == IFSTATE_IGNORED)
759                         continue;
760                 if (!strcmp(interface->name, "lo"))
761                         continue;
762                 interface_down(interface);
763         }
764
765         close(network->netlink_sd);
766         talloc_free(network);
767         return 0;
768 }