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