chiark / gitweb /
sd-dhcp-client/sd-ipv4ll: allow mac address to be updated at any time
[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_get_now_monotonic(client->event, &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_get_now_monotonic(client->event, &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_monotonic(client->event,
480                                      &client->timeout_resend,
481                                      next_timeout,
482                                      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_monotonic(client->event,
564                                    &client->timeout_resend, 0, 0,
565                                    client_timeout_resend, client);
566         if (r < 0)
567                 goto error;
568
569         r = sd_event_source_set_priority(client->timeout_resend,
570                                          client->event_priority);
571
572 error:
573         if (r < 0)
574                 client_stop(client, r);
575
576         return 0;
577
578 }
579
580 static int client_start(sd_dhcp_client *client) {
581         int r;
582
583         assert_return(client, -EINVAL);
584         assert_return(client->event, -EINVAL);
585         assert_return(client->index > 0, -EINVAL);
586         assert_return(client->fd < 0, -EBUSY);
587         assert_return(client->xid == 0, -EINVAL);
588         assert_return(client->state == DHCP_STATE_INIT ||
589                       client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);
590
591         client->xid = random_u32();
592
593         r = dhcp_network_bind_raw_socket(client->index, &client->link);
594
595         if (r < 0) {
596                 client_stop(client, r);
597                 return r;
598         }
599         client->fd = r;
600
601         if (client->state == DHCP_STATE_INIT) {
602                 client->start_time = now(CLOCK_MONOTONIC);
603                 client->secs = 0;
604         }
605
606         log_dhcp_client(client, "STARTED");
607
608         return client_initialize_events(client, client_receive_message_raw);
609 }
610
611 static int client_timeout_expire(sd_event_source *s, uint64_t usec,
612                                  void *userdata) {
613         sd_dhcp_client *client = userdata;
614
615         log_dhcp_client(client, "EXPIRED");
616
617         client_notify(client, DHCP_EVENT_EXPIRED);
618
619         /* start over as the lease was lost */
620         client_initialize(client);
621         client_start(client);
622
623         return 0;
624 }
625
626 static int client_timeout_t2(sd_event_source *s, uint64_t usec, void *userdata) {
627         sd_dhcp_client *client = userdata;
628         int r;
629
630         client->receive_message = sd_event_source_unref(client->receive_message);
631         client->fd = safe_close(client->fd);
632
633         client->state = DHCP_STATE_REBINDING;
634         client->attempt = 1;
635
636         r = dhcp_network_bind_raw_socket(client->index, &client->link);
637         if (r < 0) {
638                 client_stop(client, r);
639                 return 0;
640         }
641
642         client->fd = r;
643
644         log_dhcp_client(client, "TIMEOUT T2");
645
646         return client_initialize_events(client, client_receive_message_raw);
647 }
648
649 static int client_timeout_t1(sd_event_source *s, uint64_t usec,
650                              void *userdata) {
651         sd_dhcp_client *client = userdata;
652         int r;
653
654         client->state = DHCP_STATE_RENEWING;
655         client->attempt = 1;
656
657         r = dhcp_network_bind_udp_socket(client->index,
658                                          client->lease->address,
659                                          DHCP_PORT_CLIENT);
660         if (r < 0) {
661                 client_stop(client, r);
662                 return 0;
663         }
664
665         client->fd = r;
666
667         log_dhcp_client(client, "TIMEOUT T1");
668
669         return client_initialize_events(client, client_receive_message_udp);
670 }
671
672 static int client_handle_offer(sd_dhcp_client *client, DHCPMessage *offer,
673                                size_t len) {
674         _cleanup_dhcp_lease_unref_ sd_dhcp_lease *lease = NULL;
675         int r;
676
677         r = dhcp_lease_new(&lease);
678         if (r < 0)
679                 return r;
680
681         r = dhcp_option_parse(offer, len, dhcp_lease_parse_options, lease);
682         if (r != DHCP_OFFER) {
683                 log_dhcp_client(client, "receieved message was not an OFFER, ignoring");
684                 return -ENOMSG;
685         }
686
687         lease->next_server = offer->siaddr;
688
689         lease->address = offer->yiaddr;
690
691         if (lease->address == INADDR_ANY ||
692             lease->server_address == INADDR_ANY ||
693             lease->lifetime == 0) {
694                 log_dhcp_client(client, "receieved lease lacks address, server "
695                                 "address or lease lifetime, ignoring");
696                 return -ENOMSG;
697         }
698
699         if (lease->subnet_mask == INADDR_ANY) {
700                 r = dhcp_lease_set_default_subnet_mask(lease);
701                 if (r < 0) {
702                         log_dhcp_client(client, "receieved lease lacks subnet "
703                                         "mask, and a fallback one can not be "
704                                         "generated, ignoring");
705                         return -ENOMSG;
706                 }
707         }
708
709         client->lease = lease;
710         lease = NULL;
711
712         log_dhcp_client(client, "OFFER");
713
714         return 0;
715 }
716
717 static int client_handle_ack(sd_dhcp_client *client, DHCPMessage *ack,
718                              size_t len) {
719         _cleanup_dhcp_lease_unref_ sd_dhcp_lease *lease = NULL;
720         int r;
721
722         r = dhcp_lease_new(&lease);
723         if (r < 0)
724                 return r;
725
726         r = dhcp_option_parse(ack, len, dhcp_lease_parse_options, lease);
727         if (r == DHCP_NAK) {
728                 log_dhcp_client(client, "NAK");
729                 return DHCP_EVENT_NO_LEASE;
730         }
731
732         if (r != DHCP_ACK) {
733                 log_dhcp_client(client, "receieved message was not an ACK, ignoring");
734                 return -ENOMSG;
735         }
736
737         lease->next_server = ack->siaddr;
738
739         lease->address = ack->yiaddr;
740
741         if (lease->address == INADDR_ANY ||
742             lease->server_address == INADDR_ANY ||
743             lease->lifetime == 0) {
744                 log_dhcp_client(client, "receieved lease lacks address, server "
745                                 "address or lease lifetime, ignoring");
746                 return -ENOMSG;
747         }
748
749         if (lease->subnet_mask == INADDR_ANY) {
750                 r = dhcp_lease_set_default_subnet_mask(lease);
751                 if (r < 0) {
752                         log_dhcp_client(client, "receieved lease lacks subnet "
753                                         "mask, and a fallback one can not be "
754                                         "generated, ignoring");
755                         return -ENOMSG;
756                 }
757         }
758
759         r = DHCP_EVENT_IP_ACQUIRE;
760         if (client->lease) {
761                 if (client->lease->address != lease->address ||
762                     client->lease->subnet_mask != lease->subnet_mask ||
763                     client->lease->router != lease->router) {
764                         r = DHCP_EVENT_IP_CHANGE;
765                 }
766
767                 client->lease = sd_dhcp_lease_unref(client->lease);
768         }
769
770         client->lease = lease;
771         lease = NULL;
772
773         log_dhcp_client(client, "ACK");
774
775         return r;
776 }
777
778 static uint64_t client_compute_timeout(sd_dhcp_client *client,
779                                        uint32_t lifetime, double factor) {
780         assert(client);
781         assert(client->request_sent);
782         assert(lifetime);
783
784         return client->request_sent + ((lifetime - 3) * USEC_PER_SEC * factor) +
785                 + (random_u32() & 0x1fffff);
786 }
787
788 static int client_set_lease_timeouts(sd_dhcp_client *client) {
789         usec_t time_now;
790         uint64_t lifetime_timeout;
791         uint64_t t2_timeout;
792         uint64_t t1_timeout;
793         char time_string[FORMAT_TIMESPAN_MAX];
794         int r;
795
796         assert(client);
797         assert(client->event);
798         assert(client->lease);
799         assert(client->lease->lifetime);
800
801         client->timeout_t1 = sd_event_source_unref(client->timeout_t1);
802         client->timeout_t2 = sd_event_source_unref(client->timeout_t2);
803         client->timeout_expire = sd_event_source_unref(client->timeout_expire);
804
805         /* don't set timers for infinite leases */
806         if (client->lease->lifetime == 0xffffffff)
807                 return 0;
808
809         r = sd_event_get_now_monotonic(client->event, &time_now);
810         if (r < 0)
811                 return r;
812         assert(client->request_sent <= time_now);
813
814         /* convert the various timeouts from relative (secs) to absolute (usecs) */
815         lifetime_timeout = client_compute_timeout(client, client->lease->lifetime, 1);
816         if (client->lease->t1 && client->lease->t2) {
817                 /* both T1 and T2 are given */
818                 if (client->lease->t1 < client->lease->t2 &&
819                     client->lease->t2 < client->lease->lifetime) {
820                         /* they are both valid */
821                         t2_timeout = client_compute_timeout(client, client->lease->t2, 1);
822                         t1_timeout = client_compute_timeout(client, client->lease->t1, 1);
823                 } else {
824                         /* discard both */
825                         t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
826                         client->lease->t2 = (client->lease->lifetime * 7) / 8;
827                         t1_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
828                         client->lease->t1 = client->lease->lifetime / 2;
829                 }
830         } else if (client->lease->t2 && client->lease->t2 < client->lease->lifetime) {
831                 /* only T2 is given, and it is valid */
832                 t2_timeout = client_compute_timeout(client, client->lease->t2, 1);
833                 t1_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
834                 client->lease->t1 = client->lease->lifetime / 2;
835                 if (t2_timeout <= t1_timeout) {
836                         /* the computed T1 would be invalid, so discard T2 */
837                         t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
838                         client->lease->t2 = (client->lease->lifetime * 7) / 8;
839                 }
840         } else if (client->lease->t1 && client->lease->t1 < client->lease->lifetime) {
841                 /* only T1 is given, and it is valid */
842                 t1_timeout = client_compute_timeout(client, client->lease->t1, 1);
843                 t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
844                 client->lease->t2 = (client->lease->lifetime * 7) / 8;
845                 if (t2_timeout <= t1_timeout) {
846                         /* the computed T2 would be invalid, so discard T1 */
847                         t2_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
848                         client->lease->t2 = client->lease->lifetime / 2;
849                 }
850         } else {
851                 /* fall back to the default timeouts */
852                 t1_timeout = client_compute_timeout(client, client->lease->lifetime, 0.5);
853                 client->lease->t1 = client->lease->lifetime / 2;
854                 t2_timeout = client_compute_timeout(client, client->lease->lifetime, 7.0 / 8.0);
855                 client->lease->t2 = (client->lease->lifetime * 7) / 8;
856         }
857
858         /* arm lifetime timeout */
859         r = sd_event_add_monotonic(client->event,
860                                    &client->timeout_expire, lifetime_timeout,
861                                    10 * USEC_PER_MSEC,
862                                    client_timeout_expire, client);
863         if (r < 0)
864                 return r;
865
866         r = sd_event_source_set_priority(client->timeout_expire,
867                                          client->event_priority);
868         if (r < 0)
869                 return r;
870
871         log_dhcp_client(client, "lease expires in %s",
872                         format_timespan(time_string, FORMAT_TIMESPAN_MAX,
873                         lifetime_timeout - time_now, 0));
874
875         /* don't arm earlier timeouts if this has already expired */
876         if (lifetime_timeout <= time_now)
877                 return 0;
878
879         /* arm T2 timeout */
880         r = sd_event_add_monotonic(client->event,
881                                    &client->timeout_t2,
882                                    t2_timeout,
883                                    10 * USEC_PER_MSEC,
884                                    client_timeout_t2, client);
885         if (r < 0)
886                 return r;
887
888         r = sd_event_source_set_priority(client->timeout_t2,
889                                          client->event_priority);
890         if (r < 0)
891                 return r;
892
893         log_dhcp_client(client, "T2 expires in %s",
894                         format_timespan(time_string, FORMAT_TIMESPAN_MAX,
895                         t2_timeout - time_now, 0));
896
897         /* don't arm earlier timeout if this has already expired */
898         if (t2_timeout <= time_now)
899                 return 0;
900
901         /* arm T1 timeout */
902         r = sd_event_add_monotonic(client->event,
903                                    &client->timeout_t1,
904                                    t1_timeout,
905                                    10 * USEC_PER_MSEC,
906                                    client_timeout_t1, client);
907         if (r < 0)
908                 return r;
909
910         r = sd_event_source_set_priority(client->timeout_t1,
911                                          client->event_priority);
912         if (r < 0)
913                 return r;
914
915         log_dhcp_client(client, "T1 expires in %s",
916                         format_timespan(time_string, FORMAT_TIMESPAN_MAX,
917                         t1_timeout - time_now, 0));
918
919         return 0;
920 }
921
922 static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message,
923                                  int len) {
924         int r = 0, notify_event = 0;
925
926         assert(client);
927         assert(client->event);
928         assert(message);
929
930         if (len < DHCP_MESSAGE_SIZE) {
931                 log_dhcp_client(client, "message too small (%d bytes): "
932                                 "ignoring", len);
933                 return 0;
934         }
935
936         if (message->op != BOOTREPLY) {
937                 log_dhcp_client(client, "not a BOOTREPLY message: ignoring");
938                 return 0;
939         }
940
941         if (be32toh(message->xid) != client->xid) {
942                 log_dhcp_client(client, "received xid (%u) does not match "
943                                 "expected (%u): ignoring",
944                                 be32toh(message->xid), client->xid);
945                 return 0;
946         }
947
948         if (memcmp(&message->chaddr[0], &client->client_id.mac_addr,
949                    ETH_ALEN)) {
950                 log_dhcp_client(client, "received chaddr does not match "
951                                 "expected: ignoring");
952                 return 0;
953         }
954
955         switch (client->state) {
956         case DHCP_STATE_SELECTING:
957
958                 r = client_handle_offer(client, message, len);
959                 if (r >= 0) {
960
961                         client->timeout_resend =
962                                 sd_event_source_unref(client->timeout_resend);
963
964                         client->state = DHCP_STATE_REQUESTING;
965                         client->attempt = 1;
966
967                         r = sd_event_add_monotonic(client->event,
968                                                    &client->timeout_resend, 0,
969                                                    0, client_timeout_resend,
970                                                    client);
971                         if (r < 0)
972                                 goto error;
973
974                         r = sd_event_source_set_priority(client->timeout_resend,
975                                                          client->event_priority);
976                         if (r < 0)
977                                 goto error;
978                 } else if (r == -ENOMSG)
979                         /* invalid message, let's ignore it */
980                         return 0;
981
982                 break;
983
984         case DHCP_STATE_REBOOTING:
985         case DHCP_STATE_REQUESTING:
986         case DHCP_STATE_RENEWING:
987         case DHCP_STATE_REBINDING:
988
989                 r = client_handle_ack(client, message, len);
990                 if (r == DHCP_EVENT_NO_LEASE) {
991
992                         client->timeout_resend =
993                                 sd_event_source_unref(client->timeout_resend);
994
995                         if (client->state == DHCP_STATE_REBOOTING) {
996                                 r = client_initialize(client);
997                                 if (r < 0)
998                                         goto error;
999
1000                                 r = client_start(client);
1001                                 if (r < 0)
1002                                         goto error;
1003                         }
1004
1005                         goto error;
1006                 } else if (r >= 0) {
1007                         client->timeout_resend =
1008                                 sd_event_source_unref(client->timeout_resend);
1009
1010                         if (IN_SET(client->state, DHCP_STATE_REQUESTING,
1011                                    DHCP_STATE_REBOOTING))
1012                                 notify_event = DHCP_EVENT_IP_ACQUIRE;
1013                         else if (r != DHCP_EVENT_IP_ACQUIRE)
1014                                 notify_event = r;
1015
1016                         client->state = DHCP_STATE_BOUND;
1017                         client->attempt = 1;
1018
1019                         client->last_addr = client->lease->address;
1020
1021                         r = client_set_lease_timeouts(client);
1022                         if (r < 0)
1023                                 goto error;
1024
1025                         if (notify_event)
1026                                 client_notify(client, notify_event);
1027
1028                         client->receive_message =
1029                                 sd_event_source_unref(client->receive_message);
1030                         client->fd = safe_close(client->fd);
1031                 } else if (r == -ENOMSG)
1032                         /* invalid message, let's ignore it */
1033                         return 0;
1034
1035                 break;
1036
1037         case DHCP_STATE_INIT:
1038         case DHCP_STATE_INIT_REBOOT:
1039         case DHCP_STATE_BOUND:
1040
1041                 break;
1042         }
1043
1044 error:
1045         if (r < 0 || r == DHCP_EVENT_NO_LEASE)
1046                 return client_stop(client, r);
1047
1048         return 0;
1049 }
1050
1051 static int client_receive_message_udp(sd_event_source *s, int fd,
1052                                       uint32_t revents, void *userdata) {
1053         sd_dhcp_client *client = userdata;
1054         _cleanup_free_ DHCPMessage *message = NULL;
1055         int buflen = 0, len, r;
1056
1057         assert(s);
1058         assert(client);
1059
1060         r = ioctl(fd, FIONREAD, &buflen);
1061         if (r < 0 || buflen <= 0)
1062                 buflen = sizeof(DHCPMessage) + DHCP_MIN_OPTIONS_SIZE;
1063
1064         message = malloc0(buflen);
1065         if (!message)
1066                 return -ENOMEM;
1067
1068         len = read(fd, message, buflen);
1069         if (len < 0)
1070                 return 0;
1071
1072         return client_handle_message(client, message, len);
1073 }
1074
1075 static int client_receive_message_raw(sd_event_source *s, int fd,
1076                                       uint32_t revents, void *userdata) {
1077         sd_dhcp_client *client = userdata;
1078         _cleanup_free_ DHCPPacket *packet = NULL;
1079         uint8_t cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))];
1080         struct iovec iov = {};
1081         struct msghdr msg = {
1082                 .msg_iov = &iov,
1083                 .msg_iovlen = 1,
1084                 .msg_control = cmsgbuf,
1085                 .msg_controllen = sizeof(cmsgbuf),
1086         };
1087         struct cmsghdr *cmsg;
1088         bool checksum = true;
1089         int buflen = 0, len, r;
1090
1091         assert(s);
1092         assert(client);
1093
1094         r = ioctl(fd, FIONREAD, &buflen);
1095         if (r < 0 || buflen <= 0)
1096                 buflen = sizeof(DHCPPacket) + DHCP_MIN_OPTIONS_SIZE;
1097
1098         packet = malloc0(buflen);
1099         if (!packet)
1100                 return -ENOMEM;
1101
1102         iov.iov_base = packet;
1103         iov.iov_len = buflen;
1104
1105         len = recvmsg(fd, &msg, 0);
1106         if (len < 0) {
1107                 log_dhcp_client(client, "could not receive message from raw "
1108                                 "socket: %s", strerror(errno));
1109                 return 0;
1110         }
1111
1112         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1113                 if (cmsg->cmsg_level == SOL_PACKET && cmsg->cmsg_type == PACKET_AUXDATA) {
1114                         struct tpacket_auxdata *aux = (void *)CMSG_DATA(cmsg);
1115
1116                         checksum = !(aux->tp_status & TP_STATUS_CSUMNOTREADY);
1117                         break;
1118                 }
1119         }
1120
1121         r = dhcp_packet_verify_headers(packet, len, checksum);
1122         if (r < 0)
1123                 return 0;
1124
1125         len -= DHCP_IP_UDP_SIZE;
1126
1127         return client_handle_message(client, &packet->dhcp, len);
1128 }
1129
1130 int sd_dhcp_client_start(sd_dhcp_client *client) {
1131         int r;
1132
1133         assert_return(client, -EINVAL);
1134
1135         r = client_initialize(client);
1136         if (r < 0)
1137                 return r;
1138
1139         if (client->last_addr)
1140                 client->state = DHCP_STATE_INIT_REBOOT;
1141
1142         return client_start(client);
1143 }
1144
1145 int sd_dhcp_client_stop(sd_dhcp_client *client) {
1146         return client_stop(client, DHCP_EVENT_STOP);
1147 }
1148
1149 int sd_dhcp_client_attach_event(sd_dhcp_client *client, sd_event *event,
1150                                 int priority) {
1151         int r;
1152
1153         assert_return(client, -EINVAL);
1154         assert_return(!client->event, -EBUSY);
1155
1156         if (event)
1157                 client->event = sd_event_ref(event);
1158         else {
1159                 r = sd_event_default(&client->event);
1160                 if (r < 0)
1161                         return 0;
1162         }
1163
1164         client->event_priority = priority;
1165
1166         return 0;
1167 }
1168
1169 int sd_dhcp_client_detach_event(sd_dhcp_client *client) {
1170         assert_return(client, -EINVAL);
1171
1172         client->event = sd_event_unref(client->event);
1173
1174         return 0;
1175 }
1176
1177 sd_event *sd_dhcp_client_get_event(sd_dhcp_client *client) {
1178         if (!client)
1179                 return NULL;
1180
1181         return client->event;
1182 }
1183
1184 void sd_dhcp_client_free(sd_dhcp_client *client) {
1185         if (!client)
1186                 return;
1187
1188         sd_dhcp_client_stop(client);
1189         sd_dhcp_client_detach_event(client);
1190
1191         free(client->req_opts);
1192         free(client);
1193 }
1194
1195 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_dhcp_client*, sd_dhcp_client_free);
1196 #define _cleanup_dhcp_client_free_ _cleanup_(sd_dhcp_client_freep)
1197
1198 int sd_dhcp_client_new(sd_dhcp_client **ret) {
1199         _cleanup_dhcp_client_free_ sd_dhcp_client *client = NULL;
1200
1201         assert_return(ret, -EINVAL);
1202
1203         client = new0(sd_dhcp_client, 1);
1204         if (!client)
1205                 return -ENOMEM;
1206
1207         client->state = DHCP_STATE_INIT;
1208         client->index = -1;
1209         client->fd = -1;
1210         client->attempt = 1;
1211
1212         client->req_opts_size = ELEMENTSOF(default_req_opts);
1213
1214         client->req_opts = memdup(default_req_opts, client->req_opts_size);
1215         if (!client->req_opts)
1216                 return -ENOMEM;
1217
1218         *ret = client;
1219         client = NULL;
1220
1221         return 0;
1222 }