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