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