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