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