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