chiark / gitweb /
libsystemd-dhcp: Factor out common code initializing events
[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                 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_INIT:
536         case DHCP_STATE_INIT_REBOOT:
537         case DHCP_STATE_REBOOTING:
538         case DHCP_STATE_SELECTING:
539         case DHCP_STATE_REQUESTING:
540         case DHCP_STATE_BOUND:
541         case DHCP_STATE_REBINDING:
542
543                 if (client->attempt < 64)
544                         client->attempt *= 2;
545
546                 next_timeout = usec + (client->attempt - 1) * USEC_PER_SEC;
547
548                 break;
549         }
550
551         next_timeout += (random_u() & 0x1fffff);
552
553         err = sd_event_add_monotonic(client->event, next_timeout,
554                                      10 * USEC_PER_MSEC,
555                                      client_timeout_resend, client,
556                                      &client->timeout_resend);
557         if (err < 0)
558                 goto error;
559
560         secs = (usec - client->start_time) / USEC_PER_SEC;
561
562         switch (client->state) {
563         case DHCP_STATE_INIT:
564                 err = client_send_discover(client, secs);
565                 if (err >= 0) {
566                         client->state = DHCP_STATE_SELECTING;
567                         client->attempt = 1;
568                 } else {
569                         if (client->attempt >= 64)
570                                 goto error;
571                 }
572
573                 break;
574
575         case DHCP_STATE_SELECTING:
576                 err = client_send_discover(client, secs);
577                 if (err < 0 && client->attempt >= 64)
578                         goto error;
579
580                 break;
581
582         case DHCP_STATE_REQUESTING:
583         case DHCP_STATE_RENEWING:
584                 err = client_send_request(client, secs);
585                 if (err < 0 && client->attempt >= 64)
586                          goto error;
587
588                 client->request_sent = usec;
589
590                 break;
591
592         case DHCP_STATE_INIT_REBOOT:
593         case DHCP_STATE_REBOOTING:
594         case DHCP_STATE_BOUND:
595         case DHCP_STATE_REBINDING:
596
597                 break;
598         }
599
600         return 0;
601
602 error:
603         client_stop(client, err);
604
605         /* Errors were dealt with when stopping the client, don't spill
606            errors into the event loop handler */
607         return 0;
608 }
609
610 static int client_initialize_events(sd_dhcp_client *client, usec_t usec)
611 {
612         int r;
613
614         r = sd_event_add_io(client->event, client->fd, EPOLLIN,
615                             client_receive_message, client,
616                             &client->receive_message);
617         if (r < 0)
618                 goto error;
619
620         r = sd_event_add_monotonic(client->event, usec, 0,
621                                    client_timeout_resend, client,
622                                    &client->timeout_resend);
623
624 error:
625         if (r < 0)
626                 client_stop(client, r);
627
628         return 0;
629
630 }
631
632 static int client_timeout_expire(sd_event_source *s, uint64_t usec,
633                                  void *userdata)
634 {
635         sd_dhcp_client *client = userdata;
636
637         client_stop(client, DHCP_EVENT_EXPIRED);
638
639         return 0;
640 }
641
642 static int client_timeout_t2(sd_event_source *s, uint64_t usec, void *userdata)
643 {
644         return 0;
645 }
646
647 static int client_timeout_t1(sd_event_source *s, uint64_t usec, void *userdata)
648 {
649         sd_dhcp_client *client = userdata;
650         int r;
651
652         client->state = DHCP_STATE_RENEWING;
653         client->attempt = 1;
654
655         r = dhcp_network_bind_udp_socket(client->index,
656                                          client->lease->address);
657         if (r < 0) {
658                 client_stop(client, r);
659                 return 0;
660         }
661
662         client->fd = r;
663
664         return client_initialize_events(client, usec);
665 }
666
667 static int client_parse_offer(uint8_t code, uint8_t len, const uint8_t *option,
668                               void *user_data)
669 {
670         DHCPLease *lease = user_data;
671         be32_t val;
672
673         switch(code) {
674
675         case DHCP_OPTION_IP_ADDRESS_LEASE_TIME:
676                 if (len == 4) {
677                         memcpy(&val, option, 4);
678                         lease->lifetime = be32toh(val);
679                 }
680
681                 break;
682
683         case DHCP_OPTION_SERVER_IDENTIFIER:
684                 if (len >= 4)
685                         memcpy(&lease->server_address, option, 4);
686
687                 break;
688
689         case DHCP_OPTION_SUBNET_MASK:
690                 if (len >= 4)
691                         memcpy(&lease->subnet_mask, option, 4);
692
693                 break;
694
695         case DHCP_OPTION_ROUTER:
696                 if (len >= 4)
697                         memcpy(&lease->router, option, 4);
698
699                 break;
700
701         case DHCP_OPTION_RENEWAL_T1_TIME:
702                 if (len == 4) {
703                         memcpy(&val, option, 4);
704                         lease->t1 = be32toh(val);
705                 }
706
707                 break;
708
709         case DHCP_OPTION_REBINDING_T2_TIME:
710                 if (len == 4) {
711                         memcpy(&val, option, 4);
712                         lease->t2 = be32toh(val);
713                 }
714
715                 break;
716         }
717
718         return 0;
719 }
720
721 static int client_verify_headers(sd_dhcp_client *client, DHCPPacket *message,
722                                  size_t len)
723 {
724         size_t hdrlen;
725
726         if (len < (DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE))
727                 return -EINVAL;
728
729         hdrlen = message->ip.ihl * 4;
730         if (hdrlen < 20 || hdrlen > len || client_checksum(&message->ip,
731                                                            hdrlen))
732                 return -EINVAL;
733
734         message->ip.check = message->udp.len;
735         message->ip.ttl = 0;
736
737         if (hdrlen + be16toh(message->udp.len) > len ||
738             client_checksum(&message->ip.ttl, be16toh(message->udp.len) + 12))
739                 return -EINVAL;
740
741         if (be16toh(message->udp.source) != DHCP_PORT_SERVER ||
742             be16toh(message->udp.dest) != DHCP_PORT_CLIENT)
743                 return -EINVAL;
744
745         if (message->dhcp.op != BOOTREPLY)
746                 return -EINVAL;
747
748         if (be32toh(message->dhcp.xid) != client->xid)
749                 return -EINVAL;
750
751         if (memcmp(&message->dhcp.chaddr[0], &client->mac_addr.ether_addr_octet,
752                     ETHER_ADDR_LEN))
753                 return -EINVAL;
754
755         return 0;
756 }
757
758 static int client_receive_offer(sd_dhcp_client *client, DHCPPacket *offer,
759                                 size_t len)
760 {
761         int err;
762         DHCPLease *lease;
763
764         err = client_verify_headers(client, offer, len);
765         if (err < 0)
766                 return err;
767
768         lease = new0(DHCPLease, 1);
769         if (!lease)
770                 return -ENOMEM;
771
772         len = len - DHCP_IP_UDP_SIZE;
773         if (dhcp_option_parse(&offer->dhcp, len, client_parse_offer,
774                               lease) != DHCP_OFFER)
775                 goto error;
776
777         lease->address = offer->dhcp.yiaddr;
778
779         if (lease->address == INADDR_ANY ||
780             lease->server_address == INADDR_ANY ||
781             lease->subnet_mask == INADDR_ANY ||
782             lease->lifetime == 0)
783                 goto error;
784
785         client->lease = lease;
786
787         return 0;
788
789 error:
790         free(lease);
791
792         return -ENOMSG;
793 }
794
795 static int client_receive_ack(sd_dhcp_client *client, const uint8_t *buf,
796                               size_t len)
797 {
798         int r;
799         DHCPPacket *ack;
800         DHCPMessage *dhcp;
801         DHCPLease *lease;
802
803         if (client->state == DHCP_STATE_RENEWING) {
804                 dhcp = (DHCPMessage *)buf;
805         } else {
806                 ack = (DHCPPacket *)buf;
807
808                 r = client_verify_headers(client, ack, len);
809                 if (r < 0)
810                         return r;
811
812                 dhcp = &ack->dhcp;
813                 len -= DHCP_IP_UDP_SIZE;
814         }
815
816         lease = new0(DHCPLease, 1);
817         if (!lease)
818                 return -ENOMEM;
819
820         r = dhcp_option_parse(dhcp, len, client_parse_offer, lease);
821
822         if (r == DHCP_NAK) {
823                 r = DHCP_EVENT_NO_LEASE;
824                 goto error;
825         }
826
827         if (r != DHCP_ACK) {
828                 r = -ENOMSG;
829                 goto error;
830         }
831
832         lease->address = dhcp->yiaddr;
833
834         if (lease->address == INADDR_ANY ||
835             lease->server_address == INADDR_ANY ||
836             lease->subnet_mask == INADDR_ANY || lease->lifetime == 0) {
837                 r = -ENOMSG;
838                 goto error;
839         }
840
841         r = DHCP_EVENT_IP_ACQUIRE;
842         if (client->lease) {
843                 if (client->lease->address != lease->address ||
844                     client->lease->subnet_mask != lease->subnet_mask ||
845                     client->lease->router != lease->router) {
846                         r = DHCP_EVENT_IP_CHANGE;
847                 }
848
849                 free(client->lease);
850         }
851
852         client->lease = lease;
853
854         return r;
855
856 error:
857         free(lease);
858
859         return r;
860 }
861
862 static uint64_t client_compute_timeout(uint64_t request_sent,
863                                        uint32_t lifetime)
864 {
865         return request_sent + (lifetime - 3) * USEC_PER_SEC +
866                 + (random_u() & 0x1fffff);
867 }
868
869 static int client_set_lease_timeouts(sd_dhcp_client *client, uint64_t usec)
870 {
871         int err;
872         uint64_t next_timeout;
873
874         if (client->lease->lifetime < 10)
875                 return -EINVAL;
876
877         client->timeout_t1 = sd_event_source_unref(client->timeout_t1);
878         client->timeout_t2 = sd_event_source_unref(client->timeout_t2);
879         client->timeout_expire = sd_event_source_unref(client->timeout_expire);
880
881         if (!client->lease->t1)
882                 client->lease->t1 = client->lease->lifetime / 2;
883
884         next_timeout = client_compute_timeout(client->request_sent,
885                                               client->lease->t1);
886         if (next_timeout < usec)
887                 return -EINVAL;
888
889         err = sd_event_add_monotonic(client->event, next_timeout,
890                                      10 * USEC_PER_MSEC,
891                                      client_timeout_t1, client,
892                                      &client->timeout_t1);
893         if (err < 0)
894                 return err;
895
896         if (!client->lease->t2)
897                 client->lease->t2 = client->lease->lifetime * 7 / 8;
898
899         if (client->lease->t2 < client->lease->t1)
900                 return -EINVAL;
901
902         if (client->lease->lifetime < client->lease->t2)
903                 return -EINVAL;
904
905         next_timeout = client_compute_timeout(client->request_sent,
906                                               client->lease->t2);
907         if (next_timeout < usec)
908                 return -EINVAL;
909
910         err = sd_event_add_monotonic(client->event, next_timeout,
911                                      10 * USEC_PER_MSEC,
912                                      client_timeout_t2, client,
913                                      &client->timeout_t2);
914         if (err < 0)
915                 return err;
916
917         next_timeout = client_compute_timeout(client->request_sent,
918                                               client->lease->lifetime);
919         if (next_timeout < usec)
920                 return -EINVAL;
921
922         err = sd_event_add_monotonic(client->event, next_timeout,
923                                      10 * USEC_PER_MSEC,
924                                      client_timeout_expire, client,
925                                      &client->timeout_expire);
926         if (err < 0)
927                 return err;
928
929         return 0;
930 }
931
932 static int client_receive_message(sd_event_source *s, int fd,
933                                   uint32_t revents, void *userdata)
934 {
935         sd_dhcp_client *client = userdata;
936         uint8_t buf[sizeof(DHCPPacket) + DHCP_CLIENT_MIN_OPTIONS_SIZE];
937         int buflen = sizeof(buf);
938         int len, r = 0, notify_event = 0;
939         DHCPPacket *message;
940         usec_t time_now;
941
942         len = read(fd, &buf, buflen);
943         if (len < 0)
944                 return 0;
945
946         r = sd_event_get_now_monotonic(client->event, &time_now);
947         if (r < 0)
948                 goto error;
949
950         switch (client->state) {
951         case DHCP_STATE_SELECTING:
952
953                 message = (DHCPPacket *)&buf;
954
955                 if (client_receive_offer(client, message, len) >= 0) {
956
957                         client->timeout_resend =
958                                 sd_event_source_unref(client->timeout_resend);
959
960                         client->state = DHCP_STATE_REQUESTING;
961                         client->attempt = 1;
962
963                         r = sd_event_add_monotonic(client->event, time_now, 0,
964                                                    client_timeout_resend,
965                                                    client,
966                                                    &client->timeout_resend);
967                         if (r < 0)
968                                 goto error;
969                 }
970
971                 break;
972
973         case DHCP_STATE_REQUESTING:
974         case DHCP_STATE_RENEWING:
975
976                 r = client_receive_ack(client, buf, len);
977
978                 if (r == DHCP_EVENT_NO_LEASE)
979                         goto error;
980
981                 if (r >= 0) {
982                         client->timeout_resend =
983                                 sd_event_source_unref(client->timeout_resend);
984
985                         if (client->state == DHCP_STATE_REQUESTING)
986                                 notify_event = DHCP_EVENT_IP_ACQUIRE;
987                         else if (r != DHCP_EVENT_IP_ACQUIRE)
988                                 notify_event = r;
989
990                         client->state = DHCP_STATE_BOUND;
991                         client->attempt = 1;
992
993                         client->last_addr = client->lease->address;
994
995                         r = client_set_lease_timeouts(client, time_now);
996                         if (r < 0)
997                                 goto error;
998
999                         if (notify_event)
1000                                 client_notify(client, notify_event);
1001
1002                         client->receive_message =
1003                                 sd_event_source_unref(client->receive_message);
1004                         close(client->fd);
1005                         client->fd = -1;
1006                 }
1007
1008                 r = 0;
1009
1010                 break;
1011
1012         case DHCP_STATE_INIT:
1013         case DHCP_STATE_INIT_REBOOT:
1014         case DHCP_STATE_REBOOTING:
1015         case DHCP_STATE_BOUND:
1016         case DHCP_STATE_REBINDING:
1017
1018                 break;
1019         }
1020
1021 error:
1022         if (r < 0 || r == DHCP_EVENT_NO_LEASE)
1023                 return client_stop(client, r);
1024
1025         return 0;
1026 }
1027
1028 int sd_dhcp_client_start(sd_dhcp_client *client)
1029 {
1030         int r;
1031
1032         assert_return(client, -EINVAL);
1033         assert_return(client->index >= 0, -EINVAL);
1034         assert_return(client->state == DHCP_STATE_INIT ||
1035                       client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);
1036
1037         client->xid = random_u();
1038
1039         r = dhcp_network_bind_raw_socket(client->index, &client->link);
1040
1041         if (r < 0) {
1042                 client_stop(client, r);
1043                 return r;
1044         }
1045
1046         client->fd = r;
1047         client->start_time = now(CLOCK_MONOTONIC);
1048
1049         return client_initialize_events(client, client->start_time);
1050 }
1051
1052 int sd_dhcp_client_stop(sd_dhcp_client *client)
1053 {
1054         return client_stop(client, DHCP_EVENT_STOP);
1055 }
1056
1057 sd_dhcp_client *sd_dhcp_client_free(sd_dhcp_client *client)
1058 {
1059         assert_return(client, NULL);
1060
1061         sd_dhcp_client_stop(client);
1062
1063         sd_event_unref(client->event);
1064         free(client->req_opts);
1065         free(client);
1066
1067         return NULL;
1068 }
1069
1070 sd_dhcp_client *sd_dhcp_client_new(sd_event *event)
1071 {
1072         sd_dhcp_client *client;
1073
1074         assert_return(event, NULL);
1075
1076         client = new0(sd_dhcp_client, 1);
1077         if (!client)
1078                 return NULL;
1079
1080         client->event = sd_event_ref(event);
1081         client->state = DHCP_STATE_INIT;
1082         client->index = -1;
1083         client->fd = -1;
1084         client->attempt = 1;
1085
1086         client->req_opts_size = ELEMENTSOF(default_req_opts);
1087
1088         client->req_opts = memdup(default_req_opts, client->req_opts_size);
1089         if (!client->req_opts) {
1090                 free(client);
1091                 return NULL;
1092         }
1093
1094         return client;
1095 }