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