summaryrefslogtreecommitdiff
path: root/src/libsystemd-dhcp/dhcp-client.c
blob: b1bdd385930d90d617b4222ff0f4937eb65324dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/***
  This file is part of systemd.

  Copyright (C) 2013 Intel Corporation. All rights reserved.

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation; either version 2.1 of the License, or
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <net/ethernet.h>

#include "util.h"
#include "list.h"

#include "dhcp-protocol.h"
#include "dhcp-internal.h"
#include "sd-dhcp-client.h"

#define DHCP_CLIENT_MIN_OPTIONS_SIZE            312

struct DHCPLease {
        uint32_t lifetime;
        uint32_t address;
        uint32_t server_address;
        uint32_t subnet_mask;
        uint32_t router;
};

typedef struct DHCPLease DHCPLease;

struct sd_dhcp_client {
        DHCPState state;
        sd_event *event;
        sd_event_source *timeout_resend;
        int index;
        int fd;
        union sockaddr_union link;
        sd_event_source *receive_message;
        uint8_t *req_opts;
        size_t req_opts_size;
        uint32_t last_addr;
        struct ether_addr mac_addr;
        uint32_t xid;
        usec_t start_time;
        unsigned int attempt;
        DHCPLease *lease;
};

static const uint8_t default_req_opts[] = {
        DHCP_OPTION_SUBNET_MASK,
        DHCP_OPTION_ROUTER,
        DHCP_OPTION_HOST_NAME,
        DHCP_OPTION_DOMAIN_NAME,
        DHCP_OPTION_DOMAIN_NAME_SERVER,
        DHCP_OPTION_NTP_SERVER,
};

int sd_dhcp_client_set_request_option(sd_dhcp_client *client, uint8_t option)
{
        size_t i;

        assert_return(client, -EINVAL);
        assert_return (client->state == DHCP_STATE_INIT, -EBUSY);

        switch(option) {
        case DHCP_OPTION_PAD:
        case DHCP_OPTION_OVERLOAD:
        case DHCP_OPTION_MESSAGE_TYPE:
        case DHCP_OPTION_PARAMETER_REQUEST_LIST:
        case DHCP_OPTION_END:
                return -EINVAL;

        default:
                break;
        }

        for (i = 0; i < client->req_opts_size; i++)
                if (client->req_opts[i] == option)
                        return -EEXIST;

        if (!GREEDY_REALLOC(client->req_opts, client->req_opts_size,
                            client->req_opts_size + 1))
                return -ENOMEM;

        client->req_opts[client->req_opts_size - 1] = option;

        return 0;
}

int sd_dhcp_client_set_request_address(sd_dhcp_client *client,
                                       const struct in_addr *last_addr)
{
        assert_return(client, -EINVAL);
        assert_return(client->state == DHCP_STATE_INIT, -EBUSY);

        if (last_addr)
                client->last_addr = last_addr->s_addr;
        else
                client->last_addr = INADDR_ANY;

        return 0;
}

int sd_dhcp_client_set_index(sd_dhcp_client *client, int interface_index)
{
        assert_return(client, -EINVAL);
        assert_return(client->state == DHCP_STATE_INIT, -EBUSY);
        assert_return(interface_index >= -1, -EINVAL);

        client->index = interface_index;

        return 0;
}

int sd_dhcp_client_set_mac(sd_dhcp_client *client,
                           const struct ether_addr *addr)
{
        assert_return(client, -EINVAL);
        assert_return(client->state == DHCP_STATE_INIT, -EBUSY);

        memcpy(&client->mac_addr, addr, ETH_ALEN);

        return 0;
}

static int client_stop(sd_dhcp_client *client, int error)
{
        assert_return(client, -EINVAL);
        assert_return(client->state != DHCP_STATE_INIT &&
                      client->state != DHCP_STATE_INIT_REBOOT, -EALREADY);

        client->receive_message =
                sd_event_source_unref(client->receive_message);

        if (client->fd >= 0)
                close(client->fd);
        client->fd = -1;

        client->timeout_resend = sd_event_source_unref(client->timeout_resend);

        client->attempt = 1;

        switch (client->state) {

        case DHCP_STATE_INIT:
        case DHCP_STATE_SELECTING:

                client->start_time = 0;
                client->state = DHCP_STATE_INIT;
                break;

        case DHCP_STATE_INIT_REBOOT:
        case DHCP_STATE_REBOOTING:
        case DHCP_STATE_REQUESTING:
        case DHCP_STATE_BOUND:
        case DHCP_STATE_RENEWING:
        case DHCP_STATE_REBINDING:

                break;
        }

        if (client->lease) {
                free(client->lease);
                client->lease = NULL;
        }

        return 0;
}

static int client_packet_init(sd_dhcp_client *client, uint8_t type,
                              DHCPMessage *message, uint16_t secs,
                              uint8_t **opt, size_t *optlen)
{
        int err;
        be16_t max_size;

        *opt = (uint8_t *)(message + 1);

        if (*optlen < 4)
                return -ENOBUFS;
        *optlen -= 4;

        message->op = BOOTREQUEST;
        message->htype = 1;
        message->hlen = ETHER_ADDR_LEN;
        message->xid = htobe32(client->xid);

        /* Although 'secs' field is a SHOULD in RFC 2131, certain DHCP servers
           refuse to issue an DHCP lease if 'secs' is set to zero */
        message->secs = htobe16(secs);

        memcpy(&message->chaddr, &client->mac_addr, ETH_ALEN);
        (*opt)[0] = 0x63;
        (*opt)[1] = 0x82;
        (*opt)[2] = 0x53;
        (*opt)[3] = 0x63;

        *opt += 4;

        err = dhcp_option_append(opt, optlen, DHCP_OPTION_MESSAGE_TYPE, 1,
                                 &type);
        if (err < 0)
                return err;

        /* Some DHCP servers will refuse to issue an DHCP lease if the Cliient
           Identifier option is not set */
        err = dhcp_option_append(opt, optlen, DHCP_OPTION_CLIENT_IDENTIFIER,
                                 ETH_ALEN, &client->mac_addr);
        if (err < 0)
                return err;

        if (type == DHCP_DISCOVER || type == DHCP_REQUEST) {
                err = dhcp_option_append(opt, optlen,
                                         DHCP_OPTION_PARAMETER_REQUEST_LIST,
                                         client->req_opts_size,
                                         client->req_opts);
                if (err < 0)
                        return err;

                /* Some DHCP servers will send bigger DHCP packets than the
                   defined default size unless the Maximum Messge Size option
                   is explicitely set */
                max_size = htobe16(DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE +
                                   DHCP_CLIENT_MIN_OPTIONS_SIZE);
                err = dhcp_option_append(opt, optlen,
                                         DHCP_OPTION_MAXIMUM_MESSAGE_SIZE,
                                         2, &max_size);
                if (err < 0)
                        return err;
        }

        return 0;
}

