chiark / gitweb /
dhcp: Process DHCP Ack/Nak message
[elogind.git] / src / libsystemd-dhcp / 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
26 #include "util.h"
27 #include "list.h"
28
29 #include "dhcp-protocol.h"
30 #include "dhcp-internal.h"
31 #include "sd-dhcp-client.h"
32
33 #define DHCP_CLIENT_MIN_OPTIONS_SIZE            312
34
35 struct DHCPLease {
36         uint32_t lifetime;
37         uint32_t address;
38         uint32_t server_address;
39         uint32_t subnet_mask;
40         uint32_t router;
41 };
42
43 typedef struct DHCPLease DHCPLease;
44
45 struct sd_dhcp_client {
46         DHCPState state;
47         sd_event *event;
48         sd_event_source *timeout_resend;
49         int index;
50         int fd;
51         union sockaddr_union link;
52         sd_event_source *receive_message;
53         uint8_t *req_opts;
54         size_t req_opts_size;
55         uint32_t last_addr;
56         struct ether_addr mac_addr;
57         uint32_t xid;
58         usec_t start_time;
59         unsigned int attempt;
60         DHCPLease *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 int sd_dhcp_client_set_request_option(sd_dhcp_client *client, uint8_t option)
73 {
74         size_t i;
75
76         assert_return(client, -EINVAL);
77         assert_return (client->state == DHCP_STATE_INIT, -EBUSY);
78
79         switch(option) {
80         case DHCP_OPTION_PAD:
81         case DHCP_OPTION_OVERLOAD:
82         case DHCP_OPTION_MESSAGE_TYPE:
83         case DHCP_OPTION_PARAMETER_REQUEST_LIST:
84         case DHCP_OPTION_END:
85                 return -EINVAL;
86
87         default:
88                 break;
89         }
90
91         for (i = 0; i < client->req_opts_size; i++)
92                 if (client->req_opts[i] == option)
93                         return -EEXIST;
94
95         if (!GREEDY_REALLOC(client->req_opts, client->req_opts_size,
96                             client->req_opts_size + 1))
97                 return -ENOMEM;
98
99         client->req_opts[client->req_opts_size - 1] = option;
100
101         return 0;
102 }
103
104 int sd_dhcp_client_set_request_address(sd_dhcp_client *client,
105                                        const struct in_addr *last_addr)
106 {
107         assert_return(client, -EINVAL);
108         assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
109
110         if (last_addr)
111                 client->last_addr = last_addr->s_addr;
112         else
113                 client->last_addr = INADDR_ANY;
114
115         return 0;
116 }
117
118 int sd_dhcp_client_set_index(sd_dhcp_client *client, int interface_index)
119 {
120         assert_return(client, -EINVAL);
121         assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
122         assert_return(interface_index >= -1, -EINVAL);
123
124         client->index = interface_index;
125
126         return 0;
127 }
128
129 int sd_dhcp_client_set_mac(sd_dhcp_client *client,
130                            const struct ether_addr *addr)
131 {
132         assert_return(client, -EINVAL);
133         assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
134
135         memcpy(&client->mac_addr, addr, ETH_ALEN);
136
137         return 0;
138 }
139
140 static int client_notify(sd_dhcp_client *client, int event)
141 {
142         return 0;
143 }
144
145 static int client_stop(sd_dhcp_client *client, int error)
146 {
147         assert_return(client, -EINVAL);
148         assert_return(client->state != DHCP_STATE_INIT &&
149                       client->state != DHCP_STATE_INIT_REBOOT, -EALREADY);
150
151         client->receive_message =
152                 sd_event_source_unref(client->receive_message);
153
154         if (client->fd >= 0)
155                 close(client->fd);
156         client->fd = -1;
157
158         client->timeout_resend = sd_event_source_unref(client->timeout_resend);
159
160         client->attempt = 1;
161
162         switch (client->state) {
163
164         case DHCP_STATE_INIT:
165         case DHCP_STATE_SELECTING:
166         case DHCP_STATE_REQUESTING:
167
168                 client->start_time = 0;
169                 client->state = DHCP_STATE_INIT;
170                 break;
171
172         case DHCP_STATE_INIT_REBOOT:
173         case DHCP_STATE_REBOOTING:
174         case DHCP_STATE_BOUND:
175         case DHCP_STATE_RENEWING:
176         case DHCP_STATE_REBINDING:
177
178                 break;
179         }
180
181         if (client->lease) {
182                 free(client->lease);
183                 client->lease = NULL;
184         }
185
186         return 0;
187 }
188
189 static int client_packet_init(sd_dhcp_client *client, uint8_t type,
190                               DHCPMessage *message, uint16_t secs,
191                               uint8_t **opt, size_t *optlen)
192 {
193         int err;
194         be16_t max_size;
195
196         *opt = (uint8_t *)(message + 1);
197
198         if (*optlen < 4)
199                 return -ENOBUFS;
200         *optlen -= 4;
201
202         message->op = BOOTREQUEST;
203         message->htype = 1;
204         message->hlen = ETHER_ADDR_LEN;
205         message->xid = htobe32(client->xid);
206
207         /* Although 'secs' field is a SHOULD in RFC 2131, certain DHCP servers
208            refuse to issue an DHCP lease if 'secs' is set to zero */
209         message->secs = htobe16(secs);
210
211         memcpy(&message->chaddr, &client->mac_addr, ETH_ALEN);
212         (*opt)[0] = 0x63;
213         (*opt)[1] = 0x82;
214         (*opt)[2] = 0x53;
215         (*opt)[3] = 0x63;
216
217         *opt += 4;
218
219         err = dhcp_option_append(opt, optlen, DHCP_OPTION_MESSAGE_TYPE, 1,
220                                  &type);
221         if (err < 0)
222                 return err;
223
224         /* Some DHCP servers will refuse to issue an DHCP lease if the Cliient
225            Identifier option is not set */
226         err = dhcp_option_append(opt, optlen, DHCP_OPTION_CLIENT_IDENTIFIER,
227                                  ETH_ALEN, &client->mac_addr);
228         if (err < 0)
229                 return err;
230
231         if (type == DHCP_DISCOVER || type == DHCP_REQUEST) {
232                 err = dhcp_option_append(opt, optlen,
233                                          DHCP_OPTION_PARAMETER_REQUEST_LIST,
234                                          client->req_opts_size,
235                                          client->req_opts);
236                 if (err < 0)
237                         return err;
238
239                 /* Some DHCP servers will send bigger DHCP packets than the
240                    defined default size unless the Maximum Messge Size option
241                    is explicitely set */
242                 max_size = htobe16(DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE +
243                                    DHCP_CLIENT_MIN_OPTIONS_SIZE);
244                 err = dhcp_option_append(opt, optlen,
245                                          DHCP_OPTION_MAXIMUM_MESSAGE_SIZE,
246                                          2, &max_size);
247                 if (err < 0)
248                         return err;
249         }
250
251         return 0;
252 }
253
254 static uint16_t client_checksum(void *buf, int len)
255 {
256         uint32_t sum;
257         uint16_t *check;
258         int i;
259         uint8_t *odd;
260
261         sum = 0;
262         check = buf;
263
264         for (i = 0; i < len / 2 ; i++)
265                 sum += check[i];
266
267         if (len & 0x01) {
268                 odd = buf;
269                 sum += odd[len];
270         }
271
272         return ~((sum & 0xffff) + (sum >> 16));
273 }
274
275 static void client_append_ip_headers(DHCPPacket *packet, uint16_t len)
276 {
277         packet->ip.version = IPVERSION;
278         packet->ip.ihl = DHCP_IP_SIZE / 4;
279         packet->ip.tot_len = htobe16(len);
280
281         packet->ip.protocol = IPPROTO_UDP;
282         packet->ip.saddr = INADDR_ANY;
283         packet->ip.daddr = INADDR_BROADCAST;
284
285         packet->udp.source = htobe16(DHCP_PORT_CLIENT);
286         packet->udp.dest = htobe16(DHCP_PORT_SERVER);
287         packet->udp.len = htobe16(len - DHCP_IP_SIZE);
288
289         packet->ip.check = packet->udp.len;
290         packet->udp.check = client_checksum(&packet->ip.ttl, len - 8);
291
292         packet->ip.ttl = IPDEFTTL;
293         packet->ip.check = 0;
294         packet->ip.check = client_checksum(&packet->ip, DHCP_IP_SIZE);
295 }
296
297 static int client_send_discover(sd_dhcp_client *client, uint16_t secs)
298 {
299         int err = 0;
300         _cleanup_free_ DHCPPacket *discover;
301         size_t optlen, len;
302         uint8_t *opt;
303
304         optlen = DHCP_CLIENT_MIN_OPTIONS_SIZE;
305         len = sizeof(DHCPPacket) + optlen;
306
307         discover = malloc0(len);
308
309         if (!discover)
310                 return -ENOMEM;
311
312         err = client_packet_init(client, DHCP_DISCOVER, &discover->dhcp,
313                                  secs, &opt, &optlen);
314         if (err < 0)
315                 return err;
316
317         if (client->last_addr != INADDR_ANY) {
318                 err = dhcp_option_append(&opt, &optlen,
319                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
320                                          4, &client->last_addr);
321                 if (err < 0)
322                         return err;
323         }
324
325         err = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
326         if (err < 0)
327                 return err;
328
329         client_append_ip_headers(discover, len);
330
331         err = dhcp_network_send_raw_socket(client->fd, &client->link,
332                                            discover, len);
333
334         return err;
335 }
336
337 static int client_send_request(sd_dhcp_client *client, uint16_t secs)
338 {
339         _cleanup_free_ DHCPPacket *request;
340         size_t optlen, len;
341         int err;
342         uint8_t *opt;
343
344         optlen = DHCP_CLIENT_MIN_OPTIONS_SIZE;
345         len = DHCP_MESSAGE_SIZE + optlen;
346
347         request = malloc0(len);
348         if (!request)
349                 return -ENOMEM;
350
351         err = client_packet_init(client, DHCP_REQUEST, &request->dhcp, secs,
352                                  &opt, &optlen);
353         if (err < 0)
354                 return err;
355
356         if (client->state == DHCP_STATE_REQUESTING) {
357                 err = dhcp_option_append(&opt, &optlen,
358                                          DHCP_OPTION_REQUESTED_IP_ADDRESS,
359                                          4, &client->lease->address);
360                 if (err < 0)
361                         return err;
362
363                 err = dhcp_option_append(&opt, &optlen,
364                                          DHCP_OPTION_SERVER_IDENTIFIER,
365                                          4, &client->lease->server_address);
366                 if (err < 0)
367                         return err;
368         }
369
370         err = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
371         if (err < 0)
372                 return err;
373
374         client_append_ip_headers(request, len);
375
376         err = dhcp_network_send_raw_socket(client->fd, &client->link,
377                                            request, len);
378
379         return err;
380 }
381
382 static int client_timeout_resend(sd_event_source *s, uint64_t usec,
383                                  void *userdata)
384 {
385         sd_dhcp_client *client = userdata;
386         usec_t next_timeout;
387         uint16_t secs;
388         int err = 0;
389
390         secs = (usec - client->start_time) / USEC_PER_SEC;
391
392         if (client->attempt < 64)
393                 client->attempt *= 2;
394
395         next_timeout = usec + (client->attempt - 1) * USEC_PER_SEC +
396                 (random_u() & 0x1fffff);
397
398         err = sd_event_add_monotonic(client->event, next_timeout,
399                                      10 * USEC_PER_MSEC,
400                                      client_timeout_resend, client,
401                                      &client->timeout_resend);
402         if (err < 0)
403                 goto error;
404
405         switch (client->state) {
406         case DHCP_STATE_INIT:
407                 err = client_send_discover(client, secs);
408                 if (err >= 0) {
409                         client->state = DHCP_STATE_SELECTING;
410                         client->attempt = 1;
411                 } else {
412                         if (client->attempt >= 64)
413                                 goto error;
414                 }
415
416                 break;
417
418         case DHCP_STATE_SELECTING:
419                 err = client_send_discover(client, secs);
420                 if (err < 0 && client->attempt >= 64)
421                         goto error;
422
423                 break;
424
425         case DHCP_STATE_REQUESTING:
426                 err = client_send_request(client, secs);
427                 if (err < 0 && client->attempt >= 64)
428                          goto error;
429
430                 break;
431
432         case DHCP_STATE_INIT_REBOOT:
433         case DHCP_STATE_REBOOTING:
434         case DHCP_STATE_BOUND:
435         case DHCP_STATE_RENEWING:
436         case DHCP_STATE_REBINDING:
437
438                 break;
439         }
440
441         return 0;
442
443 error:
444         client_stop(client, err);
445
446         /* Errors were dealt with when stopping the client, don't spill
447            errors into the event loop handler */
448         return 0;
449 }
450
451 static int client_parse_offer(uint8_t code, uint8_t len, const uint8_t *option,
452                               void *user_data)
453 {
454         DHCPLease *lease = user_data;
455         be32_t val;
456
457         switch(code) {
458
459         case DHCP_OPTION_IP_ADDRESS_LEASE_TIME:
460                 if (len == 4) {
461                         memcpy(&val, option, 4);
462                         lease->lifetime = be32toh(val);
463                 }
464
465                 break;
466
467         case DHCP_OPTION_SERVER_IDENTIFIER:
468                 if (len >= 4)
469                         memcpy(&lease->server_address, option, 4);
470
471                 break;
472
473         case DHCP_OPTION_SUBNET_MASK:
474                 if (len >= 4)
475                         memcpy(&lease->subnet_mask, option, 4);
476
477                 break;
478
479         case DHCP_OPTION_ROUTER:
480                 if (len >= 4)
481                         memcpy(&lease->router, option, 4);
482
483                 break;
484         }
485
486         return 0;
487 }
488
489 static int client_verify_headers(sd_dhcp_client *client, DHCPPacket *message,
490                                  size_t len)
491 {
492         size_t hdrlen;
493
494         if (len < (DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE))
495                 return -EINVAL;
496
497         hdrlen = message->ip.ihl * 4;
498         if (hdrlen < 20 || hdrlen > len || client_checksum(&message->ip,
499                                                            hdrlen))
500                 return -EINVAL;
501
502         message->ip.check = message->udp.len;
503         message->ip.ttl = 0;
504
505         if (hdrlen + be16toh(message->udp.len) > len ||
506             client_checksum(&message->ip.ttl, be16toh(message->udp.len) + 12))
507                 return -EINVAL;
508
509         if (be16toh(message->udp.source) != DHCP_PORT_SERVER ||
510             be16toh(message->udp.dest) != DHCP_PORT_CLIENT)
511                 return -EINVAL;
512
513         if (message->dhcp.op != BOOTREPLY)
514                 return -EINVAL;
515
516         if (be32toh(message->dhcp.xid) != client->xid)
517                 return -EINVAL;
518
519         if (memcmp(&message->dhcp.chaddr[0], &client->mac_addr.ether_addr_octet,
520                     ETHER_ADDR_LEN))
521                 return -EINVAL;
522
523         return 0;
524 }
525
526 static int client_receive_offer(sd_dhcp_client *client, DHCPPacket *offer,
527                                 size_t len)
528 {
529         int err;
530         DHCPLease *lease;
531
532         err = client_verify_headers(client, offer, len);
533         if (err < 0)
534                 return err;
535
536         lease = new0(DHCPLease, 1);
537         if (!lease)
538                 return -ENOMEM;
539
540         len = len - DHCP_IP_UDP_SIZE;
541         if (dhcp_option_parse(&offer->dhcp, len, client_parse_offer,
542                               lease) != DHCP_OFFER)
543                 goto error;
544
545         lease->address = offer->dhcp.yiaddr;
546
547         if (lease->address == INADDR_ANY ||
548             lease->server_address == INADDR_ANY ||
549             lease->subnet_mask == INADDR_ANY ||
550             lease->lifetime == 0)
551                 goto error;
552
553         client->lease = lease;
554
555         return 0;
556
557 error:
558         free(lease);
559
560         return -ENOMSG;
561 }
562
563 static int client_receive_ack(sd_dhcp_client *client, DHCPPacket *offer,
564                               size_t len)
565 {
566         int r;
567         DHCPLease *lease;
568
569         r = client_verify_headers(client, offer, len);
570         if (r < 0)
571                 return r;
572
573         lease = new0(DHCPLease, 1);
574         if (!lease)
575                 return -ENOBUFS;
576
577         len = len - DHCP_IP_UDP_SIZE;
578         r = dhcp_option_parse(&offer->dhcp, len, client_parse_offer, lease);
579
580         if (r != DHCP_ACK)
581                 goto error;
582
583         lease->address = offer->dhcp.yiaddr;
584
585         if (lease->address == INADDR_ANY ||
586             lease->server_address == INADDR_ANY ||
587             lease->subnet_mask == INADDR_ANY || lease->lifetime == 0) {
588                 r = -ENOMSG;
589                 goto error;
590         }
591
592         r = DHCP_EVENT_IP_ACQUIRE;
593         if (client->lease) {
594                 if (client->lease->address != lease->address ||
595                     client->lease->subnet_mask != lease->subnet_mask ||
596                     client->lease->router != lease->router) {
597                         r = DHCP_EVENT_IP_CHANGE;
598                 }
599
600                 free(client->lease);
601         }
602
603         client->lease = lease;
604
605         return r;
606
607 error:
608         free(lease);
609
610         return r;
611 }
612
613 static int client_receive_raw_message(sd_event_source *s, int fd,
614                                       uint32_t revents, void *userdata)
615 {
616         sd_dhcp_client *client = userdata;
617         uint8_t buf[sizeof(DHCPPacket) + DHCP_CLIENT_MIN_OPTIONS_SIZE];
618         int buflen = sizeof(buf);
619         int len, r = 0;
620         DHCPPacket *message;
621         usec_t time_now;
622
623         len = read(fd, &buf, buflen);
624         if (len < 0)
625                 return 0;
626
627         r = sd_event_get_now_monotonic(client->event, &time_now);
628         if (r < 0)
629                 goto error;
630
631         message = (DHCPPacket *)&buf;
632
633         switch (client->state) {
634         case DHCP_STATE_SELECTING:
635
636                 if (client_receive_offer(client, message, len) >= 0) {
637
638                         client->timeout_resend =
639                                 sd_event_source_unref(client->timeout_resend);
640
641                         client->state = DHCP_STATE_REQUESTING;
642                         client->attempt = 1;
643
644                         r = sd_event_add_monotonic(client->event, time_now, 0,
645                                                    client_timeout_resend,
646                                                    client,
647                                                    &client->timeout_resend);
648                         if (r < 0)
649                                 goto error;
650                 }
651
652                 break;
653
654         case DHCP_STATE_REQUESTING:
655
656                 r = client_receive_ack(client, message, len);
657                 if (r == DHCP_EVENT_NO_LEASE)
658                         goto error;
659
660                 if (r >= 0) {
661                         client->timeout_resend =
662                                 sd_event_source_unref(client->timeout_resend);
663
664                         client->state = DHCP_STATE_BOUND;
665                         client->attempt = 1;
666
667                         client->last_addr = client->lease->address;
668
669                         client_notify(client, DHCP_EVENT_IP_ACQUIRE);
670
671                         close(client->fd);
672                         client->fd = -1;
673                         client->receive_message =
674                                 sd_event_source_unref(client->receive_message);
675                 }
676                 break;
677
678         case DHCP_STATE_INIT:
679         case DHCP_STATE_INIT_REBOOT:
680         case DHCP_STATE_REBOOTING:
681         case DHCP_STATE_BOUND:
682         case DHCP_STATE_RENEWING:
683         case DHCP_STATE_REBINDING:
684
685                 break;
686         }
687
688 error:
689         if (r < 0)
690                 return client_stop(client, r);
691
692         return 0;
693 }
694
695 int sd_dhcp_client_start(sd_dhcp_client *client)
696 {
697         int err;
698
699         assert_return(client, -EINVAL);
700         assert_return(client->index >= 0, -EINVAL);
701         assert_return(client->state == DHCP_STATE_INIT ||
702                       client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);
703
704         client->xid = random_u();
705
706         client->fd = dhcp_network_bind_raw_socket(client->index,
707                                                   &client->link);
708
709         if (client->fd < 0) {
710                 err = client->fd;
711                 goto error;
712         }
713
714         err = sd_event_add_io(client->event, client->fd, EPOLLIN,
715                               client_receive_raw_message, client,
716                               &client->receive_message);
717         if (err < 0)
718                 goto error;
719
720         client->start_time = now(CLOCK_MONOTONIC);
721         err = sd_event_add_monotonic(client->event, client->start_time, 0,
722                                      client_timeout_resend, client,
723                                      &client->timeout_resend);
724         if (err < 0)
725                 goto error;
726
727         return 0;
728
729 error:
730         client_stop(client, err);
731
732         return err;
733 }
734
735 int sd_dhcp_client_stop(sd_dhcp_client *client)
736 {
737         return client_stop(client, 0);
738 }
739
740 sd_dhcp_client *sd_dhcp_client_new(sd_event *event)
741 {
742         sd_dhcp_client *client;
743
744         assert_return(event, NULL);
745
746         client = new0(sd_dhcp_client, 1);
747         if (!client)
748                 return NULL;
749
750         client->event = sd_event_ref(event);
751         client->state = DHCP_STATE_INIT;
752         client->index = -1;
753         client->fd = -1;
754         client->attempt = 1;
755
756         client->req_opts_size = ELEMENTSOF(default_req_opts);
757
758         client->req_opts = memdup(default_req_opts, client->req_opts_size);
759         if (!client->req_opts) {
760                 free(client);
761                 return NULL;
762         }
763
764         return client;
765 }