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