static uint16_t client_checksum(void *buf, int len)
{
        uint32_t sum;
        uint16_t *check;
        int i;
        uint8_t *odd;

        sum = 0;
        check = buf;

        for (i = 0; i < len / 2 ; i++)
                sum += check[i];

        if (len & 0x01) {
                odd = buf;
                sum += odd[len];
        }

        return ~((sum & 0xffff) + (sum >> 16));
}

static void client_append_ip_headers(DHCPPacket *packet, uint16_t len)
{
        packet->ip.version = IPVERSION;
        packet->ip.ihl = DHCP_IP_SIZE / 4;
        packet->ip.tot_len = htobe16(len);

        packet->ip.protocol = IPPROTO_UDP;
        packet->ip.saddr = INADDR_ANY;
        packet->ip.daddr = INADDR_BROADCAST;

        packet->udp.source = htobe16(DHCP_PORT_CLIENT);
        packet->udp.dest = htobe16(DHCP_PORT_SERVER);
        packet->udp.len = htobe16(len - DHCP_IP_SIZE);

        packet->ip.check = packet->udp.len;
        packet->udp.check = client_checksum(&packet->ip.ttl, len - 8);

        packet->ip.ttl = IPDEFTTL;
        packet->ip.check = 0;
        packet->ip.check = client_checksum(&packet->ip, DHCP_IP_SIZE);
}

static int client_send_discover(sd_dhcp_client *client, uint16_t secs)
{
        int err = 0;
        _cleanup_free_ DHCPPacket *discover;
        size_t optlen, len;
        uint8_t *opt;

        optlen = DHCP_CLIENT_MIN_OPTIONS_SIZE;
        len = sizeof(DHCPPacket) + optlen;

        discover = malloc0(len);

        if (!discover)
                return -ENOMEM;

        err = client_packet_init(client, DHCP_DISCOVER, &discover->dhcp,
                                 secs, &opt, &optlen);
        if (err < 0)
                return err;

        if (client->last_addr != INADDR_ANY) {
                err = dhcp_option_append(&opt, &optlen,
                                         DHCP_OPTION_REQUESTED_IP_ADDRESS,
                                         4, &client->last_addr);
                if (err < 0)
                        return err;
        }

        err = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
        if (err < 0)
                return err;

        client_append_ip_headers(discover, len);

        err = dhcp_network_send_raw_socket(client->fd, &client->link,
                                           discover, len);

        return err;
}

