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