chiark / gitweb /
libsystemd-dhcp: DNS name option must be a multiple of 4 bytes
[elogind.git] / src / libsystemd-dhcp / sd-dhcp-client.c
1 /***
2   This file is part of systemd.
3
4   Copyright (C) 2013 Intel Corporation. All rights reserved.
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <net/ethernet.h>
25 #include <sys/param.h>
26
27 #include "util.h"
28 #include "list.h"
29
30 #include "dhcp-protocol.h"
31 #include "dhcp-internal.h"
32 #include "sd-dhcp-client.h"
33
34 #define DHCP_CLIENT_MIN_OPTIONS_SIZE            312
35
36 #define client_state_machine_check(s, r)                                \
37         do {                                                            \
38                 if (s != DHCP_STATE_BOUND &&                            \
39                     s != DHCP_STATE_RENEWING &&                         \
40                     s != DHCP_STATE_REBINDING) {                        \
41                         return (r);                                     \
42                 }                                                       \
43         } while (false)
44
45 struct DHCPLease {
46         uint32_t t1;
47         uint32_t t2;
48         uint32_t lifetime;
49         be32_t address;
50         be32_t server_address;
51         be32_t subnet_mask;
52         be32_t router;
53         struct in_addr *dns;
54         size_t dns_size;
55         uint16_t mtu;
56         char *domainname;
57         char *hostname;
58 };
59
60 typedef struct DHCPLease DHCPLease;
61
62 struct sd_dhcp_client {
63         DHCPState state;
64         sd_event *event;
65         int event_priority;
66         sd_event_source *timeout_resend;
67         int index;
68         int fd;
69         union sockaddr_union link;
70         sd_event_source *receive_message;
71         uint8_t *req_opts;
72         size_t req_opts_allocated;
73         size_t req_opts_size;
74         be32_t last_addr;
75         struct ether_addr mac_addr;
76         uint32_t xid;
77         usec_t start_time;
78         unsigned int attempt;
79         usec_t request_sent;
80         sd_event_source *timeout_t1;
81         sd_event_source *timeout_t2;
82         sd_event_source *timeout_expire;
83         sd_dhcp_client_cb_t cb;
84         void *userdata;
85         DHCPLease *lease;
86 };
87
88 static const uint8_t default_req_opts[] = {
89         DHCP_OPTION_SUBNET_MASK,
90         DHCP_OPTION_ROUTER,
91         DHCP_OPTION_HOST_NAME,
92         DHCP_OPTION_DOMAIN_NAME,
93         DHCP_OPTION_DOMAIN_NAME_SERVER,
94         DHCP_OPTION_NTP_SERVER,
95 };
96
97 static int client_receive_message(sd_event_source *s, int fd,
98                                   uint32_t revents, void *userdata);
99
100 int sd_dhcp_client_set_callback(sd_dhcp_client *client, sd_dhcp_client_cb_t cb,
101                                 void *userdata) {
102         assert_return(client, -EINVAL);
103
104         client->cb = cb;
105         client->userdata = userdata;
106
107         return 0;
108 }
109
110 int sd_dhcp_client_set_request_option(sd_dhcp_client *client, uint8_t option) {
111         size_t i;
112
113         assert_return(client, -EINVAL);
114         assert_return (client->state == DHCP_STATE_INIT, -EBUSY);
115
116         switch(option) {
117         case DHCP_OPTION_PAD:
118         case DHCP_OPTION_OVERLOAD:
119         case DHCP_OPTION_MESSAGE_TYPE:
120         case DHCP_OPTION_PARAMETER_REQUEST_LIST:
121         case DHCP_OPTION_END:
122                 return -EINVAL;
123
124         default:
125                 break;
126         }
127
128         for (i = 0; i < client->req_opts_size; i++)
129                 if (client->req_opts[i] == option)
130                         return -EEXIST;
131
132         if (!GREEDY_REALLOC(client->req_opts, client->req_opts_allocated,
133                             client->req_opts_size + 1))
134                 return -ENOMEM;
135
136         client->req_opts[client->req_opts_size++] = option;
137
138         return 0;
139 }
140
141 int sd_dhcp_client_set_request_address(sd_dhcp_client *client,
142                                        const struct in_addr *last_addr) {
143         assert_return(client, -EINVAL);
144         assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
145
146         if (last_addr)
147                 client->last_addr = last_addr->s_addr;
148         else
149                 client->last_addr = INADDR_ANY;
150
151         return 0;
152 }
153
154 int sd_dhcp_client_set_index(sd_dhcp_client *client, int interface_index) {
155         assert_return(client, -EINVAL);
156         assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
157         assert_return(interface_index >= -1, -EINVAL);
158
159         client->index = interface_index;
160
161         return 0;
162 }
163
164 int sd_dhcp_client_set_mac(sd_dhcp_client *client,
165                            const struct ether_addr *addr) {
166         assert_return(client, -EINVAL);
167         assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
168
169         memcpy(&client->mac_addr, addr, ETH_ALEN);
170
171         return 0;
172 }
173
174 int sd_dhcp_client_get_address(sd_dhcp_client *client, struct in_addr *addr) {
175         assert_return(client, -EINVAL);
176         assert_return(addr, -EINVAL);
177
178         client_state_machine_check (client->state, -EADDRNOTAVAIL);
179
180         addr->s_addr = client->lease->address;
181
182         return 0;
183 }
184
185 int sd_dhcp_client_get_mtu(sd_dhcp_client *client, uint16_t *mtu) {
186         assert_return(client, -EINVAL);
187         assert_return(mtu, -EINVAL);
188
189         client_state_machine_check (client->state, -EADDRNOTAVAIL);
190
191         if (client->lease->mtu)
192                 *mtu = client->lease->mtu;
193         else
194                 return -ENOENT;
195
196         return 0;
197 }
198
199 int sd_dhcp_client_get_dns(sd_dhcp_client *client, struct in_addr **addr, size_t *addr_size) {
200         assert_return(client, -EINVAL);
201         assert_return(addr, -EINVAL);
202         assert_return(addr_size, -EINVAL);
203
204         client_state_machine_check (client->state, -EADDRNOTAVAIL);
205
206         if (client->lease->dns_size) {
207                 *addr_size = client->lease->dns_size;
208                 *addr = client->lease->dns;
209         } else
210                 return -ENOENT;
211
212         return 0;
213 }
214
215 int sd_dhcp_client_get_domainname(sd_dhcp_client *client, const char **domainname) {
216         assert_return(client, -EINVAL);
217         assert_return(domainname, -EINVAL);
218
219         client_state_machine_check (client->state, -EADDRNOTAVAIL);
220
221         if (client->lease->domainname)
222                 *domainname = client->lease->domainname;
223         else
224                 return -ENOENT;
225
226         return 0;
227 }
228
229 int sd_dhcp_client_get_hostname(sd_dhcp_client *client, const char **hostname) {
230         assert_return(client, -EINVAL);
231         assert_return(hostname, -EINVAL);
232
233         client_state_machine_check (client->state, -EADDRNOTAVAIL);
234
235         if (client->lease->hostname)
236                 *hostname = client->lease->hostname;
237         else
238                 return -ENOENT;
239
240         return 0;
241 }
242
243 int sd_dhcp_client_get_router(sd_dhcp_client *client, struct in_addr *addr) {
244         assert_return(client, -EINVAL);
245         assert_return(addr, -EINVAL);
246
247         client_state_machine_check (client->state, -EADDRNOTAVAIL);
248
249         addr->s_addr = client->lease->router;
250
251         return 0;
252 }
253
254 int sd_dhcp_client_get_netmask(sd_dhcp_client *client, struct in_addr *addr) {
255         assert_return(client, -EINVAL);
256         assert_return(addr, -EINVAL);
257
258         client_state_machine_check (client->state, -EADDRNOTAVAIL);
259
260         addr->s_addr = client->lease->subnet_mask;
261
262         return 0;
263 }
264
265 static int client_notify(sd_dhcp_client *client, int event) {
266         if (client->cb)
267                 client->cb(client, event, client->userdata);
268
269         return 0;
270 }
271
272 static void lease_free(DHCPLease *lease) {
273         if (!lease)
274                 return;
275
276         free(lease->hostname);
277         free(lease->domainname);
278         free(lease->dns);
279         free(lease);
280 }
281
282 DEFINE_TRIVIAL_CLEANUP_FUNC(DHCPLease*, lease_free);
283 #define _cleanup_lease_free_ _cleanup_(lease_freep)
284
285 static int client_stop(sd_dhcp_client *client, int error) {
286         assert_return(client, -EINVAL);
287
288         client->receive_message =
289                 sd_event_source_unref(client->receive_message);
290
291         if (client->fd >= 0)
292                 close(client->fd);
293         client->fd = -1;
294
295         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
296
297         client->timeout_t1 = sd_event_source_unref(client->timeout_t1);
298         client->timeout_t2 = sd_event_source_unref(client->timeout_t2);
299         client->timeout_expire = sd_event_source_unref(client->timeout_expire);
300
301         client->attempt = 1;
302
303         client_notify(client, error);
304
305         switch (client->state) {
306
307         case DHCP_STATE_INIT:
308         case DHCP_STATE_SELECTING:
309         case DHCP_STATE_REQUESTING:
310         case DHCP_STATE_BOUND:
311
312                 client->start_time = 0;
313                 client->state = DHCP_STATE_INIT;
314                 break;
315
316         case DHCP_STATE_INIT_REBOOT:
317         case DHCP_STATE_REBOOTING:
318         case DHCP_STATE_RENEWING:
319         case DHCP_STATE_REBINDING:
320
321                 break;
322         }
323
324         if (client->lease) {
325                 lease_free(client->lease);
326                 client->lease = NULL;
327         }
328
329         return 0;
330 }
331
332 static int client_packet_init(sd_dhcp_client *client, uint8_t type,
333                               DHCPMessage *message, uint16_t secs,
334                               uint8_t **opt, size_t *optlen) {
335         int err;
336         be16_t max_size;
337
338         *opt = (uint8_t *)(message + 1);
339
340         if (*optlen < 4)
341                 return -ENOBUFS;
342         *optlen -= 4;
343
344         message->op = BOOTREQUEST;
345         message->htype = 1;
346         message->hlen = ETHER_ADDR_LEN;
347         message->xid = htobe32(client->xid);
348
349         /* Although 'secs' field is a SHOULD in RFC 2131, certain DHCP servers
350            refuse to issue an DHCP lease if 'secs' is set to zero */
351         message->secs = htobe16(secs);
352
353         if (client->state == DHCP_STATE_RENEWING ||
354             client->state == DHCP_STATE_REBINDING)
355                 message->ciaddr = client->lease->address;
356
357         memcpy(&message->chaddr, &client->mac_addr, ETH_ALEN);
358         (*opt)[0] = 0x63;
359         (*opt)[1] = 0x82;
360         (*opt)[2] = 0x53;
361         (*opt)[3] = 0x63;
362
363         *opt += 4;
364
365         err = dhcp_option_append(opt, optlen, DHCP_OPTION_MESSAGE_TYPE, 1,
366                                  &type);
367         if (err < 0)
368                 return err;
369
370         /* Some DHCP servers will refuse to issue an DHCP lease if the Cliient
371            Identifier option is not set */
372         err = dhcp_option_append(opt, optlen, DHCP_OPTION_CLIENT_IDENTIFIER,
373                                  ETH_ALEN, &client->mac_addr);
374         if (err < 0)
375                 return err;
376
377         if (type == DHCP_DISCOVER || type == DHCP_REQUEST) {
378                 err = dhcp_option_append(opt, optlen,
379                                          DHCP_OPTION_PARAMETER_REQUEST_LIST,
380                                          client->req_opts_size,
381                                          client->req_opts);
382                 if (err < 0)
383                         return err;
384
385                 /* Some DHCP servers will send bigger DHCP packets than the
386                    defined default size unless the Maximum Messge Size option
387                    is explicitely set */
388                 max_size = htobe16(DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE +
389                                    DHCP_CLIENT_MIN_OPTIONS_SIZE);
390                 err = dhcp_option_append(opt, optlen,
391                                          DHCP_OPTION_MAXIMUM_MESSAGE_SIZE,
392                                          2, &max_size);
393                 if (err < 0)
394                         return err;
395         }
396
397         return 0;
398 }
399
400 static uint16_t client_checksum(void *buf, int len) {
401         uint32_t sum;
402         uint16_t *check;
403         int i;
404         uint8_t *odd;
405
406         sum = 0;
407         check = buf;
408
409         for (i = 0; i < len / 2 ; i++)
410                 sum += check[i];
411
412         if (len & 0x01) {
413                 odd = buf;
414                 sum += odd[len - 1];
415         }
416
417         while (sum >> 16)
418                 sum = (sum & 0xffff) + (sum >> 16);
419
420         return ~sum;
421 }
422
423 static void client_append_ip_headers(DHCPPacket *packet, uint16_t len) {
424         packet->ip.version = IPVERSION;
425         packet->ip.ihl = DHCP_IP_SIZE / 4;
426         packet->ip.tot_len = htobe16(len);
427
428         packet->ip.protocol = IPPROTO_UDP;
429         packet->ip.saddr = INADDR_ANY;
430         packet->ip.daddr = INADDR_BROADCAST;
431
432         packet->udp.source = htobe16(DHCP_PORT_CLIENT);
433         packet->udp.dest = htobe16(DHCP_PORT_SERVER);
434         packet->udp.len = htobe16(len - DHCP_IP_SIZE);
435
436         packet->ip.check = packet->udp.len;
437         packet->udp.check = client_checksum(&packet->ip.ttl, len - 8);
438
439         packet->ip.ttl = IPDEFTTL;
440         packet->ip.check = 0;
441         packet->ip.check = client_checksum(&packet->ip, DHCP_IP_SIZE);
442 }
443
444 static int client_send_discover(sd_dhcp_client *client, uint16_t secs) {
445         int err = 0;
446         _cleanup_free_ DHCPPacket *discover;
447         size_t optlen, len;
448         uint8_t *opt;
449
450         optlen = DHCP_CLIENT_MIN_OPTIONS_SIZE;
451         len = sizeof(DHCPPacket) + optlen;
452
453         discover = malloc0(len);
454
455         if (!discover)
456                 return -ENOMEM;
457
458         err = client_packet_init(client, DHCP_DISCOVER, &discover->dhcp,
459                                  secs, &opt, &optlen);
460         if (err < 0)
461                 return err;
462
463         if (client->last_addr != INADDR_ANY) {
464                 err = dhcp_option_append(&opt, &optlen,
465                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
466                                          4, &client->last_addr);
467                 if (err < 0)
468                         return err;
469         }
470
471         err = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
472         if (err < 0)
473                 return err;
474
475         client_append_ip_headers(discover, len);
476
477         err = dhcp_network_send_raw_socket(client->fd, &client->link,
478                                            discover, len);
479
480         return err;
481 }
482
483 static int client_send_request(sd_dhcp_client *client, uint16_t secs) {
484         _cleanup_free_ DHCPPacket *request;
485         size_t optlen, len;
486         int err;
487         uint8_t *opt;
488
489         optlen = DHCP_CLIENT_MIN_OPTIONS_SIZE;
490         len = DHCP_MESSAGE_SIZE + optlen;
491
492         request = malloc0(len);
493         if (!request)
494                 return -ENOMEM;
495
496         err = client_packet_init(client, DHCP_REQUEST, &request->dhcp, secs,
497                                  &opt, &optlen);
498         if (err < 0)
499                 return err;
500
501         if (client->state == DHCP_STATE_REQUESTING) {
502                 err = dhcp_option_append(&opt, &optlen,
503                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
504                                          4, &client->lease->address);
505                 if (err < 0)
506                         return err;
507
508                 err = dhcp_option_append(&opt, &optlen,
509                                          DHCP_OPTION_SERVER_IDENTIFIER,
510                                          4, &client->lease->server_address);
511                 if (err < 0)
512                         return err;
513         }
514
515         err = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
516         if (err < 0)
517                 return err;
518
519         if (client->state == DHCP_STATE_RENEWING) {
520                 err = dhcp_network_send_udp_socket(client->fd,
521                                                    client->lease->server_address,
522                                                    &request->dhcp,
523                                                    len - DHCP_IP_UDP_SIZE);
524         } else {
525                 client_append_ip_headers(request, len);
526
527                 err = dhcp_network_send_raw_socket(client->fd, &client->link,
528                                                    request, len);
529         }
530
531         return err;
532 }
533
534 static int client_timeout_resend(sd_event_source *s, uint64_t usec,
535                                  void *userdata) {
536         sd_dhcp_client *client = userdata;
537         usec_t next_timeout = 0;
538         uint32_t time_left;
539         uint16_t secs;
540         int r = 0;
541
542         assert(s);
543         assert(client);
544         assert(client->event);
545
546         switch (client->state) {
547         case DHCP_STATE_RENEWING:
548
549                 time_left = (client->lease->t2 - client->lease->t1)/2;
550                 if (time_left < 60)
551                         time_left = 60;
552
553                 next_timeout = usec + time_left * USEC_PER_SEC;
554
555                 break;
556
557         case DHCP_STATE_REBINDING:
558
559                 time_left = (client->lease->lifetime - client->lease->t2)/2;
560                 if (time_left < 60)
561                         time_left = 60;
562
563                 next_timeout = usec + time_left * USEC_PER_SEC;
564                 break;
565
566         case DHCP_STATE_INIT:
567         case DHCP_STATE_INIT_REBOOT:
568         case DHCP_STATE_REBOOTING:
569         case DHCP_STATE_SELECTING:
570         case DHCP_STATE_REQUESTING:
571         case DHCP_STATE_BOUND:
572
573                 if (client->attempt < 64)
574                         client->attempt *= 2;
575
576                 next_timeout = usec + (client->attempt - 1) * USEC_PER_SEC;
577
578                 break;
579         }
580
581         next_timeout += (random_u32() & 0x1fffff);
582
583         r = sd_event_add_monotonic(client->event, next_timeout,
584                                      10 * USEC_PER_MSEC,
585                                      client_timeout_resend, client,
586                                      &client->timeout_resend);
587         if (r < 0)
588                 goto error;
589
590         r = sd_event_source_set_priority(client->timeout_resend, client->event_priority);
591         if (r < 0)
592                 goto error;
593
594         secs = (usec - client->start_time) / USEC_PER_SEC;
595
596         switch (client->state) {
597         case DHCP_STATE_INIT:
598                 r = client_send_discover(client, secs);
599                 if (r >= 0) {
600                         client->state = DHCP_STATE_SELECTING;
601                         client->attempt = 1;
602                 } else {
603                         if (client->attempt >= 64)
604                                 goto error;
605                 }
606
607                 break;
608
609         case DHCP_STATE_SELECTING:
610                 r = client_send_discover(client, secs);
611                 if (r < 0 && client->attempt >= 64)
612                         goto error;
613
614                 break;
615
616         case DHCP_STATE_REQUESTING:
617         case DHCP_STATE_RENEWING:
618         case DHCP_STATE_REBINDING:
619                 r = client_send_request(client, secs);
620                 if (r < 0 && client->attempt >= 64)
621                          goto error;
622
623                 client->request_sent = usec;
624
625                 break;
626
627         case DHCP_STATE_INIT_REBOOT:
628         case DHCP_STATE_REBOOTING:
629         case DHCP_STATE_BOUND:
630
631                 break;
632         }
633
634         return 0;
635
636 error:
637         client_stop(client, r);
638
639         /* Errors were dealt with when stopping the client, don't spill
640            errors into the event loop handler */
641         return 0;
642 }
643
644 static int client_initialize_events(sd_dhcp_client *client, usec_t usec) {
645         int r;
646
647         assert(client);
648         assert(client->event);
649
650         r = sd_event_add_io(client->event, client->fd, EPOLLIN,
651                             client_receive_message, client,
652                             &client->receive_message);
653         if (r < 0)
654                 goto error;
655
656         r = sd_event_source_set_priority(client->receive_message, client->event_priority);
657         if (r < 0)
658                 goto error;
659
660         r = sd_event_add_monotonic(client->event, usec, 0,
661                                    client_timeout_resend, client,
662                                    &client->timeout_resend);
663         if (r < 0)
664                 goto error;
665
666         r = sd_event_source_set_priority(client->timeout_resend, client->event_priority);
667
668 error:
669         if (r < 0)
670                 client_stop(client, r);
671
672         return 0;
673
674 }
675
676 static int client_timeout_expire(sd_event_source *s, uint64_t usec,
677                                  void *userdata) {
678         sd_dhcp_client *client = userdata;
679
680         client_stop(client, DHCP_EVENT_EXPIRED);
681
682         return 0;
683 }
684
685 static int client_timeout_t2(sd_event_source *s, uint64_t usec, void *userdata) {
686         sd_dhcp_client *client = userdata;
687         int r;
688
689         if (client->fd >= 0) {
690                 client->receive_message =
691                         sd_event_source_unref(client->receive_message);
692                 close(client->fd);
693                 client->fd = -1;
694         }
695
696         client->state = DHCP_STATE_REBINDING;
697         client->attempt = 1;
698
699         r = dhcp_network_bind_raw_socket(client->index, &client->link);
700         if (r < 0) {
701                 client_stop(client, r);
702                 return 0;
703         }
704
705         client->fd = r;
706
707         return client_initialize_events(client, usec);
708 }
709
710 static int client_timeout_t1(sd_event_source *s, uint64_t usec, void *userdata) {
711         sd_dhcp_client *client = userdata;
712         int r;
713
714         client->state = DHCP_STATE_RENEWING;
715         client->attempt = 1;
716
717         r = dhcp_network_bind_udp_socket(client->index,
718                                          client->lease->address);
719         if (r < 0) {
720                 client_stop(client, r);
721                 return 0;
722         }
723
724         client->fd = r;
725
726         return client_initialize_events(client, usec);
727 }
728
729 static int client_parse_offer(uint8_t code, uint8_t len, const uint8_t *option,
730                               void *user_data) {
731         DHCPLease *lease = user_data;
732         be32_t val;
733
734         switch(code) {
735
736         case DHCP_OPTION_IP_ADDRESS_LEASE_TIME:
737                 if (len == 4) {
738                         memcpy(&val, option, 4);
739                         lease->lifetime = be32toh(val);
740                 }
741
742                 break;
743
744         case DHCP_OPTION_SERVER_IDENTIFIER:
745                 if (len >= 4)
746                         memcpy(&lease->server_address, option, 4);
747
748                 break;
749
750         case DHCP_OPTION_SUBNET_MASK:
751                 if (len >= 4)
752                         memcpy(&lease->subnet_mask, option, 4);
753
754                 break;
755
756         case DHCP_OPTION_ROUTER:
757                 if (len >= 4)
758                         memcpy(&lease->router, option, 4);
759
760                 break;
761
762         case DHCP_OPTION_DOMAIN_NAME_SERVER:
763                 if (len && !(len % 4)) {
764                         unsigned i;
765
766                         lease->dns_size = len / 4;
767
768                         free(lease->dns);
769                         lease->dns = new0(struct in_addr, lease->dns_size);
770                         if (!lease->dns)
771                                 return -ENOMEM;
772
773                         for (i = 0; i < lease->dns_size; i++) {
774                                 memcpy(&lease->dns[i].s_addr, option + 4 * i, 4);
775                         }
776                 }
777
778                 break;
779
780         case DHCP_OPTION_INTERFACE_MTU:
781                 if (len >= 2) {
782                         be16_t mtu;
783
784                         memcpy(&mtu, option, 2);
785                         lease->mtu = be16toh(mtu);
786
787                         if (lease->mtu < 68)
788                                 lease->mtu = 0;
789                 }
790
791                 break;
792
793         case DHCP_OPTION_DOMAIN_NAME:
794                 if (len >= 1) {
795                         free(lease->domainname);
796                         lease->domainname = strndup((const char *)option, len);
797                 }
798
799                 break;
800
801         case DHCP_OPTION_HOST_NAME:
802                 if (len >= 1) {
803                         free(lease->hostname);
804                         lease->hostname = strndup((const char *)option, len);
805                 }
806
807                 break;
808
809         case DHCP_OPTION_RENEWAL_T1_TIME:
810                 if (len == 4) {
811                         memcpy(&val, option, 4);
812                         lease->t1 = be32toh(val);
813                 }
814
815                 break;
816
817         case DHCP_OPTION_REBINDING_T2_TIME:
818                 if (len == 4) {
819                         memcpy(&val, option, 4);
820                         lease->t2 = be32toh(val);
821                 }
822
823                 break;
824         }
825
826         return 0;
827 }
828
829 static int client_verify_headers(sd_dhcp_client *client, DHCPPacket *message,
830                                  size_t len) {
831         size_t hdrlen;
832
833         if (len < (DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE))
834                 return -EINVAL;
835
836         hdrlen = message->ip.ihl * 4;
837         if (hdrlen < 20 || hdrlen > len || client_checksum(&message->ip,
838                                                            hdrlen))
839                 return -EINVAL;
840
841         message->ip.check = message->udp.len;
842         message->ip.ttl = 0;
843
844         if (hdrlen + be16toh(message->udp.len) > len ||
845             client_checksum(&message->ip.ttl, be16toh(message->udp.len) + 12))
846                 return -EINVAL;
847
848         if (be16toh(message->udp.source) != DHCP_PORT_SERVER ||
849             be16toh(message->udp.dest) != DHCP_PORT_CLIENT)
850                 return -EINVAL;
851
852         if (message->dhcp.op != BOOTREPLY)
853                 return -EINVAL;
854
855         if (be32toh(message->dhcp.xid) != client->xid)
856                 return -EINVAL;
857
858         if (memcmp(&message->dhcp.chaddr[0], &client->mac_addr.ether_addr_octet,
859                     ETHER_ADDR_LEN))
860                 return -EINVAL;
861
862         return 0;
863 }
864
865 static int client_receive_offer(sd_dhcp_client *client, DHCPPacket *offer,
866                                 size_t len) {
867         _cleanup_lease_free_ DHCPLease *lease = NULL;
868         int r;
869
870         r = client_verify_headers(client, offer, len);
871         if (r < 0)
872                 return r;
873
874         lease = new0(DHCPLease, 1);
875         if (!lease)
876                 return -ENOMEM;
877
878         len = len - DHCP_IP_UDP_SIZE;
879         r = dhcp_option_parse(&offer->dhcp, len, client_parse_offer,
880                               lease);
881         if (r != DHCP_OFFER)
882                 return -ENOMSG;
883
884         lease->address = offer->dhcp.yiaddr;
885
886         if (lease->address == INADDR_ANY ||
887             lease->server_address == INADDR_ANY ||
888             lease->subnet_mask == INADDR_ANY ||
889             lease->lifetime == 0)
890                 return -ENOMSG;
891
892         client->lease = lease;
893         lease = NULL;
894
895         return 0;
896 }
897
898 static int client_receive_ack(sd_dhcp_client *client, const uint8_t *buf,
899                               size_t len) {
900         DHCPPacket *ack;
901         DHCPMessage *dhcp;
902         _cleanup_lease_free_ DHCPLease *lease = NULL;
903         int r;
904
905         if (client->state == DHCP_STATE_RENEWING) {
906                 dhcp = (DHCPMessage *)buf;
907         } else {
908                 ack = (DHCPPacket *)buf;
909
910                 r = client_verify_headers(client, ack, len);
911                 if (r < 0)
912                         return r;
913
914                 dhcp = &ack->dhcp;
915                 len -= DHCP_IP_UDP_SIZE;
916         }
917
918         lease = new0(DHCPLease, 1);
919         if (!lease)
920                 return -ENOMEM;
921
922         r = dhcp_option_parse(dhcp, len, client_parse_offer, lease);
923         if (r == DHCP_NAK)
924                 return DHCP_EVENT_NO_LEASE;
925
926         if (r != DHCP_ACK)
927                 return -ENOMSG;
928
929         lease->address = dhcp->yiaddr;
930
931         if (lease->address == INADDR_ANY ||
932             lease->server_address == INADDR_ANY ||
933             lease->subnet_mask == INADDR_ANY || lease->lifetime == 0)
934                 return -ENOMSG;
935
936         r = DHCP_EVENT_IP_ACQUIRE;
937         if (client->lease) {
938                 if (client->lease->address != lease->address ||
939                     client->lease->subnet_mask != lease->subnet_mask ||
940                     client->lease->router != lease->router) {
941                         r = DHCP_EVENT_IP_CHANGE;
942                 }
943
944                 lease_free(client->lease);
945         }
946
947         client->lease = lease;
948         lease = NULL;
949
950         return r;
951 }
952
953 static uint64_t client_compute_timeout(uint64_t request_sent,
954                                        uint32_t lifetime) {
955         return request_sent + (lifetime - 3) * USEC_PER_SEC +
956                 + (random_u32() & 0x1fffff);
957 }
958
959 static int client_set_lease_timeouts(sd_dhcp_client *client, uint64_t usec) {
960         uint64_t next_timeout;
961         int r;
962
963         assert(client);
964         assert(client->event);
965
966         if (client->lease->lifetime < 10)
967                 return -EINVAL;
968
969         client->timeout_t1 = sd_event_source_unref(client->timeout_t1);
970         client->timeout_t2 = sd_event_source_unref(client->timeout_t2);
971         client->timeout_expire = sd_event_source_unref(client->timeout_expire);
972
973         if (!client->lease->t1)
974                 client->lease->t1 = client->lease->lifetime / 2;
975
976         next_timeout = client_compute_timeout(client->request_sent,
977                                               client->lease->t1);
978         if (next_timeout < usec)
979                 return -EINVAL;
980
981         r = sd_event_add_monotonic(client->event, next_timeout,
982                                      10 * USEC_PER_MSEC,
983                                      client_timeout_t1, client,
984                                      &client->timeout_t1);
985         if (r < 0)
986                 return r;
987
988         r = sd_event_source_set_priority(client->timeout_t1, client->event_priority);
989         if (r < 0)
990                 return r;
991
992         if (!client->lease->t2)
993                 client->lease->t2 = client->lease->lifetime * 7 / 8;
994
995         if (client->lease->t2 < client->lease->t1)
996                 return -EINVAL;
997
998         if (client->lease->lifetime < client->lease->t2)
999                 return -EINVAL;
1000
1001         next_timeout = client_compute_timeout(client->request_sent,
1002                                               client->lease->t2);
1003         if (next_timeout < usec)
1004                 return -EINVAL;
1005
1006         r = sd_event_add_monotonic(client->event, next_timeout,
1007                                      10 * USEC_PER_MSEC,
1008                                      client_timeout_t2, client,
1009                                      &client->timeout_t2);
1010         if (r < 0)
1011                 return r;
1012
1013         r = sd_event_source_set_priority(client->timeout_t2, client->event_priority);
1014         if (r < 0)
1015                 return r;
1016
1017         next_timeout = client_compute_timeout(client->request_sent,
1018                                               client->lease->lifetime);
1019         if (next_timeout < usec)
1020                 return -EINVAL;
1021
1022         r = sd_event_add_monotonic(client->event, next_timeout,
1023                                      10 * USEC_PER_MSEC,
1024                                      client_timeout_expire, client,
1025                                      &client->timeout_expire);
1026         if (r < 0)
1027                 return r;
1028
1029         r = sd_event_source_set_priority(client->timeout_expire, client->event_priority);
1030         if (r < 0)
1031                 return r;
1032
1033         return 0;
1034 }
1035
1036 static int client_receive_message(sd_event_source *s, int fd,
1037                                   uint32_t revents, void *userdata) {
1038         sd_dhcp_client *client = userdata;
1039         uint8_t buf[sizeof(DHCPPacket) + DHCP_CLIENT_MIN_OPTIONS_SIZE];
1040         int buflen = sizeof(buf);
1041         int len, r = 0, notify_event = 0;
1042         DHCPPacket *message;
1043         usec_t time_now;
1044
1045         assert(s);
1046         assert(client);
1047         assert(client->event);
1048
1049         len = read(fd, &buf, buflen);
1050         if (len < 0)
1051                 return 0;
1052
1053         r = sd_event_get_now_monotonic(client->event, &time_now);
1054         if (r < 0)
1055                 goto error;
1056
1057         switch (client->state) {
1058         case DHCP_STATE_SELECTING:
1059
1060                 message = (DHCPPacket *)&buf;
1061
1062                 if (client_receive_offer(client, message, len) >= 0) {
1063
1064                         client->timeout_resend =
1065                                 sd_event_source_unref(client->timeout_resend);
1066
1067                         client->state = DHCP_STATE_REQUESTING;
1068                         client->attempt = 1;
1069
1070                         r = sd_event_add_monotonic(client->event, time_now, 0,
1071                                                    client_timeout_resend,
1072                                                    client,
1073                                                    &client->timeout_resend);
1074                         if (r < 0)
1075                                 goto error;
1076
1077                         r = sd_event_source_set_priority(client->timeout_resend, client->event_priority);
1078                         if (r < 0)
1079                                 goto error;
1080                 }
1081
1082                 break;
1083
1084         case DHCP_STATE_REQUESTING:
1085         case DHCP_STATE_RENEWING:
1086         case DHCP_STATE_REBINDING:
1087
1088                 r = client_receive_ack(client, buf, len);
1089
1090                 if (r == DHCP_EVENT_NO_LEASE)
1091                         goto error;
1092
1093                 if (r >= 0) {
1094                         client->timeout_resend =
1095                                 sd_event_source_unref(client->timeout_resend);
1096
1097                         if (client->state == DHCP_STATE_REQUESTING)
1098                                 notify_event = DHCP_EVENT_IP_ACQUIRE;
1099                         else if (r != DHCP_EVENT_IP_ACQUIRE)
1100                                 notify_event = r;
1101
1102                         client->state = DHCP_STATE_BOUND;
1103                         client->attempt = 1;
1104
1105                         client->last_addr = client->lease->address;
1106
1107                         r = client_set_lease_timeouts(client, time_now);
1108                         if (r < 0)
1109                                 goto error;
1110
1111                         if (notify_event)
1112                                 client_notify(client, notify_event);
1113
1114                         client->receive_message =
1115                                 sd_event_source_unref(client->receive_message);
1116                         close(client->fd);
1117                         client->fd = -1;
1118                 }
1119
1120                 r = 0;
1121
1122                 break;
1123
1124         case DHCP_STATE_INIT:
1125         case DHCP_STATE_INIT_REBOOT:
1126         case DHCP_STATE_REBOOTING:
1127         case DHCP_STATE_BOUND:
1128
1129                 break;
1130         }
1131
1132 error:
1133         if (r < 0 || r == DHCP_EVENT_NO_LEASE)
1134                 return client_stop(client, r);
1135
1136         return 0;
1137 }
1138
1139 int sd_dhcp_client_start(sd_dhcp_client *client) {
1140         int r;
1141
1142         assert_return(client, -EINVAL);
1143         assert_return(client->event, -EINVAL);
1144         assert_return(client->index > 0, -EINVAL);
1145         assert_return(client->state == DHCP_STATE_INIT ||
1146                       client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);
1147
1148         client->xid = random_u32();
1149
1150         r = dhcp_network_bind_raw_socket(client->index, &client->link);
1151
1152         if (r < 0) {
1153                 client_stop(client, r);
1154                 return r;
1155         }
1156
1157         client->fd = r;
1158         client->start_time = now(CLOCK_MONOTONIC);
1159
1160         return client_initialize_events(client, client->start_time);
1161 }
1162
1163 int sd_dhcp_client_stop(sd_dhcp_client *client) {
1164         return client_stop(client, DHCP_EVENT_STOP);
1165 }
1166
1167 int sd_dhcp_client_attach_event(sd_dhcp_client *client, sd_event *event, int priority) {
1168         int r;
1169
1170         assert_return(client, -EINVAL);
1171         assert_return(!client->event, -EBUSY);
1172
1173         if (event)
1174                 client->event = sd_event_ref(event);
1175         else {
1176                 r = sd_event_default(&client->event);
1177                 if (r < 0)
1178                         return 0;
1179         }
1180
1181         client->event_priority = priority;
1182
1183         return 0;
1184 }
1185
1186 int sd_dhcp_client_detach_event(sd_dhcp_client *client) {
1187         assert_return(client, -EINVAL);
1188
1189         client->event = sd_event_unref(client->event);
1190
1191         return 0;
1192 }
1193
1194 sd_event *sd_dhcp_client_get_event(sd_dhcp_client *client) {
1195         if (!client)
1196                 return NULL;
1197
1198         return client->event;
1199 }
1200
1201 void sd_dhcp_client_free(sd_dhcp_client *client) {
1202         if (!client)
1203                 return;
1204
1205         sd_dhcp_client_stop(client);
1206         sd_dhcp_client_detach_event(client);
1207
1208         free(client->req_opts);
1209         free(client);
1210 }
1211
1212 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_dhcp_client*, sd_dhcp_client_free);
1213 #define _cleanup_dhcp_client_free_ _cleanup_(sd_dhcp_client_freep)
1214
1215 int sd_dhcp_client_new(sd_dhcp_client **ret) {
1216         _cleanup_dhcp_client_free_ sd_dhcp_client *client = NULL;
1217
1218         assert_return(ret, -EINVAL);
1219
1220         client = new0(sd_dhcp_client, 1);
1221         if (!client)
1222                 return -ENOMEM;
1223
1224         client->state = DHCP_STATE_INIT;
1225         client->index = -1;
1226         client->fd = -1;
1227         client->attempt = 1;
1228
1229         client->req_opts_size = ELEMENTSOF(default_req_opts);
1230
1231         client->req_opts = memdup(default_req_opts, client->req_opts_size);
1232         if (!client->req_opts)
1233                 return -ENOMEM;
1234
1235         *ret = client;
1236         client = NULL;
1237
1238         return 0;
1239 }