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