chiark / gitweb /
5d8efbbd3f7c16c33b93fdc1873ecb0ccf4633df
[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->start_time = 0;
202         client->secs = 0;
203         client->state = DHCP_STATE_INIT;
204         client->xid = 0;
205
206         if (client->lease)
207                 client->lease = sd_dhcp_lease_unref(client->lease);
208
209         return 0;
210 }
211
212 static int client_stop(sd_dhcp_client *client, int error) {
213         assert_return(client, -EINVAL);
214
215         client_notify(client, error);
216
217         client_initialize(client);
218
219         log_dhcp_client(client, "STOPPED");
220
221         return 0;
222 }
223
224 static int client_message_init(sd_dhcp_client *client, DHCPMessage *message,
225                                uint8_t type, uint8_t **opt, size_t *optlen) {
226         int r;
227
228         assert(client);
229         assert(client->secs);
230         assert(message);
231         assert(opt);
232         assert(optlen);
233
234         r = dhcp_message_init(message, BOOTREQUEST, client->xid, type, opt,
235                               optlen);
236         if (r < 0)
237                 return r;
238
239         /* Although 'secs' field is a SHOULD in RFC 2131, certain DHCP servers
240            refuse to issue an DHCP lease if 'secs' is set to zero */
241         message->secs = htobe16(client->secs);
242
243         memcpy(&message->chaddr, &client->client_id.mac_addr, ETH_ALEN);
244
245         if (client->state == DHCP_STATE_RENEWING ||
246             client->state == DHCP_STATE_REBINDING)
247                 message->ciaddr = client->lease->address;
248
249         /* Some DHCP servers will refuse to issue an DHCP lease if the Client
250            Identifier option is not set */
251         r = dhcp_option_append(opt, optlen, DHCP_OPTION_CLIENT_IDENTIFIER,
252                                sizeof(client->client_id), &client->client_id);
253         if (r < 0)
254                 return r;
255
256         if (type == DHCP_DISCOVER || type == DHCP_REQUEST) {
257                 be16_t max_size;
258
259                 r = dhcp_option_append(opt, optlen,
260                                        DHCP_OPTION_PARAMETER_REQUEST_LIST,
261                                        client->req_opts_size,
262                                        client->req_opts);
263                 if (r < 0)
264                         return r;
265
266                 /* Some DHCP servers will send bigger DHCP packets than the
267                    defined default size unless the Maximum Messge Size option
268                    is explicitely set */
269                 max_size = htobe16(DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE +
270                                    DHCP_MIN_OPTIONS_SIZE);
271                 r = dhcp_option_append(opt, optlen,
272                                        DHCP_OPTION_MAXIMUM_MESSAGE_SIZE,
273                                        2, &max_size);
274                 if (r < 0)
275                         return r;
276         }
277
278         return 0;
279 }
280
281 static int dhcp_client_send_raw(sd_dhcp_client *client, DHCPPacket *packet,
282                                 size_t len) {
283         dhcp_packet_append_ip_headers(packet, INADDR_ANY, DHCP_PORT_CLIENT,
284                                       INADDR_BROADCAST, DHCP_PORT_SERVER, len);
285
286         return dhcp_network_send_raw_socket(client->fd, &client->link,
287                                             packet, len);
288 }
289
290 static int client_send_discover(sd_dhcp_client *client) {
291         _cleanup_free_ DHCPPacket *discover;
292         size_t optlen, len;
293         uint8_t *opt;
294         usec_t time_now;
295         int r;
296
297         assert(client);
298
299         r = sd_event_get_now_monotonic(client->event, &time_now);
300         if (r < 0)
301                 return r;
302         assert(time_now >= client->start_time);
303
304         /* seconds between sending first and last DISCOVER
305          * must always be strictly positive to deal with broken servers */
306         client->secs = ((time_now - client->start_time) / USEC_PER_SEC) ? : 1;
307
308         optlen = DHCP_MIN_OPTIONS_SIZE;
309         len = sizeof(DHCPPacket) + optlen;
310
311         discover = malloc0(len);
312         if (!discover)
313                 return -ENOMEM;
314
315         r = client_message_init(client, &discover->dhcp, DHCP_DISCOVER,
316                                 &opt, &optlen);
317         if (r < 0)
318                 return r;
319
320         if (client->last_addr != INADDR_ANY) {
321                 r = dhcp_option_append(&opt, &optlen,
322                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
323                                          4, &client->last_addr);
324                 if (r < 0)
325                         return r;
326         }
327
328         r = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
329         if (r < 0)
330                 return r;
331
332         r = dhcp_client_send_raw(client, discover, len - optlen);
333         if (r < 0)
334                 return r;
335
336         log_dhcp_client(client, "DISCOVER");
337
338         return 0;
339 }
340
341 static int client_send_request(sd_dhcp_client *client) {
342         _cleanup_free_ DHCPPacket *request;
343         size_t optlen, len;
344         uint8_t *opt;
345         int r;
346
347         optlen = DHCP_MIN_OPTIONS_SIZE;
348         len = sizeof(DHCPPacket) + optlen;
349
350         request = malloc0(len);
351         if (!request)
352                 return -ENOMEM;
353
354         r = client_message_init(client, &request->dhcp, DHCP_REQUEST, &opt,
355                                 &optlen);
356         if (r < 0)
357                 return r;
358
359         switch (client->state) {
360
361         case DHCP_STATE_INIT_REBOOT:
362                 r = dhcp_option_append(&opt, &optlen,
363                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
364                                          4, &client->last_addr);
365                 if (r < 0)
366                         return r;
367                 break;
368
369         case DHCP_STATE_REQUESTING:
370                 r = dhcp_option_append(&opt, &optlen,
371                                        DHCP_OPTION_REQUESTED_IP_ADDRESS,
372                                        4, &client->lease->address);
373                 if (r < 0)
374                         return r;
375
376                 r = dhcp_option_append(&opt, &optlen,
377                                        DHCP_OPTION_SERVER_IDENTIFIER,
378                                        4, &client->lease->server_address);
379                 if (r < 0)
380                         return r;
381                 break;
382
383         case DHCP_STATE_INIT:
384         case DHCP_STATE_SELECTING:
385         case DHCP_STATE_REBOOTING:
386         case DHCP_STATE_BOUND:
387         case DHCP_STATE_RENEWING:
388         case DHCP_STATE_REBINDING:
389
390                 break;
391         }
392
393         r = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
394         if (r < 0)
395                 return r;
396
397         if (client->state == DHCP_STATE_RENEWING) {
398                 r = dhcp_network_send_udp_socket(client->fd,
399                                                  client->lease->server_address,
400                                                  DHCP_PORT_SERVER,
401                                                  &request->dhcp,
402                                                  len - optlen - DHCP_IP_UDP_SIZE);
403         } else {
404                 r = dhcp_client_send_raw(client, request, len - optlen);
405         }
406         if (r < 0)
407                 return r;
408
409         log_dhcp_client(client, "REQUEST");
410
411         return 0;
412 }
413
414 static int client_timeout_resend(sd_event_source *s, uint64_t usec,
415                                  void *userdata) {
416         sd_dhcp_client *client = userdata;
417         usec_t next_timeout = 0;
418         uint64_t time_now;
419         uint32_t time_left;
420         int r;
421
422         assert(s);
423         assert(client);
424         assert(client->event);
425
426         r = sd_event_get_now_monotonic(client->event, &time_now);
427         if (r < 0)
428                 goto error;
429
430         switch (client->state) {
431         case DHCP_STATE_RENEWING:
432
433                 time_left = (client->lease->t2 - client->lease->t1) / 2;
434                 if (time_left < 60)
435                         time_left = 60;
436
437                 next_timeout = time_now + time_left * USEC_PER_SEC;
438
439                 break;
440
441         case DHCP_STATE_REBINDING:
442
443                 time_left = (client->lease->lifetime - client->lease->t2) / 2;
444                 if (time_left < 60)
445                         time_left = 60;
446
447                 next_timeout = time_now + time_left * USEC_PER_SEC;
448                 break;
449
450         case DHCP_STATE_REBOOTING:
451                 /* start over as we did not receive a timely ack or nak */
452                 client->state = DHCP_STATE_INIT;
453                 client->attempt = 1;
454                 client->xid = random_u32();
455
456                 /* fall through */
457         case DHCP_STATE_INIT:
458         case DHCP_STATE_INIT_REBOOT:
459         case DHCP_STATE_SELECTING:
460         case DHCP_STATE_REQUESTING:
461         case DHCP_STATE_BOUND:
462
463                 if (client->attempt < 64)
464                         client->attempt *= 2;
465
466                 next_timeout = time_now + (client->attempt - 1) * USEC_PER_SEC;
467
468                 break;
469         }
470
471         next_timeout += (random_u32() & 0x1fffff);
472
473         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
474
475         r = sd_event_add_monotonic(client->event,
476                                      &client->timeout_resend,
477                                      next_timeout,
478                                      10 * USEC_PER_MSEC,
479                                      client_timeout_resend, client);
480         if (r < 0)
481                 goto error;
482
483         r = sd_event_source_set_priority(client->timeout_resend,
484                                          client->event_priority);
485         if (r < 0)
486                 goto error;
487
488         switch (client->state) {
489         case DHCP_STATE_INIT:
490                 r = client_send_discover(client);
491                 if (r >= 0) {
492                         client->state = DHCP_STATE_SELECTING;
493                         client->attempt = 1;
494                 } else {
495                         if (client->attempt >= 64)
496                                 goto error;
497                 }
498
499                 break;
500
501         case DHCP_STATE_SELECTING:
502                 r = client_send_discover(client);
503                 if (r < 0 && client->attempt >= 64)
504                         goto error;
505
506                 break;
507
508         case DHCP_STATE_INIT_REBOOT:
509         case DHCP_STATE_REQUESTING:
510         case DHCP_STATE_RENEWING:
511         case DHCP_STATE_REBINDING:
512                 r = client_send_request(client);
513                 if (r < 0 && client->attempt >= 64)
514                          goto error;
515
516                 if (client->state == DHCP_STATE_INIT_REBOOT)
517                         client->state = DHCP_STATE_REBOOTING;
518
519                 client->request_sent = time_now;
520
521                 break;
522
523         case DHCP_STATE_REBOOTING:
524         case DHCP_STATE_BOUND:
525
526                 break;
527         }
528
529         return 0;
530
531 error:
532         client_stop(client, r);
533
534         /* Errors were dealt with when stopping the client, don't spill
535            errors into the event loop handler */
536         return 0;
537 }
538
539 static int client_initialize_events(sd_dhcp_client *client,
540                                     sd_event_io_handler_t io_callback) {
541         int r;
542
543         assert(client);
544         assert(client->event);
545
546         r = sd_event_add_io(client->event, &client->receive_message,
547                             client->fd, EPOLLIN, io_callback,
548                             client);
549         if (r < 0)
550                 goto error;
551
552         r = sd_event_source_set_priority(client->receive_message,
553                                          client->event_priority);
554         if (r < 0)
555                 goto error;
556
557         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
558
559         r = sd_event_add_monotonic(client->event,
560                                    &client->timeout_resend, 0, 0,
561                                    client_timeout_resend, client);
562         if (r < 0)
563                 goto error;
564
565         r = sd_event_source_set_priority(client->timeout_resend,
566                                          client->event_priority);
567
568 error:
569         if (r < 0)
570                 client_stop(client, r);
571
572         return 0;
573
574 }
575
576 static int client_start(sd_dhcp_client *client) {
577         int r;
578
579         assert_return(client, -EINVAL);
580         assert_return(client->event, -EINVAL);
581         assert_return(client->index > 0, -EINVAL);
582         assert_return(client->fd < 0, -EBUSY);
583         assert_return(client->xid == 0, -EINVAL);
584         assert_return(client->state == DHCP_STATE_INIT ||
585                       client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);
586
587         client->xid = random_u32();
588
589         r = dhcp_network_bind_raw_socket(client->index, &client->link);
590
591         if (r < 0) {
592                 client_stop(client, r);
593                 return r;
594         }
595
596         client->fd = r;
597         client->start_time = now(CLOCK_MONOTONIC);
598         client->secs = 0;
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 }