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