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