static int client_send_request(sd_dhcp_client *client, uint16_t secs)
{
        _cleanup_free_ DHCPPacket *request;
        size_t optlen, len;
        int err;
        uint8_t *opt;

        optlen = DHCP_CLIENT_MIN_OPTIONS_SIZE;
        len = DHCP_MESSAGE_SIZE + optlen;

        request = malloc0(len);
        if (!request)
                return -ENOMEM;

        err = client_packet_init(client, DHCP_REQUEST, &request->dhcp, secs,
                                 &opt, &optlen);
        if (err < 0)
                return err;

        if (client->state == DHCP_STATE_REQUESTING) {
                err = dhcp_option_append(&opt, &optlen,
                                         DHCP_OPTION_REQUESTED_IP_ADDRESS,
                                         4, &client->lease->address);
                if (err < 0)
                        return err;

                err = dhcp_option_append(&opt, &optlen,
                                         DHCP_OPTION_SERVER_IDENTIFIER,
                                         4, &client->lease->server_address);
                if (err < 0)
                        return err;
        }

        err = dhcp_option_append(&opt, &optlen, DHCP_OPTION_END, 0, NULL);
        if (err < 0)
                return err;

        client_append_ip_headers(request, len);

        err = dhcp_network_send_raw_socket(client->fd, &client->link,
                                           request, len);

        return err;
}

static int client_timeout_resend(sd_event_source *s, uint64_t usec,
                                 void *userdata)
{
        sd_dhcp_client *client = userdata;
        usec_t next_timeout;
        uint16_t secs;
        int err = 0;

        secs = (usec - client->start_time) / USEC_PER_SEC;

        if (client->attempt < 64)
                client->attempt *= 2;

        next_timeout = usec + (client->attempt - 1) * USEC_PER_SEC +
                (random_u() & 0x1fffff);

        err = sd_event_add_monotonic(client->event, next_timeout,
                                     10 * USEC_PER_MSEC,
                                     client_timeout_resend, client,
                                     &client->timeout_resend);
        if (err < 0)
                goto error;

        switch (client->state) {
        case DHCP_STATE_INIT:
                err = client_send_discover(client, secs);
                if (err >= 0) {
                        client->state = DHCP_STATE_SELECTING;
                        client->attempt = 1;
                } else {
                        if (client->attempt >= 64)
                                goto error;
                }

                break;

        case DHCP_STATE_SELECTING:
                err = client_send_discover(client, secs);
                if (err < 0 && client->attempt >= 64)
                        goto error;

                break;

        case DHCP_STATE_REQUESTING:
                err = client_send_request(client, secs);
                if (err < 0 && client->attempt >= 64)
                         goto error;

                break;

        case DHCP_STATE_INIT_REBOOT:
        case DHCP_STATE_REBOOTING:
        case DHCP_STATE_BOUND:
        case DHCP_STATE_RENEWING:
        case DHCP_STATE_REBINDING:

                break;
        }

        return 0;

error:
        client_stop(client, err);

        /* Errors were dealt with when stopping the client, don't spill
           errors into the event loop handler */
        return 0;
}

static int client_parse_offer(uint8_t code, uint8_t len, const uint8_t *option,
                              void *user_data)
{
        DHCPLease *lease = user_data;
        be32_t val;

        switch(code) {

        case DHCP_OPTION_IP_ADDRESS_LEASE_TIME:
                if (len == 4) {
                        memcpy(&val, option, 4);
                        lease->lifetime = be32toh(val);
                }

                break;

        case DHCP_OPTION_SERVER_IDENTIFIER:
                if (len >= 4)
                        memcpy(&lease->server_address, option, 4);

                break;

        case DHCP_OPTION_SUBNET_MASK:
                if (len >= 4)
                        memcpy(&lease->subnet_mask, option, 4);

                break;

        case DHCP_OPTION_ROUTER:
                if (len >= 4)
                        memcpy(&lease->router, option, 4);

                break;
        }

        return 0;
}

