chiark / gitweb /
e690f6785ff3fabcd6390ab1ab1625d035179d34
[elogind.git] / src / libsystemd-network / 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 <net/if_arp.h>
26 #include <sys/param.h>
27 #include <sys/ioctl.h>
28
29 #include "util.h"
30 #include "list.h"
31 #include "refcnt.h"
32
33 #include "dhcp-protocol.h"
34 #include "dhcp-internal.h"
35 #include "dhcp-lease-internal.h"
36 #include "sd-dhcp-client.h"
37
38 struct sd_dhcp_client {
39         RefCount n_ref;
40
41         DHCPState state;
42         sd_event *event;
43         int event_priority;
44         sd_event_source *timeout_resend;
45         int index;
46         int fd;
47         union sockaddr_union link;
48         sd_event_source *receive_message;
49         uint8_t *req_opts;
50         size_t req_opts_allocated;
51         size_t req_opts_size;
52         be32_t last_addr;
53         struct {
54                 uint8_t type;
55                 struct ether_addr mac_addr;
56         } _packed_ client_id;
57         uint32_t xid;
58         usec_t start_time;
59         uint16_t secs;
60         unsigned int attempt;
61         usec_t request_sent;
62         sd_event_source *timeout_t1;
63         sd_event_source *timeout_t2;
64         sd_event_source *timeout_expire;
65         sd_dhcp_client_cb_t cb;
66         void *userdata;
67         sd_dhcp_lease *lease;
68 };
69
70 static const uint8_t default_req_opts[] = {
71         DHCP_OPTION_SUBNET_MASK,
72         DHCP_OPTION_ROUTER,
73         DHCP_OPTION_HOST_NAME,
74         DHCP_OPTION_DOMAIN_NAME,
75         DHCP_OPTION_DOMAIN_NAME_SERVER,
76         DHCP_OPTION_NTP_SERVER,
77 };
78
79 static int client_receive_message_raw(sd_event_source *s, int fd,
80                                       uint32_t revents, void *userdata);
81 static int client_receive_message_udp(sd_event_source *s, int fd,
82                                       uint32_t revents, void *userdata);
83 static sd_dhcp_client *client_stop(sd_dhcp_client *client, int error);
84
85 int sd_dhcp_client_set_callback(sd_dhcp_client *client, sd_dhcp_client_cb_t cb,
86                                 void *userdata) {
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         size_t i;
97
98         assert_return(client, -EINVAL);
99         assert_return (IN_SET(client->state, DHCP_STATE_INIT,
100                               DHCP_STATE_STOPPED), -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_allocated,
119                             client->req_opts_size + 1))
120                 return -ENOMEM;
121
122         client->req_opts[client->req_opts_size++] = 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         assert_return(client, -EINVAL);
130         assert_return (IN_SET(client->state, DHCP_STATE_INIT,
131                               DHCP_STATE_STOPPED), -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         assert_return(client, -EINVAL);
143         assert_return (IN_SET(client->state, DHCP_STATE_INIT,
144                               DHCP_STATE_STOPPED), -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         bool need_restart = false;
155
156         assert_return(client, -EINVAL);
157         assert_return(addr, -EINVAL);
158
159         if (memcmp(&client->client_id.mac_addr, addr, ETH_ALEN) == 0)
160                 return 0;
161
162         if (!IN_SET(client->state, DHCP_STATE_INIT, DHCP_STATE_STOPPED)) {
163                 log_dhcp_client(client, "Changing MAC address on running DHCP "
164                                 "client, restarting");
165                 need_restart = true;
166                 client = client_stop(client, DHCP_EVENT_STOP);
167         }
168
169         if (!client)
170                 return 0;
171
172         memcpy(&client->client_id.mac_addr, addr, ETH_ALEN);
173         client->client_id.type = 0x01;
174
175         if (need_restart && client->state != DHCP_STATE_STOPPED)
176                 sd_dhcp_client_start(client);
177
178         return 0;
179 }
180
181 int sd_dhcp_client_get_lease(sd_dhcp_client *client, sd_dhcp_lease **ret) {
182         assert_return(client, -EINVAL);
183         assert_return(ret, -EINVAL);
184
185         if (client->state != DHCP_STATE_BOUND &&
186             client->state != DHCP_STATE_RENEWING &&
187             client->state != DHCP_STATE_REBINDING)
188                 return -EADDRNOTAVAIL;
189
190         *ret = sd_dhcp_lease_ref(client->lease);
191
192         return 0;
193 }
194
195 static sd_dhcp_client *client_notify(sd_dhcp_client *client, int event) {
196         if (client->cb) {
197                 client = sd_dhcp_client_ref(client);
198                 client->cb(client, event, client->userdata);
199                 client = sd_dhcp_client_unref(client);
200         }
201
202         return client;
203 }
204
205 static int client_initialize(sd_dhcp_client *client) {
206         assert_return(client, -EINVAL);
207
208         client->receive_message =
209                 sd_event_source_unref(client->receive_message);
210
211         client->fd = safe_close(client->fd);
212
213         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
214
215         client->timeout_t1 = sd_event_source_unref(client->timeout_t1);
216         client->timeout_t2 = sd_event_source_unref(client->timeout_t2);
217         client->timeout_expire = sd_event_source_unref(client->timeout_expire);
218
219         client->attempt = 1;
220
221         client->state = DHCP_STATE_INIT;
222         client->xid = 0;
223
224         if (client->lease)
225                 client->lease = sd_dhcp_lease_unref(client->lease);
226
227         return 0;
228 }
229
230 static sd_dhcp_client *client_stop(sd_dhcp_client *client, int error) {
231         assert_return(client, NULL);
232
233         log_dhcp_client(client, "STOPPED %d", error);
234
235         client = client_notify(client, error);
236
237         if (client)
238                 client_initialize(client);
239
240         return client;
241 }
242
243 static int client_message_init(sd_dhcp_client *client, DHCPMessage *message,
244                                uint8_t type, uint8_t **opt, size_t *optlen) {
245         be16_t max_size;
246         int r;
247
248         assert(client);
249         assert(client->secs);
250         assert(message);
251         assert(opt);
252         assert(optlen);
253         assert(type == DHCP_DISCOVER || type == DHCP_REQUEST);
254
255         r = dhcp_message_init(message, BOOTREQUEST, client->xid, type, opt,
256                               optlen);
257         if (r < 0)
258                 return r;
259
260         /* Although 'secs' field is a SHOULD in RFC 2131, certain DHCP servers
261            refuse to issue an DHCP lease if 'secs' is set to zero */
262         message->secs = htobe16(client->secs);
263
264         memcpy(&message->chaddr, &client->client_id.mac_addr, ETH_ALEN);
265
266         if (client->state == DHCP_STATE_RENEWING ||
267             client->state == DHCP_STATE_REBINDING)
268                 message->ciaddr = client->lease->address;
269
270         /* Some DHCP servers will refuse to issue an DHCP lease if the Client
271            Identifier option is not set */
272         r = dhcp_option_append(opt, optlen, DHCP_OPTION_CLIENT_IDENTIFIER,
273                                sizeof(client->client_id), &client->client_id);
274         if (r < 0)
275                 return r;
276
277         r = dhcp_option_append(opt, optlen,
278                                DHCP_OPTION_PARAMETER_REQUEST_LIST,
279                                client->req_opts_size,
280                                client->req_opts);
281         if (r < 0)
282                 return r;
283
284         /* Some DHCP servers will send bigger DHCP packets than the
285            defined default size unless the Maximum Messge Size option
286            is explicitely set */
287         max_size = htobe16(DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE +
288                            DHCP_MIN_OPTIONS_SIZE);
289         r = dhcp_option_append(opt, optlen,
290                                DHCP_OPTION_MAXIMUM_MESSAGE_SIZE,
291                                2, &max_size);
292         if (r < 0)
293                 return r;
294
295         return 0;
296 }
297
298 static int dhcp_client_send_raw(sd_dhcp_client *client, DHCPPacket *packet,
299                                 size_t len) {
300         dhcp_packet_append_ip_headers(packet, INADDR_ANY, DHCP_PORT_CLIENT,
301                                       INADDR_BROADCAST, DHCP_PORT_SERVER, len);
302
303         return dhcp_network_send_raw_socket(client->fd, &client->link,
304                                             packet, len);
305 }
306
307 static int client_send_discover(sd_dhcp_client *client) {
308         _cleanup_free_ DHCPPacket *discover = NULL;
309         size_t optlen, len;
310         uint8_t *opt;
311         usec_t time_now;
312         int r;
313
314         assert(client);
315
316         r = sd_event_now(client->event, CLOCK_MONOTONIC, &time_now);
317         if (r < 0)
318                 return r;
319         assert(time_now >= client->start_time);
320
321         /* seconds between sending first and last DISCOVER
322          * must always be strictly positive to deal with broken servers */
323         client->secs = ((time_now - client->start_time) / USEC_PER_SEC) ? : 1;
324
325         optlen = DHCP_MIN_OPTIONS_SIZE;
326         len = sizeof(DHCPPacket) + optlen;
327
328         discover = malloc0(len);
329         if (!discover)
330                 return -ENOMEM;
331
332         r = client_message_init(client, &discover->dhcp, DHCP_DISCOVER,
333                                 &opt, &optlen);
334         if (r < 0)
335                 return r;
336
337         if (client->last_addr != INADDR_ANY) {
338                 r = dhcp_option_append(&opt, &optlen,
339                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
340                                          4, &client->last_addr);
341                 if (r < 0)
342                         return r;
343         }
344
345         r = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
346         if (r < 0)
347                 return r;
348
349         r = dhcp_client_send_raw(client, discover, len - optlen);
350         if (r < 0)
351                 return r;
352
353         log_dhcp_client(client, "DISCOVER");
354
355         return 0;
356 }
357
358 static int client_send_request(sd_dhcp_client *client) {
359         _cleanup_free_ DHCPPacket *request;
360         size_t optlen, len;
361         uint8_t *opt;
362         int r;
363
364         optlen = DHCP_MIN_OPTIONS_SIZE;
365         len = sizeof(DHCPPacket) + optlen;
366
367         request = malloc0(len);
368         if (!request)
369                 return -ENOMEM;
370
371         r = client_message_init(client, &request->dhcp, DHCP_REQUEST, &opt,
372                                 &optlen);
373         if (r < 0)
374                 return r;
375
376         switch (client->state) {
377
378         case DHCP_STATE_INIT_REBOOT:
379                 r = dhcp_option_append(&opt, &optlen,
380                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
381                                          4, &client->last_addr);
382                 if (r < 0)
383                         return r;
384                 break;
385
386         case DHCP_STATE_REQUESTING:
387                 r = dhcp_option_append(&opt, &optlen,
388                                        DHCP_OPTION_REQUESTED_IP_ADDRESS,
389                                        4, &client->lease->address);
390                 if (r < 0)
391                         return r;
392
393                 r = dhcp_option_append(&opt, &optlen,
394                                        DHCP_OPTION_SERVER_IDENTIFIER,
395                                        4, &client->lease->server_address);
396                 if (r < 0)
397                         return r;
398                 break;
399
400         case DHCP_STATE_INIT:
401         case DHCP_STATE_SELECTING:
402         case DHCP_STATE_REBOOTING:
403         case DHCP_STATE_BOUND:
404         case DHCP_STATE_RENEWING:
405         case DHCP_STATE_REBINDING:
406
407                 break;
408
409         case DHCP_STATE_STOPPED:
410                 return -EINVAL;
411         }
412
413         r = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
414         if (r < 0)
415                 return r;
416
417         if (client->state == DHCP_STATE_RENEWING) {
418                 r = dhcp_network_send_udp_socket(client->fd,
419                                                  client->lease->server_address,
420                                                  DHCP_PORT_SERVER,
421                                                  &request->dhcp,
422                                                  len - optlen - DHCP_IP_UDP_SIZE);
423         } else {
424                 r = dhcp_client_send_raw(client, request, len - optlen);
425         }
426         if (r < 0)
427                 return r;
428
429         log_dhcp_client(client, "REQUEST");
430
431         return 0;
432 }
433
434 static int client_timeout_resend(sd_event_source *s, uint64_t usec,
435                                  void *userdata) {
436         sd_dhcp_client *client = userdata;
437         usec_t next_timeout = 0;
438         uint64_t time_now;
439         uint32_t time_left;
440         int r;
441
442         assert(s);
443         assert(client);
444         assert(client->event);
445
446         r = sd_event_now(client->event, CLOCK_MONOTONIC, &time_now);
447         if (r < 0)
448                 goto error;
449
450         switch (client->state) {
451         case DHCP_STATE_RENEWING:
452
453                 time_left = (client->lease->t2 - client->lease->t1) / 2;
454                 if (time_left < 60)
455                         time_left = 60;
456
457                 next_timeout = time_now + time_left * USEC_PER_SEC;
458
459                 break;
460
461         case DHCP_STATE_REBINDING:
462
463                 time_left = (client->lease->lifetime - client->lease->t2) / 2;
464                 if (time_left < 60)
465                         time_left = 60;
466
467                 next_timeout = time_now + time_left * USEC_PER_SEC;
468                 break;
469
470         case DHCP_STATE_REBOOTING:
471                 /* start over as we did not receive a timely ack or nak */
472                 client->state = DHCP_STATE_INIT;
473                 client->attempt = 1;
474
475                 client->fd = safe_close(client->fd);
476                 client->xid = random_u32();
477                 r = dhcp_network_bind_raw_socket(client->index, &client->link, client->xid);
478                 if (r < 0)
479                         goto error;
480                 client->fd = r;
481
482                 /* fall through */
483         case DHCP_STATE_INIT:
484         case DHCP_STATE_INIT_REBOOT:
485         case DHCP_STATE_SELECTING:
486         case DHCP_STATE_REQUESTING:
487         case DHCP_STATE_BOUND:
488
489                 if (client->attempt < 64)
490                         client->attempt *= 2;
491
492                 next_timeout = time_now + (client->attempt - 1) * USEC_PER_SEC;
493
494                 break;
495
496         case DHCP_STATE_STOPPED:
497                 r = -EINVAL;
498                 goto error;
499         }
500
501         next_timeout += (random_u32() & 0x1fffff);
502
503         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
504
505         r = sd_event_add_time(client->event,
506                               &client->timeout_resend,
507                               CLOCK_MONOTONIC,
508                               next_timeout, 10 * USEC_PER_MSEC,
509                               client_timeout_resend, client);
510         if (r < 0)
511                 goto error;
512
513         r = sd_event_source_set_priority(client->timeout_resend,
514                                          client->event_priority);
515         if (r < 0)
516                 goto error;
517
518         switch (client->state) {
519         case DHCP_STATE_INIT:
520                 r = client_send_discover(client);
521                 if (r >= 0) {
522                         client->state = DHCP_STATE_SELECTING;
523                         client->attempt = 1;
524                 } else {
525                         if (client->attempt >= 64)
526                                 goto error;
527                 }
528
529                 break;
530
531         case DHCP_STATE_SELECTING:
532                 r = client_send_discover(client);
533                 if (r < 0 && client->attempt >= 64)
534                         goto error;
535
536                 break;
537
538         case DHCP_STATE_INIT_REBOOT:
539         case DHCP_STATE_REQUESTING:
540         case DHCP_STATE_RENEWING:
541         case DHCP_STATE_REBINDING:
542                 r = client_send_request(client);
543                 if (r < 0 && client->attempt >= 64)
544                          goto error;
545
546                 if (client->state == DHCP_STATE_INIT_REBOOT)
547                         client->state = DHCP_STATE_REBOOTING;
548
549                 client->request_sent = time_now;
550
551                 break;
552
553         case DHCP_STATE_REBOOTING:
554         case DHCP_STATE_BOUND:
555
556                 break;
557
558         case DHCP_STATE_STOPPED:
559                 r = -EINVAL;
560                 goto error;
561         }
562
563         return 0;
564
565 error:
566         client_stop(client, r);
567
568         /* Errors were dealt with when stopping the client, don't spill
569            errors into the event loop handler */
570         return 0;
571 }
572
573 static int client_initialize_events(sd_dhcp_client *client,
574                                     sd_event_io_handler_t io_callback) {
575         int r;
576
577         assert(client);
578         assert(client->event);
579
580         r = sd_event_add_io(client->event, &client->receive_message,
581                             client->fd, EPOLLIN, io_callback,
582                             client);
583         if (r < 0)
584                 goto error;
585
586         r = sd_event_source_set_priority(client->receive_message,
587                                          client->event_priority);
588         if (r < 0)
589                 goto error;
590
591         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
592
593         r = sd_event_add_time(client->event,
594                               &client->timeout_resend,
595                               CLOCK_MONOTONIC,
596                               0, 0,
597                               client_timeout_resend, client);
598         if (r < 0)
599                 goto error;
600
601         r = sd_event_source_set_priority(client->timeout_resend,
602                                          client->event_priority);
603
604 error:
605         if (r < 0)
606                 client_stop(client, r);
607
608         return 0;
609
610 }
611
612 static int client_start(sd_dhcp_client *client) {
613         int r;
614
615         assert_return(client, -EINVAL);
616         assert_return(client->event, -EINVAL);
617         assert_return(client->index > 0, -EINVAL);
618         assert_return(client->fd < 0, -EBUSY);
619         assert_return(client->xid == 0, -EINVAL);
620         assert_return(client->state == DHCP_STATE_INIT ||
621                       client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);
622
623         client->xid = random_u32();
624
625         r = dhcp_network_bind_raw_socket(client->index, &client->link, client->xid);
626
627         if (r < 0) {
628                 client_stop(client, r);
629                 return r;
630         }
631         client->fd = r;
632
633         if (client->state == DHCP_STATE_INIT) {
634                 client->start_time = now(CLOCK_MONOTONIC);
635                 client->secs = 0;
636         }
637
638         log_dhcp_client(client, "STARTED");
639
640         return client_initialize_events(client, client_receive_message_raw);
641 }
642
643 static int client_timeout_expire(sd_event_source *s, uint64_t usec,
644                                  void *userdata) {
645         sd_dhcp_client *client = userdata;
646
647         log_dhcp_client(client, "EXPIRED");
648
649         client = client_notify(client, DHCP_EVENT_EXPIRED);
650
651         /* lease was lost, start over if not freed or stopped in callback */
652         if (client && client->state != DHCP_STATE_STOPPED) {
653                 client_initialize(client);
654                 client_start(client);
655         }
656
657         return 0;
658 }
659
660 static int client_timeout_t2(sd_event_source *s, uint64_t usec, void *userdata) {
661         sd_dhcp_client *client = userdata;
662         int r;
663
664         client->receive_message = sd_event_source_unref(client->receive_message);
665         client->fd = safe_close(client->fd);
666
667         client->state = DHCP_STATE_REBINDING;
668         client->attempt = 1;
669
670         r = dhcp_network_bind_raw_socket(client->index, &client->link, client->xid);
671         if (r < 0) {
672                 client_stop(client, r);
673                 return 0;
674         }
675
676         client->fd = r;
677
678         log_dhcp_client(client, "TIMEOUT T2");
679
680         return client_initialize_events(client, client_receive_message_raw);
681 }
682
683 static int client_timeout_t1(sd_event_source *s, uint64_t usec,
684                              void *userdata) {
685         sd_dhcp_client *client = userdata;
686         int r;
687
688         client->state = DHCP_STATE_RENEWING;
689         client->attempt = 1;
690
691         r = dhcp_network_bind_udp_socket(client->index,
692                                          client->lease->address,
693                                          DHCP_PORT_CLIENT);
694         if (r < 0) {
695                 client_stop(client, r);
696                 return 0;
697         }
698
699         client->fd = r;
700
701         log_dhcp_client(client, "TIMEOUT T1");
702
703         return client_initialize_events(client, client_receive_message_udp);
704 }
705
706 static int client_handle_offer(sd_dhcp_client *client, DHCPMessage *offer,
707                                size_t len) {
708         _cleanup_dhcp_lease_unref_ sd_dhcp_lease *lease = NULL;
709         int r;
710
711         r = dhcp_lease_new(&lease);
712         if (r < 0)
713                 return r;
714
715         r = dhcp_option_parse(offer, len, dhcp_lease_parse_options, lease);
716         if (r != DHCP_OFFER) {
717                 log_dhcp_client(client, "receieved message was not an OFFER, ignoring");
718                 return -ENOMSG;
719         }
720
721         lease->next_server = offer->siaddr;
722
723         lease->address = offer->yiaddr;
724
725         if (lease->address == INADDR_ANY ||
726             lease->server_address == INADDR_ANY ||
727             lease->lifetime == 0) {
728                 log_dhcp_client(client, "receieved lease lacks address, server "
729                                 "address or lease lifetime, ignoring");
730                 return -ENOMSG;
731         }
732
733         if (lease->subnet_mask == INADDR_ANY) {
734                 r = dhcp_lease_set_default_subnet_mask(lease);
735                 if (r < 0) {
736                         log_dhcp_client(client, "receieved lease lacks subnet "
737                                         "mask, and a fallback one can not be "
738                                         "generated, ignoring");
739                         return -ENOMSG;
740                 }
741         }
742
743         client->lease = lease;
744         lease = NULL;
745
746         log_dhcp_client(client, "OFFER");
747
748         return 0;
749 }
750
751 static int client_handle_ack(sd_dhcp_client *client, DHCPMessage *ack,
752                              size_t len) {
753         _cleanup_dhcp_lease_unref_ sd_dhcp_lease *lease = NULL;
754         int r;
755
756         r = dhcp_lease_new(&lease);
757         if (r < 0)
758                 return r;
759
760         r = dhcp_option_parse(ack, len, dhcp_lease_parse_options, lease);
761         if (r == DHCP_NAK) {
762                 log_dhcp_client(client, "NAK");
763                 return DHCP_EVENT_NO_LEASE;
764         }
765
766         if (r != DHCP_ACK) {
767                 log_dhcp_client(client, "receieved message was not an ACK, ignoring");
768                 return -ENOMSG;
769         }
770
771         lease->next_server = ack->siaddr;
772
773         lease->address = ack->yiaddr;
774
775         if (lease->address == INADDR_ANY ||
776             lease->server_address == INADDR_ANY ||
777             lease->lifetime == 0) {
778                 log_dhcp_client(client, "receieved lease lacks address, server "
779                                 "address or lease lifetime, ignoring");
780                 return -ENOMSG;
781         }
782
783         if (lease->subnet_mask == INADDR_ANY) {
784                 r = dhcp_lease_set_default_subnet_mask(lease);
785                 if (r < 0) {
786                         log_dhcp_client(client, "receieved lease lacks subnet "
787                                         "mask, and a fallback one can not be "
788                                         "generated, ignoring");
789                         return -ENOMSG;
790                 }
791         }
792
793         r = DHCP_EVENT_IP_ACQUIRE;
794         if (client->lease) {
795                 if (client->lease->address != lease->address ||
796                     client->lease->subnet_mask != lease->subnet_mask ||
797                     client->lease->router != lease->router) {
798                         r = DHCP_EVENT_IP_CHANGE;
799                 }
800
801                 client->lease = sd_dhcp_lease_unref(client->lease);
802         }
803
804         client->lease = lease;
805         lease = NULL;
806
807         log_dhcp_client(client, "ACK");
808
809         return r;
810 }
811
812 static uint64_t client_compute_timeout(sd_dhcp_client *client,
813                                        uint32_t lifetime, double factor) {
814         assert(client);
815         assert(client->request_sent);
816         assert(lifetime);
817
818         return client->request_sent + ((lifetime - 3) * USEC_PER_SEC * factor) +
819                 + (random_u32() & 0x1fffff);
820 }
821
822 static int client_set_lease_timeouts(sd_dhcp_client *client) {
823         usec_t time_now;
824         uint64_t lifetime_timeout;
825         uint64_t t2_timeout;
826         uint64_t t1_timeout;
827         char time_string[FORMAT_TIMESPAN_MAX];
828         int r;
829
830         assert(client);
831         assert(client->event);
832         assert(client->lease);
833         assert(client->lease->lifetime);
834
835         client->timeout_t1 = sd_event_source_unref(client->timeout_t1);
836         client->timeout_t2 = sd_event_source_unref(client->timeout_t2);
837         client->timeout_expire = sd_event_source_unref(client->timeout_expire);
838
839         /* don't set timers for infinite leases */
840         if (client->lease->lifetime == 0xffffffff)
841                 return 0;
842
843         r = sd_event_now(client->event, CLOCK_MONOTONIC, &time_now);
844         if (r < 0)
845                 return r;
846         assert(client->request_sent <= time_now);
847
848         /* convert the various timeouts from relative (secs) to absolute (usecs) */
849         lifetime_timeout = client_compute_timeout(client, client->lease->lifetime, 1);
850         if (client->lease->t1 && client->lease->t2) {
851                 /* both T1 and T2 are given */
852                 if (client->lease->t1 < client->lease->t2 &&
853                     client->lease->t2 < client->lease->lifetime) {
854                         /* they are both valid */
855                         t2_timeout = client_compute_timeout(client, client->lease->t2, 1);
856                         t1_timeout = client_compute_timeout(client, client->lease->t1, 1);
857                 } else {
858                         /* discard both */
859                         t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
860                         client->lease->t2 = (client->lease->lifetime * 7) / 8;
861                         t1_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
862                         client->lease->t1 = client->lease->lifetime / 2;
863                 }
864         } else if (client->lease->t2 && client->lease->t2 < client->lease->lifetime) {
865                 /* only T2 is given, and it is valid */
866                 t2_timeout = client_compute_timeout(client, client->lease->t2, 1);
867                 t1_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
868                 client->lease->t1 = client->lease->lifetime / 2;
869                 if (t2_timeout <= t1_timeout) {
870                         /* the computed T1 would be invalid, so discard T2 */
871                         t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
872                         client->lease->t2 = (client->lease->lifetime * 7) / 8;
873                 }
874         } else if (client->lease->t1 && client->lease->t1 < client->lease->lifetime) {
875                 /* only T1 is given, and it is valid */
876                 t1_timeout = client_compute_timeout(client, client->lease->t1, 1);
877                 t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
878                 client->lease->t2 = (client->lease->lifetime * 7) / 8;
879                 if (t2_timeout <= t1_timeout) {
880                         /* the computed T2 would be invalid, so discard T1 */
881                         t2_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
882                         client->lease->t2 = client->lease->lifetime / 2;
883                 }
884         } else {
885                 /* fall back to the default timeouts */
886                 t1_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
887                 client->lease->t1 = client->lease->lifetime / 2;
888                 t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
889                 client->lease->t2 = (client->lease->lifetime * 7) / 8;
890         }
891
892         /* arm lifetime timeout */
893         r = sd_event_add_time(client->event, &client->timeout_expire,
894                               CLOCK_MONOTONIC,
895                               lifetime_timeout, 10 * USEC_PER_MSEC,
896                               client_timeout_expire, client);
897         if (r < 0)
898                 return r;
899
900         r = sd_event_source_set_priority(client->timeout_expire,
901                                          client->event_priority);
902         if (r < 0)
903                 return r;
904
905         log_dhcp_client(client, "lease expires in %s",
906                         format_timespan(time_string, FORMAT_TIMESPAN_MAX,
907                         lifetime_timeout - time_now, 0));
908
909         /* don't arm earlier timeouts if this has already expired */
910         if (lifetime_timeout <= time_now)
911                 return 0;
912
913         /* arm T2 timeout */
914         r = sd_event_add_time(client->event,
915                               &client->timeout_t2,
916                               CLOCK_MONOTONIC,
917                               t2_timeout,
918                               10 * USEC_PER_MSEC,
919                               client_timeout_t2, client);
920         if (r < 0)
921                 return r;
922
923         r = sd_event_source_set_priority(client->timeout_t2,
924                                          client->event_priority);
925         if (r < 0)
926                 return r;
927
928         log_dhcp_client(client, "T2 expires in %s",
929                         format_timespan(time_string, FORMAT_TIMESPAN_MAX,
930                         t2_timeout - time_now, 0));
931
932         /* don't arm earlier timeout if this has already expired */
933         if (t2_timeout <= time_now)
934                 return 0;
935
936         /* arm T1 timeout */
937         r = sd_event_add_time(client->event,
938                               &client->timeout_t1,
939                               CLOCK_MONOTONIC,
940                               t1_timeout, 10 * USEC_PER_MSEC,
941                               client_timeout_t1, client);
942         if (r < 0)
943                 return r;
944
945         r = sd_event_source_set_priority(client->timeout_t1,
946                                          client->event_priority);
947         if (r < 0)
948                 return r;
949
950         log_dhcp_client(client, "T1 expires in %s",
951                         format_timespan(time_string, FORMAT_TIMESPAN_MAX,
952                         t1_timeout - time_now, 0));
953
954         return 0;
955 }
956
957 static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message,
958                                  int len) {
959         int r = 0, notify_event = 0;
960
961         assert(client);
962         assert(client->event);
963         assert(message);
964
965         if (be32toh(message->magic) != DHCP_MAGIC_COOKIE) {
966                 log_dhcp_client(client, "not a DHCP message: ignoring");
967                 return 0;
968         }
969
970         if (message->op != BOOTREPLY) {
971                 log_dhcp_client(client, "not a BOOTREPLY message: ignoring");
972                 return 0;
973         }
974
975         if (be32toh(message->xid) != client->xid) {
976                 log_dhcp_client(client, "received xid (%u) does not match "
977                                 "expected (%u): ignoring",
978                                 be32toh(message->xid), client->xid);
979                 return 0;
980         }
981
982         if (message->htype != ARPHRD_ETHER || message->hlen != ETHER_ADDR_LEN) {
983                 log_dhcp_client(client, "not an ethernet packet");
984                 return 0;
985         }
986
987         if (memcmp(&message->chaddr[0], &client->client_id.mac_addr,
988                    ETH_ALEN)) {
989                 log_dhcp_client(client, "received chaddr does not match "
990                                 "expected: ignoring");
991                 return 0;
992         }
993
994         switch (client->state) {
995         case DHCP_STATE_SELECTING:
996
997                 r = client_handle_offer(client, message, len);
998                 if (r >= 0) {
999
1000                         client->timeout_resend =
1001                                 sd_event_source_unref(client->timeout_resend);
1002
1003                         client->state = DHCP_STATE_REQUESTING;
1004                         client->attempt = 1;
1005
1006                         r = sd_event_add_time(client->event,
1007                                               &client->timeout_resend,
1008                                               CLOCK_MONOTONIC,
1009                                               0, 0,
1010                                               client_timeout_resend, client);
1011                         if (r < 0)
1012                                 goto error;
1013
1014                         r = sd_event_source_set_priority(client->timeout_resend,
1015                                                          client->event_priority);
1016                         if (r < 0)
1017                                 goto error;
1018                 } else if (r == -ENOMSG)
1019                         /* invalid message, let's ignore it */
1020                         return 0;
1021
1022                 break;
1023
1024         case DHCP_STATE_REBOOTING:
1025         case DHCP_STATE_REQUESTING:
1026         case DHCP_STATE_RENEWING:
1027         case DHCP_STATE_REBINDING:
1028
1029                 r = client_handle_ack(client, message, len);
1030                 if (r == DHCP_EVENT_NO_LEASE) {
1031
1032                         client->timeout_resend =
1033                                 sd_event_source_unref(client->timeout_resend);
1034
1035                         if (client->state == DHCP_STATE_REBOOTING) {
1036                                 r = client_initialize(client);
1037                                 if (r < 0)
1038                                         goto error;
1039
1040                                 r = client_start(client);
1041                                 if (r < 0)
1042                                         goto error;
1043                         }
1044
1045                         goto error;
1046                 } else if (r >= 0) {
1047                         client->timeout_resend =
1048                                 sd_event_source_unref(client->timeout_resend);
1049
1050                         if (IN_SET(client->state, DHCP_STATE_REQUESTING,
1051                                    DHCP_STATE_REBOOTING))
1052                                 notify_event = DHCP_EVENT_IP_ACQUIRE;
1053                         else if (r != DHCP_EVENT_IP_ACQUIRE)
1054                                 notify_event = r;
1055
1056                         client->state = DHCP_STATE_BOUND;
1057                         client->attempt = 1;
1058
1059                         client->last_addr = client->lease->address;
1060
1061                         r = client_set_lease_timeouts(client);
1062                         if (r < 0)
1063                                 goto error;
1064
1065                         if (notify_event) {
1066                                 client = client_notify(client, notify_event);
1067                                 if (!client ||
1068                                     client->state == DHCP_STATE_STOPPED)
1069                                         return 0;
1070                         }
1071
1072                         client->receive_message =
1073                                 sd_event_source_unref(client->receive_message);
1074                         client->fd = safe_close(client->fd);
1075                 } else if (r == -ENOMSG)
1076                         /* invalid message, let's ignore it */
1077                         return 0;
1078
1079                 break;
1080
1081         case DHCP_STATE_INIT:
1082         case DHCP_STATE_INIT_REBOOT:
1083         case DHCP_STATE_BOUND:
1084
1085                 break;
1086
1087         case DHCP_STATE_STOPPED:
1088                 r = -EINVAL;
1089                 goto error;
1090         }
1091
1092 error:
1093         if (r < 0 || r == DHCP_EVENT_NO_LEASE)
1094                 client_stop(client, r);
1095
1096         return r;
1097 }
1098
1099 static int client_receive_message_udp(sd_event_source *s, int fd,
1100                                       uint32_t revents, void *userdata) {
1101         sd_dhcp_client *client = userdata;
1102         _cleanup_free_ DHCPMessage *message = NULL;
1103         int buflen = 0, len, r;
1104
1105         assert(s);
1106         assert(client);
1107
1108         r = ioctl(fd, FIONREAD, &buflen);
1109         if (r < 0 || buflen <= 0)
1110                 buflen = sizeof(DHCPMessage) + DHCP_MIN_OPTIONS_SIZE;
1111
1112         message = malloc0(buflen);
1113         if (!message)
1114                 return -ENOMEM;
1115
1116         len = read(fd, message, buflen);
1117         if (len < 0) {
1118                 log_dhcp_client(client, "could not receive message from UDP "
1119                                 "socket: %s", strerror(errno));
1120                 return 0;
1121         } else if ((size_t)len < sizeof(DHCPMessage))
1122                 return 0;
1123
1124         return client_handle_message(client, message, len);
1125 }
1126
1127 static int client_receive_message_raw(sd_event_source *s, int fd,
1128                                       uint32_t revents, void *userdata) {
1129         sd_dhcp_client *client = userdata;
1130         _cleanup_free_ DHCPPacket *packet = NULL;
1131         uint8_t cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))];
1132         struct iovec iov = {};
1133         struct msghdr msg = {
1134                 .msg_iov = &iov,
1135                 .msg_iovlen = 1,
1136                 .msg_control = cmsgbuf,
1137                 .msg_controllen = sizeof(cmsgbuf),
1138         };
1139         struct cmsghdr *cmsg;
1140         bool checksum = true;
1141         int buflen = 0, len, r;
1142
1143         assert(s);
1144         assert(client);
1145
1146         r = ioctl(fd, FIONREAD, &buflen);
1147         if (r < 0 || buflen <= 0)
1148                 buflen = sizeof(DHCPPacket) + DHCP_MIN_OPTIONS_SIZE;
1149
1150         packet = malloc0(buflen);
1151         if (!packet)
1152                 return -ENOMEM;
1153
1154         iov.iov_base = packet;
1155         iov.iov_len = buflen;
1156
1157         len = recvmsg(fd, &msg, 0);
1158         if (len < 0) {
1159                 log_dhcp_client(client, "could not receive message from raw "
1160                                 "socket: %s", strerror(errno));
1161                 return 0;
1162         } else if ((size_t)len < sizeof(DHCPPacket))
1163                 return 0;
1164
1165         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1166                 if (cmsg->cmsg_level == SOL_PACKET &&
1167                     cmsg->cmsg_type == PACKET_AUXDATA &&
1168                     cmsg->cmsg_len == CMSG_LEN(sizeof(struct tpacket_auxdata))) {
1169                         struct tpacket_auxdata *aux = (struct tpacket_auxdata*)CMSG_DATA(cmsg);
1170
1171                         checksum = !(aux->tp_status & TP_STATUS_CSUMNOTREADY);
1172                         break;
1173                 }
1174         }
1175
1176         r = dhcp_packet_verify_headers(packet, len, checksum);
1177         if (r < 0)
1178                 return 0;
1179
1180         len -= DHCP_IP_UDP_SIZE;
1181
1182         return client_handle_message(client, &packet->dhcp, len);
1183 }
1184
1185 int sd_dhcp_client_start(sd_dhcp_client *client) {
1186         int r;
1187
1188         assert_return(client, -EINVAL);
1189
1190         r = client_initialize(client);
1191         if (r < 0)
1192                 return r;
1193
1194         if (client->last_addr)
1195                 client->state = DHCP_STATE_INIT_REBOOT;
1196
1197         return client_start(client);
1198 }
1199
1200 int sd_dhcp_client_stop(sd_dhcp_client *client) {
1201         assert_return(client, -EINVAL);
1202
1203         if (client_stop(client, DHCP_EVENT_STOP))
1204                 client->state = DHCP_STATE_STOPPED;
1205
1206         return 0;
1207 }
1208
1209 int sd_dhcp_client_attach_event(sd_dhcp_client *client, sd_event *event,
1210                                 int priority) {
1211         int r;
1212
1213         assert_return(client, -EINVAL);
1214         assert_return(!client->event, -EBUSY);
1215
1216         if (event)
1217                 client->event = sd_event_ref(event);
1218         else {
1219                 r = sd_event_default(&client->event);
1220                 if (r < 0)
1221                         return 0;
1222         }
1223
1224         client->event_priority = priority;
1225
1226         return 0;
1227 }
1228
1229 int sd_dhcp_client_detach_event(sd_dhcp_client *client) {
1230         assert_return(client, -EINVAL);
1231
1232         client->event = sd_event_unref(client->event);
1233
1234         return 0;
1235 }
1236
1237 sd_event *sd_dhcp_client_get_event(sd_dhcp_client *client) {
1238         if (!client)
1239                 return NULL;
1240
1241         return client->event;
1242 }
1243
1244 sd_dhcp_client *sd_dhcp_client_ref(sd_dhcp_client *client) {
1245         if (client)
1246                 assert_se(REFCNT_INC(client->n_ref) >= 2);
1247
1248         return client;
1249 }
1250
1251 sd_dhcp_client *sd_dhcp_client_unref(sd_dhcp_client *client) {
1252         if (client && REFCNT_DEC(client->n_ref) <= 0) {
1253                 log_dhcp_client(client, "UNREF");
1254
1255                 client_initialize(client);
1256
1257                 client->receive_message =
1258                         sd_event_source_unref(client->receive_message);
1259
1260                 sd_dhcp_client_detach_event(client);
1261
1262                 free(client->req_opts);
1263                 free(client);
1264
1265                 return NULL;
1266         }
1267
1268         return client;
1269 }
1270
1271 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_dhcp_client*, sd_dhcp_client_unref);
1272 #define _cleanup_dhcp_client_free_ _cleanup_(sd_dhcp_client_unrefp)
1273
1274 int sd_dhcp_client_new(sd_dhcp_client **ret) {
1275         _cleanup_dhcp_client_free_ sd_dhcp_client *client = NULL;
1276
1277         assert_return(ret, -EINVAL);
1278
1279         client = new0(sd_dhcp_client, 1);
1280         if (!client)
1281                 return -ENOMEM;
1282
1283         client->n_ref = REFCNT_INIT;
1284         client->state = DHCP_STATE_INIT;
1285         client->index = -1;
1286         client->fd = -1;
1287         client->attempt = 1;
1288
1289         client->req_opts_size = ELEMENTSOF(default_req_opts);
1290
1291         client->req_opts = memdup(default_req_opts, client->req_opts_size);
1292         if (!client->req_opts)
1293                 return -ENOMEM;
1294
1295         *ret = client;
1296         client = NULL;
1297
1298         return 0;
1299 }