chiark / gitweb /
68a7328348b700a0c29dbe04de40588006d9e8e5
[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
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_u() & 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_u() & 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_u();
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 }