static int client_receive_offer(sd_dhcp_client *client, DHCPPacket *offer,
                                size_t len)
{
        size_t hdrlen;
        DHCPLease *lease;

        if (len < (DHCP_IP_UDP_SIZE + DHCP_MESSAGE_SIZE))
                return -EINVAL;

        hdrlen = offer->ip.ihl * 4;
        if (hdrlen < 20 || hdrlen > len || client_checksum(&offer->ip,
                                                           hdrlen))
                return -EINVAL;

        offer->ip.check = offer->udp.len;
        offer->ip.ttl = 0;

        if (hdrlen + be16toh(offer->udp.len) > len ||
            client_checksum(&offer->ip.ttl, be16toh(offer->udp.len) + 12))
                return -EINVAL;

        if (be16toh(offer->udp.source) != DHCP_PORT_SERVER ||
            be16toh(offer->udp.dest) != DHCP_PORT_CLIENT)
                return -EINVAL;

        if (offer->dhcp.op != BOOTREPLY)
                return -EINVAL;

        if (be32toh(offer->dhcp.xid) != client->xid)
                return -EINVAL;

        if (memcmp(&offer->dhcp.chaddr[0], &client->mac_addr.ether_addr_octet,
                    ETHER_ADDR_LEN))
                return -EINVAL;

        lease = new0(DHCPLease, 1);
        if (!lease)
                return -ENOMEM;

        len = len - DHCP_IP_UDP_SIZE;
        if (dhcp_option_parse(&offer->dhcp, len, client_parse_offer,
                              lease) != DHCP_OFFER)
                goto error;

        lease->address = offer->dhcp.yiaddr;

        if (lease->address == INADDR_ANY ||
            lease->server_address == INADDR_ANY ||
            lease->subnet_mask == INADDR_ANY ||
            lease->lifetime == 0)
                goto error;

        client->lease = lease;

        return 0;

error:
        free(lease);

        return -ENOMSG;
}

static int client_receive_raw_message(sd_event_source *s, int fd,
                                      uint32_t revents, void *userdata)
{
        sd_dhcp_client *client = userdata;
        uint8_t buf[sizeof(DHCPPacket) + DHCP_CLIENT_MIN_OPTIONS_SIZE];
        int buflen = sizeof(buf);
        int len, err = 0;
        DHCPPacket *message;
        usec_t time_now;

        len = read(fd, &buf, buflen);
        if (len < 0)
                return 0;

        err = sd_event_get_now_monotonic(client->event, &time_now);
        if (err < 0)
                goto error;

        message = (DHCPPacket *)&buf;

        switch (client->state) {
        case DHCP_STATE_SELECTING:

                if (client_receive_offer(client, message, len) >= 0) {

                        client->timeout_resend =
                                sd_event_source_unref(client->timeout_resend);

                        client->state = DHCP_STATE_REQUESTING;
                        client->attempt = 1;

                        err = sd_event_add_monotonic(client->event, time_now, 0,
                                                     client_timeout_resend,
                                                     client,
                                                     &client->timeout_resend);
                        if (err < 0)
                                goto error;
                }

                break;

        case DHCP_STATE_INIT:
        case DHCP_STATE_INIT_REBOOT:
        case DHCP_STATE_REBOOTING:
        case DHCP_STATE_REQUESTING:
        case DHCP_STATE_BOUND:
        case DHCP_STATE_RENEWING:
        case DHCP_STATE_REBINDING:

                break;
        }

error:
        if (err < 0)
                return client_stop(client, err);

        return 0;
}

int sd_dhcp_client_start(sd_dhcp_client *client)
{
        int err;

        assert_return(client, -EINVAL);
        assert_return(client->index >= 0, -EINVAL);
        assert_return(client->state == DHCP_STATE_INIT ||
                      client->state == DHCP_STATE_INIT_REBOOT, -EBUSY);

        client->xid = random_u();

        client->fd = dhcp_network_bind_raw_socket(client->index,
                                                  &client->link);

        if (client->fd < 0) {
                err = client->fd;
                goto error;
        }

        err = sd_event_add_io(client->event, client->fd, EPOLLIN,
                              client_receive_raw_message, client,
                              &client->receive_message);
        if (err < 0)
                goto error;

        client->start_time = now(CLOCK_MONOTONIC);
        err = sd_event_add_monotonic(client->event, client->start_time, 0,
                                     client_timeout_resend, client,
                                     &client->timeout_resend);
        if (err < 0)
                goto error;

        return 0;

error:
        client_stop(client, err);

        return err;
}

int sd_dhcp_client_stop(sd_dhcp_client *client)
{
        return client_stop(client, 0);
}

sd_dhcp_client *sd_dhcp_client_new(sd_event *event)
{
        sd_dhcp_client *client;

        assert_return(event, NULL);

        client = new0(sd_dhcp_client, 1);
        if (!client)
                return NULL;

        client->event = sd_event_ref(event);
        client->state = DHCP_STATE_INIT;
        client->index = -1;
        client->fd = -1;
        client->attempt = 1;

        client->req_opts_size = ELEMENTSOF(default_req_opts);

        client->req_opts = memdup(default_req_opts, client->req_opts_size);
        if (!client->req_opts) {
                free(client);
                return NULL;
        }

        return client;
}