9ad51fbc7a72727a5ba9120d2294945e8ce880bb
[freeradius.git] / src / modules / proto_dhcp / dhcp.c
1 /*
2  * dhcp.c       Functions to send/receive dhcp packets.
3  *
4  * Version:     $Id$
5  *
6  *   This library is free software; you can redistribute it and/or
7  *   modify it under the terms of the GNU Lesser General Public
8  *   License as published by the Free Software Foundation; either
9  *   version 2.1 of the License, or (at your option) any later version.
10  *
11  *   This library is distributed in the hope that it will be useful,
12  *   but 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
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2008 The FreeRADIUS server project
21  * Copyright 2008 Alan DeKok <aland@deployingradius.com>
22  */
23
24 RCSID("$Id$")
25
26 #include <freeradius-devel/libradius.h>
27 #include <freeradius-devel/udpfromto.h>
28 #include <freeradius-devel/dhcp.h>
29
30 #ifndef __MINGW32__
31 #include <sys/ioctl.h>
32 #endif
33
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37 #ifdef HAVE_SYS_TYPES_H
38 #include <sys/types.h>
39 #endif
40
41 #ifndef __MINGW32__
42 #include <net/if_arp.h>
43 #endif
44
45 #define DHCP_CHADDR_LEN (16)
46 #define DHCP_SNAME_LEN  (64)
47 #define DHCP_FILE_LEN   (128)
48 #define DHCP_VEND_LEN   (308)
49 #define DHCP_OPTION_MAGIC_NUMBER (0x63825363)
50
51 #ifndef INADDR_BROADCAST
52 #define INADDR_BROADCAST INADDR_NONE
53 #endif
54
55 /* @todo: this is a hack */
56 #  define DEBUG                 if (fr_debug_flag && fr_log_fp) fr_printf_log
57 #  define debug_pair(vp)        do { if (fr_debug_flag && fr_log_fp) { \
58                                         vp_print(fr_log_fp, vp); \
59                                      } \
60                                 } while(0)
61
62 typedef struct dhcp_packet_t {
63         uint8_t         opcode;
64         uint8_t         htype;
65         uint8_t         hlen;
66         uint8_t         hops;
67         uint32_t        xid;    /* 4 */
68         uint16_t        secs;   /* 8 */
69         uint16_t        flags;
70         uint32_t        ciaddr; /* 12 */
71         uint32_t        yiaddr; /* 16 */
72         uint32_t        siaddr; /* 20 */
73         uint32_t        giaddr; /* 24 */
74         uint8_t         chaddr[DHCP_CHADDR_LEN]; /* 28 */
75         uint8_t         sname[DHCP_SNAME_LEN]; /* 44 */
76         uint8_t         file[DHCP_FILE_LEN]; /* 108 */
77         uint32_t        option_format; /* 236 */
78         uint8_t         options[DHCP_VEND_LEN];
79 } dhcp_packet_t;
80
81 typedef struct dhcp_option_t {
82         uint8_t         code;
83         uint8_t         length;
84 } dhcp_option_t;
85
86 /*
87  *      INADDR_ANY : 68 -> INADDR_BROADCAST : 67        DISCOVER
88  *      INADDR_BROADCAST : 68 <- SERVER_IP : 67         OFFER
89  *      INADDR_ANY : 68 -> INADDR_BROADCAST : 67        REQUEST
90  *      INADDR_BROADCAST : 68 <- SERVER_IP : 67         ACK
91  */
92 static char const *dhcp_header_names[] = {
93         "DHCP-Opcode",
94         "DHCP-Hardware-Type",
95         "DHCP-Hardware-Address-Length",
96         "DHCP-Hop-Count",
97         "DHCP-Transaction-Id",
98         "DHCP-Number-of-Seconds",
99         "DHCP-Flags",
100         "DHCP-Client-IP-Address",
101         "DHCP-Your-IP-Address",
102         "DHCP-Server-IP-Address",
103         "DHCP-Gateway-IP-Address",
104         "DHCP-Client-Hardware-Address",
105         "DHCP-Server-Host-Name",
106         "DHCP-Boot-Filename",
107
108         NULL
109 };
110
111 static char const *dhcp_message_types[] = {
112         "invalid",
113         "DHCP-Discover",
114         "DHCP-Offer",
115         "DHCP-Request",
116         "DHCP-Decline",
117         "DHCP-Ack",
118         "DHCP-NAK",
119         "DHCP-Release",
120         "DHCP-Inform",
121         "DHCP-Force-Renew",
122 };
123
124 static int dhcp_header_sizes[] = {
125         1, 1, 1, 1,
126         4, 2, 2, 4,
127         4, 4, 4,
128         DHCP_CHADDR_LEN,
129         DHCP_SNAME_LEN,
130         DHCP_FILE_LEN
131 };
132
133
134 /*
135  *      Some clients silently ignore responses less than 300 bytes.
136  */
137 #define MIN_PACKET_SIZE (244)
138 #define DEFAULT_PACKET_SIZE (300)
139 #define MAX_PACKET_SIZE (1500 - 40)
140
141 #define DHCP_OPTION_FIELD (0)
142 #define DHCP_FILE_FIELD   (1)
143 #define DHCP_SNAME_FIELD  (2)
144
145 static uint8_t *dhcp_get_option(dhcp_packet_t *packet, size_t packet_size,
146                                 unsigned int option)
147 {
148         int overload = 0;
149         int field = DHCP_OPTION_FIELD;
150         size_t where, size;
151         uint8_t *data;
152
153         where = 0;
154         size = packet_size - offsetof(dhcp_packet_t, options);
155         data = &packet->options[where];
156
157         while (where < size) {
158                 if (data[0] == 0) { /* padding */
159                         where++;
160                         continue;
161                 }
162
163                 if (data[0] == 255) { /* end of options */
164                         if ((field == DHCP_OPTION_FIELD) &&
165                             (overload & DHCP_FILE_FIELD)) {
166                                 data = packet->file;
167                                 where = 0;
168                                 size = sizeof(packet->file);
169                                 field = DHCP_FILE_FIELD;
170                                 continue;
171
172                         } else if ((field == DHCP_FILE_FIELD) &&
173                                    (overload & DHCP_SNAME_FIELD)) {
174                                 data = packet->sname;
175                                 where = 0;
176                                 size = sizeof(packet->sname);
177                                 field = DHCP_SNAME_FIELD;
178                                 continue;
179                         }
180
181                         return NULL;
182                 }
183
184                 /*
185                  *      We MUST have a real option here.
186                  */
187                 if ((where + 2) > size) {
188                         fr_strerror_printf("Options overflow field at %u",
189                                            (unsigned int) (data - (uint8_t *) packet));
190                         return NULL;
191                 }
192
193                 if ((where + 2 + data[1]) > size) {
194                         fr_strerror_printf("Option length overflows field at %u",
195                                            (unsigned int) (data - (uint8_t *) packet));
196                         return NULL;
197                 }
198
199                 if (data[0] == option) return data;
200
201                 if (data[0] == 52) { /* overload sname and/or file */
202                         overload = data[3];
203                 }
204
205                 where += data[1] + 2;
206                 data += data[1] + 2;
207         }
208
209         return NULL;
210 }
211
212 /*
213  *      DHCPv4 is only for IPv4.  Broadcast only works if udpfromto is
214  *      defined.
215  */
216 RADIUS_PACKET *fr_dhcp_recv(int sockfd)
217 {
218         uint32_t                magic;
219         struct sockaddr_storage src;
220         struct sockaddr_storage dst;
221         socklen_t               sizeof_src;
222         socklen_t               sizeof_dst;
223         RADIUS_PACKET           *packet;
224         uint16_t                port;
225         uint8_t                 *code;
226         ssize_t                 data_len;
227
228         packet = rad_alloc(NULL, false);
229         if (!packet) {
230                 fr_strerror_printf("Failed allocating packet");
231                 return NULL;
232         }
233
234         packet->data = talloc_zero_array(packet, uint8_t, MAX_PACKET_SIZE);
235         if (!packet->data) {
236                 fr_strerror_printf("Out of memory");
237                 rad_free(&packet);
238                 return NULL;
239         }
240
241         packet->sockfd = sockfd;
242         sizeof_src = sizeof(src);
243 #ifdef WITH_UDPFROMTO
244         sizeof_dst = sizeof(dst);
245         data_len = recvfromto(sockfd, packet->data, MAX_PACKET_SIZE, 0,
246                               (struct sockaddr *)&src, &sizeof_src,
247                               (struct sockaddr *)&dst, &sizeof_dst);
248 #else
249         data_len = recvfrom(sockfd, packet->data, MAX_PACKET_SIZE, 0,
250                             (struct sockaddr *)&src, &sizeof_src);
251 #endif
252
253         if (data_len <= 0) {
254                 fr_strerror_printf("Failed reading DHCP socket: %s", fr_syserror(errno));
255                 rad_free(&packet);
256                 return NULL;
257         }
258
259         packet->data_len = data_len;
260         if (packet->data_len < MIN_PACKET_SIZE) {
261                 fr_strerror_printf("DHCP packet is too small (%zu < %d)",
262                                    packet->data_len, MIN_PACKET_SIZE);
263                 rad_free(&packet);
264                 return NULL;
265         }
266
267         if (packet->data_len > MAX_PACKET_SIZE) {
268                 fr_strerror_printf("DHCP packet is too large (%zx > %d)",
269                                    packet->data_len, MAX_PACKET_SIZE);
270                 rad_free(&packet);
271                 return NULL;
272         }
273
274         if (packet->data[1] != 1) {
275                 fr_strerror_printf("DHCP can only receive ethernet requests, not type %02x",
276                       packet->data[1]);
277                 rad_free(&packet);
278                 return NULL;
279         }
280
281         if (packet->data[2] != 6) {
282                 fr_strerror_printf("Ethernet HW length is wrong length %d",
283                         packet->data[2]);
284                 rad_free(&packet);
285                 return NULL;
286         }
287
288         memcpy(&magic, packet->data + 236, 4);
289         magic = ntohl(magic);
290         if (magic != DHCP_OPTION_MAGIC_NUMBER) {
291                 fr_strerror_printf("Cannot do BOOTP");
292                 rad_free(&packet);
293                 return NULL;
294         }
295
296         /*
297          *      Create unique keys for the packet.
298          */
299         memcpy(&magic, packet->data + 4, 4);
300         packet->id = ntohl(magic);
301
302         code = dhcp_get_option((dhcp_packet_t *) packet->data,
303                                packet->data_len, 53);
304         if (!code) {
305                 fr_strerror_printf("No message-type option was found in the packet");
306                 rad_free(&packet);
307                 return NULL;
308         }
309
310         if ((code[1] < 1) || (code[2] == 0) || (code[2] > 8)) {
311                 fr_strerror_printf("Unknown value for message-type option");
312                 rad_free(&packet);
313                 return NULL;
314         }
315
316         packet->code = code[2] | PW_DHCP_OFFSET;
317
318         /*
319          *      Create a unique vector from the MAC address and the
320          *      DHCP opcode.  This is a hack for the RADIUS
321          *      infrastructure in the rest of the server.
322          *
323          *      Note: packet->data[2] == 6, which is smaller than
324          *      sizeof(packet->vector)
325          *
326          *      FIXME:  Look for client-identifier in packet,
327          *      and use that, too?
328          */
329         memset(packet->vector, 0, sizeof(packet->vector));
330         memcpy(packet->vector, packet->data + 28, packet->data[2]);
331         packet->vector[packet->data[2]] = packet->code & 0xff;
332
333         /*
334          *      FIXME: for DISCOVER / REQUEST: src_port == dst_port + 1
335          *      FIXME: for OFFER / ACK       : src_port = dst_port - 1
336          */
337
338         /*
339          *      Unique keys are xid, client mac, and client ID?
340          */
341
342         /*
343          *      FIXME: More checks, like DHCP packet type?
344          */
345
346         sizeof_dst = sizeof(dst);
347
348 #ifndef WITH_UDPFROMTO
349         /*
350          *      This should never fail...
351          */
352         if (getsockname(sockfd, (struct sockaddr *) &dst, &sizeof_dst) < 0) {
353                 fr_strerror_printf("getsockname failed: %s", fr_syserror(errno));
354                 rad_free(&packet);
355                 return NULL;
356         }
357 #endif
358
359         fr_sockaddr2ipaddr(&dst, sizeof_dst, &packet->dst_ipaddr, &port);
360         packet->dst_port = port;
361
362         fr_sockaddr2ipaddr(&src, sizeof_src, &packet->src_ipaddr, &port);
363         packet->src_port = port;
364
365         if (fr_debug_flag > 1) {
366                 char type_buf[64];
367                 char const *name = type_buf;
368                 char src_ip_buf[256], dst_ip_buf[256];
369
370                 if ((packet->code >= PW_DHCP_DISCOVER) &&
371                     (packet->code <= PW_DHCP_INFORM)) {
372                         name = dhcp_message_types[packet->code - PW_DHCP_OFFSET];
373                 } else {
374                         snprintf(type_buf, sizeof(type_buf), "%d",
375                                  packet->code - PW_DHCP_OFFSET);
376                 }
377
378                 DEBUG("Received %s of Id %08x from %s:%d to %s:%d\n",
379                        name, (unsigned int) packet->id,
380                        inet_ntop(packet->src_ipaddr.af,
381                                  &packet->src_ipaddr.ipaddr,
382                                  src_ip_buf, sizeof(src_ip_buf)),
383                        packet->src_port,
384                        inet_ntop(packet->dst_ipaddr.af,
385                                  &packet->dst_ipaddr.ipaddr,
386                                  dst_ip_buf, sizeof(dst_ip_buf)),
387                        packet->dst_port);
388         }
389
390         return packet;
391 }
392
393
394 /*
395  *      Send a DHCP packet.
396  */
397 int fr_dhcp_send(RADIUS_PACKET *packet)
398 {
399         struct sockaddr_storage dst;
400         socklen_t               sizeof_dst;
401 #ifdef WITH_UDPFROMTO
402         struct sockaddr_storage src;
403         socklen_t               sizeof_src;
404
405         fr_ipaddr2sockaddr(&packet->src_ipaddr, packet->src_port,
406             &src, &sizeof_src);
407 #endif
408
409         fr_ipaddr2sockaddr(&packet->dst_ipaddr, packet->dst_port,
410                            &dst, &sizeof_dst);
411
412         if (packet->data_len == 0) {
413                 fr_strerror_printf("No data to send");
414                 return -1;
415         }
416
417         if (fr_debug_flag > 1) {
418                 char type_buf[64];
419                 char const *name = type_buf;
420 #ifdef WITH_UDPFROMTO
421                 char src_ip_buf[INET6_ADDRSTRLEN];
422 #endif
423                 char dst_ip_buf[INET6_ADDRSTRLEN];
424
425                 if ((packet->code >= PW_DHCP_DISCOVER) &&
426                     (packet->code <= PW_DHCP_INFORM)) {
427                         name = dhcp_message_types[packet->code - PW_DHCP_OFFSET];
428                 } else {
429                         snprintf(type_buf, sizeof(type_buf), "%d",
430                             packet->code - PW_DHCP_OFFSET);
431                 }
432
433                 DEBUG(
434 #ifdef WITH_UDPFROMTO
435                 "Sending %s Id %08x from %s:%d to %s:%d\n",
436 #else
437                 "Sending %s Id %08x to %s:%d\n",
438 #endif
439                    name, (unsigned int) packet->id,
440 #ifdef WITH_UDPFROMTO
441                    inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, src_ip_buf, sizeof(src_ip_buf)),
442                    packet->src_port,
443 #endif
444                    inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr, dst_ip_buf, sizeof(dst_ip_buf)),
445                    packet->dst_port);
446         }
447
448 #ifndef WITH_UDPFROMTO
449         /*
450          *      Assume that the packet is encoded before sending it.
451          */
452         return sendto(packet->sockfd, packet->data, packet->data_len, 0,
453                       (struct sockaddr *)&dst, sizeof_dst);
454 #else
455
456         return sendfromto(packet->sockfd, packet->data, packet->data_len, 0,
457                           (struct sockaddr *)&src, sizeof_src,
458                           (struct sockaddr *)&dst, sizeof_dst);
459 #endif
460 }
461
462 static int fr_dhcp_attr2vp(VALUE_PAIR **vp_p, TALLOC_CTX *ctx, uint8_t const *p, size_t alen);
463
464 /** Returns the number of array members for arrays with fixed element sizes
465  *
466  */
467 static int fr_dhcp_array_members(size_t *len, DICT_ATTR const *da)
468 {
469         int num_entries = 1;
470
471         /*
472          *      Could be an array of bytes, integers, etc.
473          */
474         if (da->flags.array) switch (da->type) {
475         case PW_TYPE_BYTE:
476                 num_entries = *len;
477                 *len = 1;
478                 break;
479
480         case PW_TYPE_SHORT: /* ignore any trailing data */
481                 num_entries = *len >> 1;
482                 *len = 2;
483                 break;
484
485         case PW_TYPE_IPV4_ADDR:
486         case PW_TYPE_INTEGER:
487         case PW_TYPE_DATE: /* ignore any trailing data */
488                 num_entries = *len >> 2;
489                 *len = 4;
490                 break;
491
492         case PW_TYPE_IPV6_ADDR:
493                 num_entries = *len >> 4;
494                 *len = 16;
495                 break;
496
497         default:
498                 break;
499         }
500
501         return num_entries;
502 }
503
504 /** RFC 4243 Vendor Specific Suboptions
505  *
506  * Vendor specific suboptions are in the format.
507  @verbatim
508       0                   1                   2                   3
509       0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
510      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
511      |                     Enterprise Number 0                       |
512      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
513      |    Len 0      |                                               /
514      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
515      /                      Suboption Data 0                         /
516      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
517      |                     Enterprise Number n                       |
518      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
519      |    Len n      |                                               /
520      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
521      /                      Suboption Data n                         /
522      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
523  @endverbatim
524  *
525  * So although the vendor is identified, the format of the data isn't specified
526  * so we can't actually resolve the suboption to an attribute.
527  *
528  * To get around that, we create an attribute with a vendor matching the
529  * enterprise number, and attr 0.
530  *
531  * How the suboption data is then processed, is dependent on what type
532  * \<iana\>.0 is defined as in the dictionary.
533  *
534  * @param[in,out] tlv to decode. *tlv will be set to the head of the list of suboptions and original will be freed.
535  * @param[in] ctx context to alloc new attributes in.
536  * @param[in] data to parse.
537  * @param[in] len length of data to parse.
538  */
539 static int fr_dhcp_decode_vsa(VALUE_PAIR **tlv, TALLOC_CTX *ctx, uint8_t const *data, size_t len)
540 {
541         uint8_t const *p, *q;
542         vp_cursor_t cursor;
543
544         VALUE_PAIR *head;
545
546         if (len < 4) goto malformed;
547
548         p = data;
549         q = p + len;
550         while (p < q) {
551                 if (p + 5 >= q) goto malformed;
552                 p += sizeof(uint32_t);
553                 p += p[0];
554
555                 /*
556                  *      Check if length > the length of the buffer we have left
557                  */
558                 if (p >= q) goto malformed;
559                 p++;
560         }
561
562         head = NULL;
563         fr_cursor_init(&cursor, &head);
564
565         /*
566          *      Now we know its sane, start decoding!
567          */
568         p = data;
569         while (p < q) {
570                 uint32_t vendor;
571                 DICT_ATTR const *da;
572                 VALUE_PAIR *vp;
573
574                 vendor = ntohl(*((uint32_t const *) p));
575                 /*
576                  *      This is pretty much all we can do.  RFC 4243 doesn't specify
577                  *      an attribute field, so it's up to vendors to figure out how
578                  *      they want to encode their attributes.
579                  */
580                 da = dict_attrbyvalue(0, vendor);
581                 if (!da) {
582                         da = dict_attrunknown(0, vendor, true);
583                         if (!da) {
584                                 pairfree(&head);
585                                 goto malformed;
586                         }
587                 }
588                 vp = pairalloc(ctx, da);
589                 if (!vp) {
590                         pairfree(&head);
591                         return -1;
592                 }
593                 vp->op = T_OP_ADD;
594
595                 if (fr_dhcp_attr2vp(&vp, ctx, p + 5, p[4]) < 0) {
596                         pairfree(&head);
597                         return -1;
598                 }
599
600                 fr_cursor_insert(&cursor, vp);
601
602                 p += 4 + 1 + p[4];      /* vendor id (4) + len (1) + vsa len (n) */
603         }
604
605         /*
606          *      The caller allocated TLV, if decoding it generated additional
607          *      attributes, we now need to free it, and write the HEAD of our
608          *      new list of attributes in its place.
609          */
610         if (head) {
611                 vp_cursor_t tlv_cursor;
612
613                 /*
614                  *      Free the old TLV attribute
615                  */
616                 TALLOC_FREE(*tlv);
617
618                 /*
619                  *      Cursor not necessary but means we don't have to set
620                  *      ->next directly.
621                  */
622                 fr_cursor_init(&tlv_cursor, tlv);
623                 fr_cursor_insert(&tlv_cursor, head);
624         }
625
626         return 0;
627
628 malformed:
629         (*tlv)->vp_tlv = talloc_array(*tlv, uint8_t, len);
630         if (!(*tlv)->vp_tlv) {
631                 fr_strerror_printf("No memory");
632                 return -1;
633         }
634         memcpy((*tlv)->vp_tlv, data, len);
635         (*tlv)->length = len;
636
637         return 0;
638 }
639
640 /** Decode DHCP suboptions
641  *
642  * @param[in,out] tlv to decode. *tlv will be set to the head of the list of suboptions and original will be freed.
643  * @param[in] ctx context to alloc new attributes in.
644  * @param[in] data to parse.
645  * @param[in] len length of data to parse.
646  */
647 static int fr_dhcp_decode_suboption(VALUE_PAIR **tlv, TALLOC_CTX *ctx, uint8_t const *data, size_t len)
648 {
649         uint8_t const *p, *q;
650         VALUE_PAIR *head, *vp;
651         vp_cursor_t cursor;
652
653         /*
654          *      TLV must already point to a VALUE_PAIR.
655          */
656         VERIFY_VP(*tlv);
657
658         /*
659          *      Take a pass at parsing it.
660          */
661         p = data;
662         q = data + len;
663         while (p < q) {
664                 /*
665                  *      RFC 3046 is very specific about not allowing termination
666                  *      with a 255 sub-option. But it's required for decoding
667                  *      option 43, and vendors will probably screw it up
668                  *      anyway.
669                  */
670                 if (*p == 0) {
671                         p++;
672                         continue;
673                 }
674                 if (*p == 255) {
675                         q--;
676                         break;
677                 }
678
679                 /*
680                  *      Check if reading length would take us past the end of the buffer
681                  */
682                 if (++p >= q) goto malformed;
683                 p += p[0];
684
685                 /*
686                  *      Check if length > the length of the buffer we have left
687                  */
688                 if (p >= q) goto malformed;
689                 p++;
690         }
691
692         /*
693          *      Got here... must be well formed.
694          */
695         head = NULL;
696         fr_cursor_init(&cursor, &head);
697
698         p = data;
699         while (p < q) {
700                 uint8_t const   *a_p;
701                 size_t          a_len;
702                 int             num_entries, i;
703
704                 DICT_ATTR const *da;
705                 uint32_t        attr;
706
707                 /*
708                  *      The initial OID string looks like:
709                  *      <iana>.0
710                  *
711                  *      If <iana>.0 is type TLV then we attempt to decode its contents as more
712                  *      DHCP suboptions, which gives us:
713                  *      <iana>.<attr>
714                  *
715                  *      If <iana>.0 is not defined in the dictionary or is type octets, we leave
716                  *      the attribute as is.
717                  */
718                 attr = (*tlv)->da->attr ? ((*tlv)->da->attr | (p[0] << 8)) : p[0];
719
720                 /*
721                  *      Use the vendor of the parent TLV which is not necessarily
722                  *      DHCP_MAGIC_VENDOR.
723                  *
724                  *      Note: This does not deal with dictionary numbering clashes. If
725                  *      the vendor uses different numbers for DHCP suboptions and RADIUS
726                  *      attributes then it's time to break out %{hex:} and regular
727                  *      expressions.
728                  */
729                 da = dict_attrbyvalue(attr, (*tlv)->da->vendor);
730                 if (!da) {
731                         da = dict_attrunknown(attr, (*tlv)->da->vendor, true);
732                         if (!da) {
733                                 pairfree(&head);
734                                 return -1;
735                         }
736                 }
737
738                 a_len = p[1];
739                 a_p = p + 2;
740                 num_entries = fr_dhcp_array_members(&a_len, da);
741                 for (i = 0; i < num_entries; i++) {
742                         vp = pairalloc(ctx, da);
743                         if (!vp) {
744                                 pairfree(&head);
745                                 return -1;
746                         }
747                         vp->op = T_OP_ADD;
748
749                         if (fr_dhcp_attr2vp(&vp, ctx, a_p, a_len) < 0) {
750                                 pairfree(&head);
751                                 goto malformed;
752                         }
753                         fr_cursor_insert(&cursor, vp);
754
755                         a_p += a_len;
756                 }
757                 p += 2 + p[1];  /* code (1) + len (1) + suboption len (n)*/
758         }
759
760         /*
761          *      The caller allocated a TLV, if decoding it generated
762          *      additional attributes, we now need to free it, and write
763          *      the HEAD of our new list of attributes in its place.
764          */
765         if (head) {
766                 vp_cursor_t tlv_cursor;
767
768                 /*
769                  *      Free the old TLV attribute
770                  */
771                 TALLOC_FREE(*tlv);
772
773                 /*
774                  *      Cursor not necessary but means we don't have to set
775                  *      ->next directly.
776                  */
777                 fr_cursor_init(&tlv_cursor, tlv);
778                 fr_cursor_insert(&tlv_cursor, head);
779         }
780
781         return 0;
782
783 malformed:
784         (*tlv)->vp_tlv = talloc_array(*tlv, uint8_t, len);
785         if (!(*tlv)->vp_tlv) {
786                 fr_strerror_printf("No memory");
787                 return -1;
788         }
789         memcpy((*tlv)->vp_tlv, data, len);
790         (*tlv)->length = len;
791
792         return 0;
793 }
794
795 /*
796  *      Decode ONE value into a VP
797  */
798 static int fr_dhcp_attr2vp(VALUE_PAIR **vp_p, TALLOC_CTX *ctx, uint8_t const *data, size_t len)
799 {
800         VALUE_PAIR *vp = *vp_p;
801         VERIFY_VP(vp);
802
803         switch (vp->da->type) {
804         case PW_TYPE_BYTE:
805                 if (len != 1) goto raw;
806                 vp->vp_byte = data[0];
807                 break;
808
809         case PW_TYPE_SHORT:
810                 if (len != 2) goto raw;
811                 memcpy(&vp->vp_short, data, 2);
812                 vp->vp_short = ntohs(vp->vp_short);
813                 break;
814
815         case PW_TYPE_INTEGER:
816                 if (len != 4) goto raw;
817                 memcpy(&vp->vp_integer, data, 4);
818                 vp->vp_integer = ntohl(vp->vp_integer);
819                 break;
820
821         case PW_TYPE_IPV4_ADDR:
822                 if (len != 4) goto raw;
823                 /*
824                  *      Keep value in Network Order!
825                  */
826                 memcpy(&vp->vp_ipaddr, data, 4);
827                 vp->length = 4;
828                 break;
829
830         /*
831          *      In DHCPv4, string options which can also be arrays,
832          *      have their values '\0' delimited.
833          */
834         case PW_TYPE_STRING:
835         {
836                 uint8_t const *p;
837                 uint8_t const *q, *end;
838                 vp_cursor_t cursor;
839
840                 /*
841                  *      Initialise the cursor as we may be inserting
842                  *      multiple additional VPs
843                  */
844                 if (vp->da->flags.array) fr_cursor_init(&cursor, vp_p);
845
846                 p = data;
847                 q = end = data + len;
848                 for (;;) {
849                         if (vp->da->flags.array) {
850                                 q = memchr(p, '\0', q - p);
851                                 /* Malformed but recoverable */
852                                 if (!q) q = end;
853                         }
854
855                         pairstrncpy(vp, (char const *)p, q - p);
856                         p = q + 1;
857
858                         /* Need another VP for the next round */
859                         if (p < end) {
860                                 vp = pairalloc(ctx, vp->da);
861                                 if (!vp) {
862                                         pairfree(vp_p);
863                                         return -1;
864                                 }
865                                 fr_cursor_insert(&cursor, vp);
866                                 continue;
867                         }
868                         break;
869                 }
870         }
871                 break;
872
873         case PW_TYPE_ETHERNET:
874                 memcpy(vp->vp_ether, data, sizeof(vp->vp_ether));
875                 vp->length = sizeof(vp->vp_ether);
876                 break;
877
878         /*
879          *      Value doesn't match up with attribute type, overwrite the
880          *      vp's original DICT_ATTR with an unknown one.
881          */
882         raw:
883                 if (pair2unknown(vp) < 0) return -1;
884
885         case PW_TYPE_OCTETS:
886                 if (len > 255) return -1;
887                 pairmemcpy(vp, data, len);
888                 break;
889
890         /*
891          *      For option 82 et al...
892          */
893         case PW_TYPE_TLV:
894                 return fr_dhcp_decode_suboption(vp_p, ctx, data, len);
895
896         /*
897          *      For option 82.9
898          */
899         case PW_TYPE_VSA:
900                 return fr_dhcp_decode_vsa(vp_p, ctx, data, len);
901
902         default:
903                 fr_strerror_printf("Internal sanity check %d %d", vp->da->type, __LINE__);
904                 return -1;
905         } /* switch over type */
906
907         vp->length = len;
908         return 0;
909 }
910
911 /** Decode DHCP options
912  *
913  * @param[in,out] out Where to write the decoded options.
914  * @param[in] ctx context to alloc new attributes in.
915  * @param[in] data to parse.
916  * @param[in] len of data to parse.
917  */
918 ssize_t fr_dhcp_decode_options(VALUE_PAIR **out, TALLOC_CTX *ctx, uint8_t const *data, size_t len)
919 {
920         VALUE_PAIR *vp;
921         vp_cursor_t cursor;
922         uint8_t const *p, *q;
923
924         *out = NULL;
925         fr_cursor_init(&cursor, out);
926
927         /*
928          *      FIXME: This should also check sname && file fields.
929          *      See the dhcp_get_option() function above.
930          */
931         p = data;
932         q = data + len;
933         while (p < q) {
934                 uint8_t const   *a_p;
935                 size_t          a_len;
936                 int             num_entries, i;
937
938                 DICT_ATTR const *da;
939
940                 if (*p == 0) {          /* 0x00 - Padding option */
941                         p++;
942                         continue;
943                 }
944
945                 if (*p == 255) {        /* 0xff - End of options signifier */
946                         break;
947                 }
948
949                 if ((p + 2) > q) break;
950
951                 da = dict_attrbyvalue(p[0], DHCP_MAGIC_VENDOR);
952                 if (!da) {
953                         da = dict_attrunknown(p[0], DHCP_MAGIC_VENDOR, true);
954                         if (!da) {
955                                 pairfree(out);
956                                 return -1;
957                         }
958                         goto next;
959                 }
960
961                 a_len = p[1];
962                 a_p = p + 2;
963                 num_entries = fr_dhcp_array_members(&a_len, da);
964                 for (i = 0; i < num_entries; i++) {
965                         vp = pairalloc(ctx, da);
966                         if (!vp) {
967                                 pairfree(out);
968                                 return -1;
969                         }
970                         vp->op = T_OP_ADD;
971
972                         if (fr_dhcp_attr2vp(&vp, ctx, a_p, a_len) < 0) {
973                                 pairfree(&vp);
974                                 pairfree(out);
975                                 return -1;
976                         }
977                         fr_cursor_insert(&cursor, vp);
978
979                         for (vp = fr_cursor_current(&cursor);
980                              vp;
981                              vp = fr_cursor_next(&cursor)) {
982                                 debug_pair(vp);
983                         }
984                         a_p += a_len;
985                 } /* loop over array entries */
986         next:
987                 p += 2 + p[1];  /* code (1) + len (1) + option len (n)*/
988         } /* loop over the entire packet */
989
990         return p - data;
991 }
992
993 int fr_dhcp_decode(RADIUS_PACKET *packet)
994 {
995         size_t i;
996         uint8_t *p;
997         uint32_t giaddr;
998         vp_cursor_t cursor;
999         VALUE_PAIR *head = NULL, *vp;
1000         VALUE_PAIR *maxms, *mtu;
1001
1002         fr_cursor_init(&cursor, &head);
1003         p = packet->data;
1004
1005         if ((fr_debug_flag > 2) && fr_log_fp) {
1006                 for (i = 0; i < packet->data_len; i++) {
1007                         if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, "%d: ", (int) i);
1008                         fprintf(fr_log_fp, "%02x ", packet->data[i]);
1009                         if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1010                 }
1011                 fprintf(fr_log_fp, "\n");
1012         }
1013
1014         if (packet->data[1] != 1) {
1015                 fr_strerror_printf("Packet is not Ethernet: %u",
1016                       packet->data[1]);
1017                 return -1;
1018         }
1019
1020         /*
1021          *      Decode the header.
1022          */
1023         for (i = 0; i < 14; i++) {
1024                 char *q;
1025
1026                 vp = pairmake(packet, NULL, dhcp_header_names[i], NULL, T_OP_EQ);
1027                 if (!vp) {
1028                         char buffer[256];
1029                         strlcpy(buffer, fr_strerror(), sizeof(buffer));
1030                         fr_strerror_printf("Cannot decode packet due to internal error: %s", buffer);
1031                         pairfree(&head);
1032                         return -1;
1033                 }
1034
1035                 /*
1036                  *      If chaddr does != 6 bytes it's probably not ethernet, and we should store
1037                  *      it as an opaque type (octets).
1038                  */
1039                 if ((i == 11) && (packet->data[1] == 1) && (packet->data[2] != sizeof(vp->vp_ether))) {
1040                         DICT_ATTR const *da = dict_attrunknown(vp->da->attr, vp->da->vendor, true);
1041                         if (!da) {
1042                                 return -1;
1043                         }
1044                         vp->da = da;
1045                 }
1046
1047                 switch (vp->da->type) {
1048                 case PW_TYPE_BYTE:
1049                         vp->vp_byte = p[0];
1050                         vp->length = 1;
1051                         break;
1052
1053                 case PW_TYPE_SHORT:
1054                         vp->vp_short = (p[0] << 8) | p[1];
1055                         vp->length = 2;
1056                         break;
1057
1058                 case PW_TYPE_INTEGER:
1059                         memcpy(&vp->vp_integer, p, 4);
1060                         vp->vp_integer = ntohl(vp->vp_integer);
1061                         vp->length = 4;
1062                         break;
1063
1064                 case PW_TYPE_IPV4_ADDR:
1065                         memcpy(&vp->vp_ipaddr, p, 4);
1066                         vp->length = 4;
1067                         break;
1068
1069                 case PW_TYPE_STRING:
1070                         vp->vp_strvalue = q = talloc_array(vp, char, dhcp_header_sizes[i] + 1);
1071                         vp->type = VT_DATA;
1072                         memcpy(q, p, dhcp_header_sizes[i]);
1073                         q[dhcp_header_sizes[i]] = '\0';
1074                         vp->length = strlen(vp->vp_strvalue);
1075                         if (vp->length == 0) {
1076                                 pairfree(&vp);
1077                         }
1078                         break;
1079
1080                 case PW_TYPE_OCTETS:
1081                         pairmemcpy(vp, p, packet->data[2]);
1082                         break;
1083
1084                 case PW_TYPE_ETHERNET:
1085                         memcpy(vp->vp_ether, p, sizeof(vp->vp_ether));
1086                         vp->length = sizeof(vp->vp_ether);
1087                         break;
1088
1089                 default:
1090                         fr_strerror_printf("BAD TYPE %d", vp->da->type);
1091                         pairfree(&vp);
1092                         break;
1093                 }
1094                 p += dhcp_header_sizes[i];
1095
1096                 if (!vp) continue;
1097
1098                 debug_pair(vp);
1099                 fr_cursor_insert(&cursor, vp);
1100         }
1101
1102         /*
1103          *      Loop over the options.
1104          */
1105
1106         /*
1107          *      Nothing uses tail after this call, if it does in the future
1108          *      it'll need to find the new tail...
1109          */
1110         {
1111                 VALUE_PAIR *options = NULL;
1112
1113                 if (fr_dhcp_decode_options(&options, packet, packet->data + 240, packet->data_len - 240) < 0) {
1114                         return -1;
1115                 }
1116
1117                 if (options) {
1118                         fr_cursor_insert(&cursor, options);
1119                 }
1120         }
1121
1122         /*
1123          *      If DHCP request, set ciaddr to zero.
1124          */
1125
1126         /*
1127          *      Set broadcast flag for broken vendors, but only if
1128          *      giaddr isn't set.
1129          */
1130         memcpy(&giaddr, packet->data + 24, sizeof(giaddr));
1131         if (giaddr == htonl(INADDR_ANY)) {
1132                 /*
1133                  *      DHCP Opcode is request
1134                  */
1135                 vp = pairfind(head, 256, DHCP_MAGIC_VENDOR, TAG_ANY);
1136                 if (vp && vp->vp_integer == 3) {
1137                         /*
1138                          *      Vendor is "MSFT 98"
1139                          */
1140                         vp = pairfind(head, 63, DHCP_MAGIC_VENDOR, TAG_ANY);
1141                         if (vp && (strcmp(vp->vp_strvalue, "MSFT 98") == 0)) {
1142                                 vp = pairfind(head, 262, DHCP_MAGIC_VENDOR, TAG_ANY);
1143
1144                                 /*
1145                                  *      Reply should be broadcast.
1146                                  */
1147                                 if (vp) vp->vp_integer |= 0x8000;
1148                                 packet->data[10] |= 0x80;
1149                         }
1150                 }
1151         }
1152
1153         /*
1154          *      FIXME: Nuke attributes that aren't used in the normal
1155          *      header for discover/requests.
1156          */
1157         packet->vps = head;
1158
1159         /*
1160          *      Client can request a LARGER size, but not a smaller
1161          *      one.  They also cannot request a size larger than MTU.
1162          */
1163         maxms = pairfind(packet->vps, 57, DHCP_MAGIC_VENDOR, TAG_ANY);
1164         mtu = pairfind(packet->vps, 26, DHCP_MAGIC_VENDOR, TAG_ANY);
1165
1166         if (mtu && (mtu->vp_integer < DEFAULT_PACKET_SIZE)) {
1167                 fr_strerror_printf("DHCP Fatal: Client says MTU is smaller than minimum permitted by the specification");
1168                 return -1;
1169         }
1170
1171         if (maxms && (maxms->vp_integer < DEFAULT_PACKET_SIZE)) {
1172                 fr_strerror_printf("DHCP WARNING: Client says maximum message size is smaller than minimum permitted by the specification: fixing it");
1173                 maxms->vp_integer = DEFAULT_PACKET_SIZE;
1174         }
1175
1176         if (maxms && mtu && (maxms->vp_integer > mtu->vp_integer)) {
1177                 fr_strerror_printf("DHCP WARNING: Client says MTU is smaller than maximum message size: fixing it");
1178                 maxms->vp_integer = mtu->vp_integer;
1179         }
1180
1181         if (fr_debug_flag) fflush(stdout);
1182
1183         return 0;
1184 }
1185
1186
1187 int8_t fr_dhcp_attr_cmp(void const *a, void const *b)
1188 {
1189         VALUE_PAIR const *my_a = a;
1190         VALUE_PAIR const *my_b = b;
1191
1192         VERIFY_VP(my_a);
1193         VERIFY_VP(my_b);
1194
1195         /*
1196          *      DHCP-Message-Type is first, for simplicity.
1197          */
1198         if ((my_a->da->attr == 53) && (my_b->da->attr != 53)) return -1;
1199
1200         /*
1201          *      Relay-Agent is last
1202          */
1203         if ((my_a->da->attr == 82) && (my_b->da->attr != 82)) return 1;
1204
1205         if (my_a->da->attr < my_b->da->attr) return -1;
1206         if (my_a->da->attr > my_b->da->attr) return 1;
1207
1208         return 0;
1209 }
1210
1211 /** Write DHCP option value into buffer
1212  *
1213  * Does not include DHCP option length or number.
1214  *
1215  * @param out where to write the DHCP option.
1216  * @param outlen length of output buffer.
1217  * @param vp option to encode.
1218  * @return the length of data writen, -1 if out of buffer, -2 if unsupported type.
1219  */
1220 static ssize_t fr_dhcp_vp2attr(uint8_t *out, size_t outlen, VALUE_PAIR *vp)
1221 {
1222         uint32_t lvalue;
1223         uint8_t *p = out;
1224
1225         if (outlen < vp->length) {
1226                 return -1;
1227         }
1228
1229         switch (vp->da->type) {
1230         case PW_TYPE_BYTE:
1231                 *p = vp->vp_byte;
1232                 break;
1233
1234         case PW_TYPE_SHORT:
1235                 p[0] = (vp->vp_short >> 8) & 0xff;
1236                 p[1] = vp->vp_short & 0xff;
1237                 break;
1238
1239         case PW_TYPE_INTEGER:
1240                 lvalue = htonl(vp->vp_integer);
1241                 memcpy(p, &lvalue, 4);
1242                 break;
1243
1244         case PW_TYPE_IPV4_ADDR:
1245                 memcpy(p, &vp->vp_ipaddr, 4);
1246                 break;
1247
1248         case PW_TYPE_ETHERNET:
1249                 memcpy(p, &vp->vp_ether, 6);
1250                 break;
1251
1252         case PW_TYPE_STRING:
1253                 memcpy(p, vp->vp_strvalue, vp->length);
1254                 break;
1255
1256         case PW_TYPE_TLV:       /* FIXME: split it on 255? */
1257                 memcpy(p, vp->vp_tlv, vp->length);
1258                 break;
1259
1260         case PW_TYPE_OCTETS:
1261                 memcpy(p, vp->vp_octets, vp->length);
1262                 break;
1263
1264         default:
1265                 fr_strerror_printf("Unsupported option type %d", vp->da->type);
1266                 return -2;
1267         }
1268
1269         return vp->length;
1270 }
1271
1272 /** Create a new TLV attribute from multiple sub options
1273  *
1274  * @param[in,out] ctx to allocate new attribute in.
1275  * @param[in,out] cursor should be set to the start of the list of TLV attributes.
1276  *   Will be advanced to the first non-TLV attribute.
1277  * @return attribute holding the concatenation of the values of the sub options.
1278  */
1279 static VALUE_PAIR *fr_dhcp_vp2suboption(TALLOC_CTX *ctx, vp_cursor_t *cursor)
1280 {
1281         ssize_t length;
1282         unsigned int parent;    /* Parent attribute of suboption */
1283         uint8_t attr = 0;
1284         uint8_t *p, *opt_len = NULL;
1285         vp_cursor_t to_pack;
1286         VALUE_PAIR *vp, *tlv;
1287
1288 #define SUBOPTION_PARENT(_x) (_x & 0xffff00ff)
1289 #define SUBOPTION_ATTR(_x) ((_x & 0xff00) >> 8)
1290
1291         vp = fr_cursor_current(cursor);
1292         if (!vp) return NULL;
1293
1294         parent = SUBOPTION_PARENT(vp->da->attr);
1295         tlv = paircreate(ctx, parent, DHCP_MAGIC_VENDOR);
1296         if (!tlv) return NULL;
1297
1298         fr_cursor_copy(&to_pack, cursor);
1299
1300         /*
1301          *  Loop over TLVs to determine how much memory we need to allocate
1302          *
1303          *  We advanced the cursor we were passed, so if we fail encoding,
1304          *  the cursor is at the right position for the next potentially
1305          *  encodable attr.
1306          */
1307         for (vp = fr_cursor_current(cursor);
1308              vp && vp->da->flags.is_tlv && !vp->da->flags.extended && (SUBOPTION_PARENT(vp->da->attr) == parent);
1309              vp = fr_cursor_next(cursor)) {
1310                 /*
1311                  *  If it's not an array type or is an array type, but is not the same
1312                  *  as the previous attribute, we add 2 for the additional sub-option
1313                  *  header bytes.
1314                  */
1315                 if (!vp->da->flags.array || (SUBOPTION_ATTR(vp->da->attr) != attr)) {
1316                         attr = SUBOPTION_ATTR(vp->da->attr);
1317                         tlv->length += 2;
1318                 }
1319                 tlv->length += vp->length;
1320         }
1321
1322         tlv->vp_tlv = talloc_array(tlv, uint8_t, tlv->length);
1323         if (!tlv->vp_tlv) {
1324                 talloc_free(tlv);
1325                 return NULL;
1326         }
1327         p = tlv->vp_tlv;
1328
1329         attr = 0;
1330         for (vp = fr_cursor_current(&to_pack);
1331              vp && vp->da->flags.is_tlv && !vp->da->flags.extended && (SUBOPTION_PARENT(vp->da->attr) == parent);
1332              vp = fr_cursor_next(&to_pack)) {
1333                 if (SUBOPTION_ATTR(vp->da->attr) == 0) {
1334                         fr_strerror_printf("Invalid attribute number 0");
1335                         return NULL;
1336                 }
1337
1338                 /* Don't write out the header, were packing array options */
1339                 if (!vp->da->flags.array || (attr != SUBOPTION_ATTR(vp->da->attr))) {
1340                         attr = SUBOPTION_ATTR(vp->da->attr);
1341                         *p++ = attr;
1342                         opt_len = p++;
1343                 }
1344
1345                 length = fr_dhcp_vp2attr(p, (tlv->vp_tlv + tlv->length) - p, vp);
1346                 if ((length < 0) || (length > 255)) {
1347                         talloc_free(tlv);
1348                         return NULL;
1349                 }
1350
1351                 fr_assert(opt_len);
1352                 *opt_len += length;
1353                 p += length;
1354         };
1355
1356         return tlv;
1357 }
1358
1359 /** Encode a DHCP option and any sub-options.
1360  *
1361  * @param out Where to write encoded DHCP attributes.
1362  * @param outlen Length of out buffer.
1363  * @param ctx to use for any allocated memory.
1364  * @param cursor with current VP set to the option to be encoded. Will be advanced to the next option to encode.
1365  * @return > 0 length of data written, < 0 error, 0 not valid option (skipping).
1366  */
1367 ssize_t fr_dhcp_encode_option(uint8_t *out, size_t outlen, TALLOC_CTX *ctx, vp_cursor_t *cursor)
1368 {
1369         VALUE_PAIR *vp;
1370         DICT_ATTR const *previous;
1371         uint8_t *opt_len, *p = out;
1372         size_t freespace = outlen;
1373         ssize_t len;
1374
1375         vp = fr_cursor_current(cursor);
1376         if (!vp) return -1;
1377
1378         if (vp->da->vendor != DHCP_MAGIC_VENDOR) goto next; /* not a DHCP option */
1379         if (vp->da->attr == 53) goto next; /* already done */
1380         if ((vp->da->attr > 255) && (DHCP_BASE_ATTR(vp->da->attr) != PW_DHCP_OPTION_82)) goto next;
1381
1382         if (vp->da->flags.extended) {
1383         next:
1384                 fr_strerror_printf("Attribute \"%s\" is not a DHCP option", vp->da->name);
1385                 fr_cursor_next(cursor);
1386                 return 0;
1387         }
1388
1389         /* Write out the option number */
1390         *(p++) = vp->da->attr & 0xff;
1391
1392         /* Pointer to the length field of the option */
1393         opt_len = p++;
1394
1395         /* Zero out the option's length field */
1396         *opt_len = 0;
1397
1398         /* We just consumed two bytes for the header */
1399         freespace -= 2;
1400
1401         /* DHCP options with the same number get coalesced into a single option */
1402         do {
1403                 VALUE_PAIR *tlv = NULL;
1404
1405                 /* Sub option */
1406                 if (vp->da->flags.is_tlv) {
1407                         /*
1408                          *  Coalesce TLVs into one sub-option.
1409                          *  Cursor will be advanced to next non-TLV attribute.
1410                          */
1411                         tlv = vp = fr_dhcp_vp2suboption(ctx, cursor);
1412
1413                         /*
1414                          *  Skip if there's an issue coalescing the sub-options.
1415                          *  Cursor will still have been advanced to next non-TLV attribute.
1416                          */
1417                         if (!tlv) return 0;
1418                 /*
1419                  *  If not calling fr_dhcp_vp2suboption() advance the cursor, so fr_cursor_current()
1420                  *  returns the next attribute.
1421                  */
1422                 } else {
1423                         fr_cursor_next(cursor);
1424                 }
1425
1426                 if ((*opt_len + vp->length) > 255) {
1427                         fr_strerror_printf("Skipping \"%s\": Option splitting not supported "
1428                                            "(option > 255 bytes)", vp->da->name);
1429                         talloc_free(tlv);
1430                         return 0;
1431                 }
1432
1433                 len = fr_dhcp_vp2attr(p, freespace, vp);
1434                 talloc_free(tlv);
1435                 if (len < 0) {
1436                         /* Failed encoding option */
1437                         return len;
1438                 }
1439
1440                 p += len;
1441                 *opt_len += len;
1442                 freespace -= len;
1443
1444                 previous = vp->da;
1445         } while ((vp = fr_cursor_current(cursor)) && (previous == vp->da) && vp->da->flags.array);
1446
1447         return p - out;
1448 }
1449
1450 int fr_dhcp_encode(RADIUS_PACKET *packet)
1451 {
1452         unsigned int i;
1453         uint8_t *p;
1454         vp_cursor_t cursor;
1455         VALUE_PAIR *vp;
1456         uint32_t lvalue;
1457         size_t dhcp_size;
1458         ssize_t len;
1459 #ifndef NDEBUG
1460         char const *name;
1461 #  ifdef WITH_UDPFROMTO
1462         char src_ip_buf[256];
1463 #  endif
1464         char dst_ip_buf[256];
1465 #endif
1466
1467         if (packet->data) return 0;
1468
1469         packet->data_len = MAX_PACKET_SIZE;
1470         packet->data = talloc_zero_array(packet, uint8_t, packet->data_len);
1471
1472         /* XXX Ugly ... should be set by the caller */
1473         if (packet->code == 0) packet->code = PW_DHCP_NAK;
1474
1475 #ifndef NDEBUG
1476         if ((packet->code >= PW_DHCP_DISCOVER) &&
1477             (packet->code <= PW_DHCP_INFORM)) {
1478                 name = dhcp_message_types[packet->code - PW_DHCP_OFFSET];
1479         } else {
1480                 name = "?Unknown?";
1481         }
1482
1483         DEBUG(
1484 #  ifdef WITH_UDPFROMTO
1485               "Encoding %s of id %08x from %s:%d to %s:%d\n",
1486 #  else
1487               "Encoding %s of id %08x to %s:%d\n",
1488 #  endif
1489               name, (unsigned int) packet->id,
1490 #  ifdef WITH_UDPFROMTO
1491               inet_ntop(packet->src_ipaddr.af,
1492                         &packet->src_ipaddr.ipaddr,
1493                         src_ip_buf, sizeof(src_ip_buf)),
1494               packet->src_port,
1495 #  endif
1496               inet_ntop(packet->dst_ipaddr.af,
1497                         &packet->dst_ipaddr.ipaddr,
1498                      dst_ip_buf, sizeof(dst_ip_buf)),
1499               packet->dst_port);
1500 #endif
1501
1502         p = packet->data;
1503
1504         /*
1505          *      @todo: Make this work again.
1506          */
1507 #if 0
1508         mms = DEFAULT_PACKET_SIZE; /* maximum message size */
1509
1510         /*
1511          *      Clients can request a LARGER size, but not a
1512          *      smaller one.  They also cannot request a size
1513          *      larger than MTU.
1514          */
1515
1516         /* DHCP-DHCP-Maximum-Msg-Size */
1517         vp = pairfind(packet->vps, 57, DHCP_MAGIC_VENDOR, TAG_ANY);
1518         if (vp && (vp->vp_integer > mms)) {
1519                 mms = vp->vp_integer;
1520
1521                 if (mms > MAX_PACKET_SIZE) mms = MAX_PACKET_SIZE;
1522         }
1523 #endif
1524
1525         vp = pairfind(packet->vps, 256, DHCP_MAGIC_VENDOR, TAG_ANY);
1526         if (vp) {
1527                 *p++ = vp->vp_integer & 0xff;
1528         } else {
1529                 *p++ = 1;       /* client message */
1530         }
1531
1532         /* DHCP-Hardware-Type */
1533         if ((vp = pairfind(packet->vps, 257, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1534                 *p++ = vp->vp_integer & 0xFF;
1535         } else {
1536                 *p++ = 1;               /* hardware type = ethernet */
1537         }
1538
1539         /* DHCP-Hardware-Address-Length */
1540         if ((vp = pairfind(packet->vps, 258, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1541                 *p++ = vp->vp_integer & 0xFF;
1542         } else {
1543                 *p++ = 6;               /* 6 bytes of ethernet */
1544         }
1545
1546         /* DHCP-Hop-Count */
1547         if ((vp = pairfind(packet->vps, 259, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1548                 *p = vp->vp_integer & 0xff;
1549         }
1550         p++;
1551
1552         /* DHCP-Transaction-Id */
1553         if ((vp = pairfind(packet->vps, 260, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1554                 lvalue = htonl(vp->vp_integer);
1555         } else {
1556                 lvalue = fr_rand();
1557         }
1558         memcpy(p, &lvalue, 4);
1559         p += 4;
1560
1561         /* DHCP-Number-of-Seconds */
1562         if ((vp = pairfind(packet->vps, 261, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1563                 lvalue = htonl(vp->vp_integer);
1564                 memcpy(p, &lvalue, 2);
1565         }
1566         p += 2;
1567
1568         /* DHCP-Flags */
1569         if ((vp = pairfind(packet->vps, 262, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1570                 lvalue = htons(vp->vp_integer);
1571                 memcpy(p, &lvalue, 2);
1572         }
1573         p += 2;
1574
1575         /* DHCP-Client-IP-Address */
1576         if ((vp = pairfind(packet->vps, 263, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1577                 memcpy(p, &vp->vp_ipaddr, 4);
1578         }
1579         p += 4;
1580
1581         /* DHCP-Your-IP-address */
1582         if ((vp = pairfind(packet->vps, 264, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1583                 lvalue = vp->vp_ipaddr;
1584         } else {
1585                 lvalue = htonl(INADDR_ANY);
1586         }
1587         memcpy(p, &lvalue, 4);
1588         p += 4;
1589
1590         /* DHCP-Server-IP-Address */
1591         vp = pairfind(packet->vps, 265, DHCP_MAGIC_VENDOR, TAG_ANY);
1592
1593         /* DHCP-DHCP-Server-Identifier */
1594         if (!vp && (vp = pairfind(packet->vps, 54, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1595                 lvalue = vp->vp_ipaddr;
1596         } else {
1597                 lvalue = htonl(INADDR_ANY);
1598         }
1599         memcpy(p, &lvalue, 4);
1600         p += 4;
1601
1602         /*
1603          *      DHCP-Gateway-IP-Address
1604          */
1605         if ((vp = pairfind(packet->vps, 266, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1606                 lvalue = vp->vp_ipaddr;
1607         } else {
1608                 lvalue = htonl(INADDR_ANY);
1609         }
1610         memcpy(p, &lvalue, 4);
1611         p += 4;
1612
1613         /* DHCP-Client-Hardware-Address */
1614         if ((vp = pairfind(packet->vps, 267, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1615                 if (vp->length == sizeof(vp->vp_ether)) {
1616                         memcpy(p, vp->vp_ether, vp->length);
1617                 } /* else ignore it */
1618         }
1619         p += DHCP_CHADDR_LEN;
1620
1621         /* DHCP-Server-Host-Name */
1622         if ((vp = pairfind(packet->vps, 268, DHCP_MAGIC_VENDOR, TAG_ANY))) {
1623                 if (vp->length > DHCP_SNAME_LEN) {
1624                         memcpy(p, vp->vp_strvalue, DHCP_SNAME_LEN);
1625                 } else {
1626                         memcpy(p, vp->vp_strvalue, vp->length);
1627                 }
1628         }
1629         p += DHCP_SNAME_LEN;
1630
1631         /*
1632          *      Copy over DHCP-Boot-Filename.
1633          *
1634          *      FIXME: This copy should be delayed until AFTER the options
1635          *      have been processed.  If there are too many options for
1636          *      the packet, then they go into the sname && filename fields.
1637          *      When that happens, the boot filename is passed as an option,
1638          *      instead of being placed verbatim in the filename field.
1639          */
1640
1641         /* DHCP-Boot-Filename */
1642         vp = pairfind(packet->vps, 269, DHCP_MAGIC_VENDOR, TAG_ANY);
1643         if (vp) {
1644                 if (vp->length > DHCP_FILE_LEN) {
1645                         memcpy(p, vp->vp_strvalue, DHCP_FILE_LEN);
1646                 } else {
1647                         memcpy(p, vp->vp_strvalue, vp->length);
1648                 }
1649         }
1650         p += DHCP_FILE_LEN;
1651
1652         /* DHCP magic number */
1653         lvalue = htonl(DHCP_OPTION_MAGIC_NUMBER);
1654         memcpy(p, &lvalue, 4);
1655         p += 4;
1656
1657         /*
1658          *      Print the header.
1659          */
1660         if (fr_debug_flag > 1) {
1661                 uint8_t *pp = p;
1662
1663                 p = packet->data;
1664
1665                 for (i = 0; i < 14; i++) {
1666                         char *q;
1667
1668                         vp = pairmake(packet, NULL,
1669                                       dhcp_header_names[i], NULL, T_OP_EQ);
1670                         if (!vp) {
1671                                 char buffer[256];
1672                                 strlcpy(buffer, fr_strerror(), sizeof(buffer));
1673                                 fr_strerror_printf("Cannot decode packet due to internal error: %s", buffer);
1674                                 return -1;
1675                         }
1676
1677                         switch (vp->da->type) {
1678                         case PW_TYPE_BYTE:
1679                                 vp->vp_byte = p[0];
1680                                 break;
1681
1682                         case PW_TYPE_SHORT:
1683                                 vp->vp_short = (p[0] << 8) | p[1];
1684                                 break;
1685
1686                         case PW_TYPE_INTEGER:
1687                                 memcpy(&vp->vp_integer, p, 4);
1688                                 vp->vp_integer = ntohl(vp->vp_integer);
1689                                 break;
1690
1691                         case PW_TYPE_IPV4_ADDR:
1692                                 memcpy(&vp->vp_ipaddr, p, 4);
1693                                 break;
1694
1695                         case PW_TYPE_STRING:
1696                                 vp->vp_strvalue = q = talloc_array(vp, char, dhcp_header_sizes[i] + 1);
1697                                 vp->type = VT_DATA;
1698                                 memcpy(q, p, dhcp_header_sizes[i]);
1699                                 q[dhcp_header_sizes[i]] = '\0';
1700                                 vp->length = strlen(vp->vp_strvalue);
1701                                 break;
1702
1703                         case PW_TYPE_OCTETS: /* only for Client HW Address */
1704                                 pairmemcpy(vp, p, packet->data[2]);
1705                                 break;
1706
1707                         case PW_TYPE_ETHERNET: /* only for Client HW Address */
1708                                 memcpy(vp->vp_ether, p, sizeof(vp->vp_ether));
1709                                 break;
1710
1711                         default:
1712                                 fr_strerror_printf("Internal sanity check failed %d %d", vp->da->type, __LINE__);
1713                                 pairfree(&vp);
1714                                 break;
1715                         }
1716
1717                         p += dhcp_header_sizes[i];
1718
1719                         debug_pair(vp);
1720                         pairfree(&vp);
1721                 }
1722
1723                 /*
1724                  *      Jump over DHCP magic number, response, etc.
1725                  */
1726                 p = pp;
1727         }
1728
1729         p[0] = 0x35;            /* DHCP-Message-Type */
1730         p[1] = 1;
1731         p[2] = packet->code - PW_DHCP_OFFSET;
1732         p += 3;
1733
1734
1735         /*
1736          *  Pre-sort attributes into contiguous blocks so that fr_dhcp_encode_option
1737          *  operates correctly. This changes the order of the list, but never mind...
1738          */
1739         pairsort(&packet->vps, fr_dhcp_attr_cmp);
1740         fr_cursor_init(&cursor, &packet->vps);
1741
1742         /*
1743          *  Each call to fr_dhcp_encode_option will encode one complete DHCP option,
1744          *  and sub options.
1745          */
1746         while ((vp = fr_cursor_current(&cursor))) {
1747                 len = fr_dhcp_encode_option(p, packet->data_len - (p - packet->data), packet, &cursor);
1748                 if (len < 0) break;
1749                 if (len > 0) debug_pair(vp);
1750                 p += len;
1751         };
1752
1753         p[0] = 0xff;            /* end of option option */
1754         p[1] = 0x00;
1755         p += 2;
1756         dhcp_size = p - packet->data;
1757
1758         /*
1759          *      FIXME: if (dhcp_size > mms),
1760          *        then we put the extra options into the "sname" and "file"
1761          *        fields, AND set the "end option option" in the "options"
1762          *        field.  We also set the "overload option",
1763          *        and put options into the "file" field, followed by
1764          *        the "sname" field.  Where each option is completely
1765          *        enclosed in the "file" and/or "sname" field, AND
1766          *        followed by the "end of option", and MUST be followed
1767          *        by padding option.
1768          *
1769          *      Yuck.  That sucks...
1770          */
1771         packet->data_len = dhcp_size;
1772
1773         if (packet->data_len < DEFAULT_PACKET_SIZE) {
1774                 memset(packet->data + packet->data_len, 0,
1775                        DEFAULT_PACKET_SIZE - packet->data_len);
1776                 packet->data_len = DEFAULT_PACKET_SIZE;
1777         }
1778
1779         if ((fr_debug_flag > 2) && fr_log_fp) {
1780                 fprintf(fr_log_fp, "DHCP Sending %zu bytes\n", packet->data_len);
1781                 for (i = 0; i < packet->data_len; i++) {
1782                         if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, "%d: ", i);
1783                         fprintf(fr_log_fp, "%02x ", packet->data[i]);
1784                         if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1785                 }
1786                 fprintf(fr_log_fp, "\n");
1787         }
1788
1789         return 0;
1790 }
1791
1792 #ifdef SIOCSARP
1793 int fr_dhcp_add_arp_entry(int fd, char const *interface,
1794                           VALUE_PAIR *macaddr, VALUE_PAIR *ip)
1795 {
1796         struct sockaddr_in *sin;
1797         struct arpreq req;
1798
1799         if (!interface) {
1800                 fr_strerror_printf("No interface specified.  Cannot update ARP table");
1801                 return -1;
1802         }
1803
1804         if (!fr_assert(macaddr) ||
1805             !fr_assert((macaddr->da->type == PW_TYPE_ETHERNET) || (macaddr->da->type == PW_TYPE_OCTETS))) {
1806                 fr_strerror_printf("Wrong VP type (%s) for chaddr",
1807                                    fr_int2str(dict_attr_types, macaddr->da->type, "<invalid>"));
1808                 return -1;
1809         }
1810
1811         if (macaddr->length > sizeof(req.arp_ha.sa_data)) {
1812                 fr_strerror_printf("arp sa_data field too small (%zu octets) to contain chaddr (%zu octets)",
1813                                    sizeof(req.arp_ha.sa_data), macaddr->length);
1814                 return -1;
1815         }
1816
1817         memset(&req, 0, sizeof(req));
1818         sin = (struct sockaddr_in *) &req.arp_pa;
1819         sin->sin_family = AF_INET;
1820         sin->sin_addr.s_addr = ip->vp_ipaddr;
1821
1822         strlcpy(req.arp_dev, interface, sizeof(req.arp_dev));
1823
1824         if (macaddr->da->type == PW_TYPE_ETHERNET) {
1825                 memcpy(&req.arp_ha.sa_data, &macaddr->vp_ether, sizeof(macaddr->vp_ether));
1826         } else {
1827                 memcpy(&req.arp_ha.sa_data, macaddr->vp_octets, macaddr->length);
1828         }
1829
1830         req.arp_flags = ATF_COM;
1831         if (ioctl(fd, SIOCSARP, &req) < 0) {
1832                 fr_strerror_printf("Failed to add entry in ARP cache: %s (%d)", fr_syserror(errno), errno);
1833                 return -1;
1834         }
1835
1836         return 0;
1837 }
1838 #else
1839 int fr_dhcp_add_arp_entry(UNUSED int fd, UNUSED char const *interface,
1840                           UNUSED VALUE_PAIR *macaddr, UNUSED VALUE_PAIR *ip)
1841 {
1842         fr_strerror_printf("Adding ARP entry is unsupported on this system");
1843         return -1;
1844 }
1845 #endif