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