aboutsummaryrefslogtreecommitdiff
path: root/server/dhcpleasequery.c
blob: 09913c24bdf3d7e074070b88c9b51d2380c72adc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
/*
 * Copyright (C) 2011-2012 by Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 2006-2007,2009 by Internet Systems Consortium, Inc. ("ISC")
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#include "dhcpd.h"

/*
 * TODO: RFC4388 specifies that the server SHOULD return the same
 *       options it would for a DHCREQUEST message, if no Parameter
 *       Request List option (option 55) is passed. We do not do that.
 *
 * TODO: RFC4388 specifies the creation of a "non-sensitive options"
 *       configuration list, and that these SHOULD be returned. We
 *       have no such list.
 *
 * TODO: RFC4388 says the server SHOULD use RFC3118, "Authentication
 *       for DHCP Messages".
 *
 * TODO: RFC4388 specifies that you SHOULD insure that you cannot be
 *       DoS'ed by DHCPLEASEQUERY message.
 */

/* 
 * If you query by hardware address or by client ID, then you may have
 * more than one IP address for your query argument. We need to do two
 * things:
 *
 *   1. Find the most recent lease.
 *   2. Find all additional IP addresses for the query argument.
 *
 * We do this by looking through all of the leases associated with a
 * given hardware address or client ID. We use the cltt (client last
 * transaction time) of the lease, which only has a resolution of one
 * second, so we might not actually give the very latest IP.
 */

static struct lease*
next_hw(const struct lease *lease) {
	/* INSIST(lease != NULL); */
	return lease->n_hw;
}

static struct lease*
next_uid(const struct lease *lease) {
	/* INSIST(lease != NULL); */
	return lease->n_uid;
}

void
get_newest_lease(struct lease **retval,
		 struct lease *lease,
		 struct lease *(*next)(const struct lease *)) {

	struct lease *p;
	struct lease *newest;

	/* INSIST(newest != NULL); */
	/* INSIST(next != NULL); */

	*retval = NULL;

	if (lease == NULL) {
		return;
	}

	newest = lease;
	for (p=next(lease); p != NULL; p=next(p)) {
		if (newest->binding_state == FTS_ACTIVE) {
			if ((p->binding_state == FTS_ACTIVE) && 
		    	(p->cltt > newest->cltt)) {
				newest = p;
			}
		} else {
			if (p->ends > newest->ends) {
				newest = p;
			}
		}
	}

	lease_reference(retval, newest, MDL);
}

static int
get_associated_ips(const struct lease *lease,
		   struct lease *(*next)(const struct lease *), 
		   const struct lease *newest,
		   u_int32_t *associated_ips,
		   unsigned int associated_ips_size) {

	const struct lease *p;
	int cnt;

	/* INSIST(next != NULL); */
	/* INSIST(associated_ips != NULL); */

	if (lease == NULL) {
		return 0;
	}

	cnt = 0;
	for (p=lease; p != NULL; p=next(p)) {
		if ((p->binding_state == FTS_ACTIVE) && (p != newest)) {
			if (cnt < associated_ips_size) {
				memcpy(&associated_ips[cnt],
				       p->ip_addr.iabuf,
				       sizeof(associated_ips[cnt]));
			}
			cnt++;
		}
	}
	return cnt;
}


void 
dhcpleasequery(struct packet *packet, int ms_nulltp) {
	char msgbuf[256];
	char dbg_info[128];
	struct iaddr cip;
	struct iaddr gip;
	struct data_string uid;
	struct hardware h;
	struct lease *tmp_lease;
	struct lease *lease;
	int want_associated_ip;
	int assoc_ip_cnt;
	u_int32_t assoc_ips[40];  /* XXXSK: arbitrary maximum number of IPs */
	const int nassoc_ips = sizeof(assoc_ips) / sizeof(assoc_ips[0]);

	unsigned char dhcpMsgType;
	const char *dhcp_msg_type_name;
	struct subnet *subnet;
	struct group *relay_group;
	struct option_state *options;
	struct option_cache *oc;
	int allow_leasequery;
	int ignorep;
	u_int32_t lease_duration;
	u_int32_t time_renewal;
	u_int32_t time_rebinding;
	u_int32_t time_expiry;
	u_int32_t client_last_transaction_time;
	struct sockaddr_in to;
	struct in_addr siaddr;
	struct data_string prl;
	struct data_string *prl_ptr;

	int i;
	struct interface_info *interface;

	/* INSIST(packet != NULL); */

	/*
	 * Prepare log information.
	 */
	snprintf(msgbuf, sizeof(msgbuf), 
		"DHCPLEASEQUERY from %s", inet_ntoa(packet->raw->giaddr));

	/* 
	 * We can't reply if there is no giaddr field.
	 */
	if (!packet->raw->giaddr.s_addr) {
		log_info("%s: missing giaddr, ciaddr is %s, no reply sent", 
			 msgbuf, inet_ntoa(packet->raw->ciaddr));
		return;
	}

	/* 
	 * Initially we use the 'giaddr' subnet options scope to determine if
	 * the giaddr-identified relay agent is permitted to perform a
	 * leasequery.  The subnet is not required, and may be omitted, in
	 * which case we are essentially interrogating the root options class
	 * to find a globally permit.
	 */
	gip.len = sizeof(packet->raw->giaddr);
	memcpy(gip.iabuf, &packet->raw->giaddr, sizeof(packet->raw->giaddr));

	subnet = NULL;
	find_subnet(&subnet, gip, MDL);
	if (subnet != NULL)
		relay_group = subnet->group;
	else
		relay_group = root_group;

	subnet_dereference(&subnet, MDL);

	options = NULL;
	if (!option_state_allocate(&options, MDL)) {
		log_error("No memory for option state.");
		log_info("%s: out of memory, no reply sent", msgbuf);
		return;
	}

	execute_statements_in_scope(NULL,
				    packet,
				    NULL,
				    NULL,
				    packet->options,
				    options,
				    &global_scope,
				    relay_group,
				    NULL);

	for (i=packet->class_count-1; i>=0; i--) {
		execute_statements_in_scope(NULL,
					    packet,
					    NULL,
					    NULL,
					    packet->options,
					    options,
					    &global_scope,
					    packet->classes[i]->group,
					    relay_group);
	}

	/* 
	 * Because LEASEQUERY has some privacy concerns, default to deny.
	 */
	allow_leasequery = 0;

	/*
	 * See if we are authorized to do LEASEQUERY.
	 */
	oc = lookup_option(&server_universe, options, SV_LEASEQUERY);
	if (oc != NULL) {
		allow_leasequery = evaluate_boolean_option_cache(&ignorep,
					 packet, NULL, NULL, packet->options,
					 options, &global_scope, oc, MDL);
	}

	if (!allow_leasequery) {
		log_info("%s: LEASEQUERY not allowed, query ignored", msgbuf);
		option_state_dereference(&options, MDL);
		return;
	}


	/* 
	 * Copy out the client IP address.
	 */
	cip.len = sizeof(packet->raw->ciaddr);
	memcpy(cip.iabuf, &packet->raw->ciaddr, sizeof(packet->raw->ciaddr));

	/* 
	 * If the client IP address is valid (not all zero), then we 
	 * are looking for information about that IP address.
	 */
	assoc_ip_cnt = 0;
	lease = tmp_lease = NULL;
	if (memcmp(cip.iabuf, "\0\0\0", 4)) {

		want_associated_ip = 0;

		snprintf(dbg_info, sizeof(dbg_info), "IP %s", piaddr(cip));
		find_lease_by_ip_addr(&lease, cip, MDL);


	} else {

		want_associated_ip = 1;

		/*
		 * If the client IP address is all zero, then we will
		 * either look up by the client identifier (if we have
		 * one), or by the MAC address.
		 */

		memset(&uid, 0, sizeof(uid));
		if (get_option(&uid, 
			       &dhcp_universe,
			       packet,
			       NULL,
			       NULL,
			       packet->options,
			       NULL,
			       packet->options, 
			       &global_scope,
			       DHO_DHCP_CLIENT_IDENTIFIER,
			       MDL)) {

			snprintf(dbg_info, 
				 sizeof(dbg_info), 
				 "client-id %s",
				 print_hex_1(uid.len, uid.data, 60));

			find_lease_by_uid(&tmp_lease, uid.data, uid.len, MDL);
			data_string_forget(&uid, MDL);
			get_newest_lease(&lease, tmp_lease, next_uid);
			assoc_ip_cnt = get_associated_ips(tmp_lease,
							  next_uid, 
							  lease,
							  assoc_ips, 
							  nassoc_ips);

		} else {

			if (packet->raw->hlen+1 > sizeof(h.hbuf)) {
				log_info("%s: hardware length too long, "
					 "no reply sent", msgbuf);
				option_state_dereference(&options, MDL);
				return;
			}

			h.hlen = packet->raw->hlen + 1;
			h.hbuf[0] = packet->raw->htype;
			memcpy(&h.hbuf[1], 
			       packet->raw->chaddr, 
			       packet->raw->hlen);

			snprintf(dbg_info, 
				 sizeof(dbg_info), 
				 "MAC address %s",
				 print_hw_addr(h.hbuf[0], 
					       h.hlen - 1, 
					       &h.hbuf[1]));

			find_lease_by_hw_addr(&tmp_lease, h.hbuf, h.hlen, MDL);
			get_newest_lease(&lease, tmp_lease, next_hw);
			assoc_ip_cnt = get_associated_ips(tmp_lease,
							  next_hw, 
							  lease,
							  assoc_ips, 
							  nassoc_ips);

		}

		lease_dereference(&tmp_lease, MDL);

		if (lease != NULL) {
			memcpy(&packet->raw->ciaddr, 
			       lease->ip_addr.iabuf,
			       sizeof(packet->raw->ciaddr));
		}

		/*
		 * Log if we have too many IP addresses associated
		 * with this client.
		 */
		if (want_associated_ip && (assoc_ip_cnt > nassoc_ips)) {
			log_info("%d IP addresses associated with %s, "
				 "only %d sent in reply.",
				 assoc_ip_cnt, dbg_info, nassoc_ips);
		}
	}

	/*
	 * We now know the query target too, so can report this in 
	 * our log message.
	 */
	snprintf(msgbuf, sizeof(msgbuf), 
		"DHCPLEASEQUERY from %s for %s",
		inet_ntoa(packet->raw->giaddr), dbg_info);

	/*
	 * Figure our our return type.
	 */
	if (lease == NULL) {
		dhcpMsgType = DHCPLEASEUNKNOWN;
		dhcp_msg_type_name = "DHCPLEASEUNKNOWN";
	} else {
		if (lease->binding_state == FTS_ACTIVE) {
			dhcpMsgType = DHCPLEASEACTIVE;
			dhcp_msg_type_name = "DHCPLEASEACTIVE";
		} else {
			dhcpMsgType = DHCPLEASEUNASSIGNED;
			dhcp_msg_type_name = "DHCPLEASEUNASSIGNED";
		}
	}

	/* 
	 * Set options that only make sense if we have an active lease.
	 */

	if (dhcpMsgType == DHCPLEASEACTIVE)
	{
		/*
		 * RFC 4388 uses the PRL to request options for the agent to
		 * receive that are "about" the client.  It is confusing
		 * because in some cases it wants to know what was sent to
		 * the client (lease times, adjusted), and in others it wants
		 * to know information the client sent.  You're supposed to
		 * know this on a case-by-case basis.
		 *
		 * "Name servers", "domain name", and the like from the relay
		 * agent's scope seems less than useful.  Our options are to
		 * restart the option cache from the lease's best point of view
		 * (execute statements from the lease pool's group), or to
		 * simply restart the option cache from empty.
		 *
		 * I think restarting the option cache from empty best
		 * approaches RFC 4388's intent; specific options are included.
		 */
		option_state_dereference(&options, MDL);

		if (!option_state_allocate(&options, MDL)) {
			log_error("%s: out of memory, no reply sent", msgbuf);
			lease_dereference(&lease, MDL);
			return;
		}

		/* 
		 * Set the hardware address fields.
		 */

		packet->raw->hlen = lease->hardware_addr.hlen - 1;
		packet->raw->htype = lease->hardware_addr.hbuf[0];
		memcpy(packet->raw->chaddr, 
		       &lease->hardware_addr.hbuf[1], 
		       sizeof(packet->raw->chaddr));

		/*
		 * Set client identifier option.
		 */
		if (lease->uid_len > 0) {
			if (!add_option(options,
					DHO_DHCP_CLIENT_IDENTIFIER,
					lease->uid,
					lease->uid_len)) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}


		/*
		 * Calculate T1 and T2, the times when the client
		 * tries to extend its lease on its networking
		 * address.
		 * These seem to be hard-coded in ISC DHCP, to 0.5 and
		 * 0.875 of the lease time.
		 */

		lease_duration = lease->ends - lease->starts;
		time_renewal = lease->starts + 
			(lease_duration / 2);
		time_rebinding = lease->starts + 
			(lease_duration / 2) +
			(lease_duration / 4) +
			(lease_duration / 8);

		if (time_renewal > cur_time) {
			time_renewal = htonl(time_renewal - cur_time);

			if (!add_option(options, 
					DHO_DHCP_RENEWAL_TIME,
					&time_renewal, 
					sizeof(time_renewal))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		if (time_rebinding > cur_time) {
			time_rebinding = htonl(time_rebinding - cur_time);

			if (!add_option(options, 
					DHO_DHCP_REBINDING_TIME,
					&time_rebinding, 
					sizeof(time_rebinding))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		if (lease->ends > cur_time) {
			time_expiry = htonl(lease->ends - cur_time);

			if (!add_option(options, 
					DHO_DHCP_LEASE_TIME,
					&time_expiry, 
					sizeof(time_expiry))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		/* Supply the Vendor-Class-Identifier. */
		if (lease->scope != NULL) {
			struct data_string vendor_class;

			memset(&vendor_class, 0, sizeof(vendor_class));

			if (find_bound_string(&vendor_class, lease->scope,
					      "vendor-class-identifier")) {
				if (!add_option(options,
						DHO_VENDOR_CLASS_IDENTIFIER,
						(void *)vendor_class.data,
						vendor_class.len)) {
					option_state_dereference(&options,
								 MDL);
					lease_dereference(&lease, MDL);
					log_error("%s: error adding vendor "
						  "class identifier, no reply "
						  "sent", msgbuf);
					data_string_forget(&vendor_class, MDL);
					return;
				}
				data_string_forget(&vendor_class, MDL);
			}
		}

		/*
		 * Set the relay agent info.
		 *
		 * Note that because agent info is appended without regard
		 * to the PRL in cons_options(), this will be sent as the
		 * last option in the packet whether it is listed on PRL or
		 * not.
		 */

		if (lease->agent_options != NULL) {
			int idx = agent_universe.index;
			struct option_chain_head **tmp1 = 
				(struct option_chain_head **)
				&(options->universes[idx]);
				struct option_chain_head *tmp2 = 
				(struct option_chain_head *)
				lease->agent_options;

			option_chain_head_reference(tmp1, tmp2, MDL);
		}

		/* 
	 	 * Set the client last transaction time.
		 * We check to make sure we have a timestamp. For
		 * lease files that were saved before running a 
		 * timestamp-aware version of the server, this may
		 * not be set.
	 	 */

		if (lease->cltt != MIN_TIME) {
			if (cur_time > lease->cltt) {
				client_last_transaction_time = 
					htonl(cur_time - lease->cltt);
			} else {
				client_last_transaction_time = htonl(0);
			}
			if (!add_option(options, 
					DHO_CLIENT_LAST_TRANSACTION_TIME,
					&client_last_transaction_time,
		     			sizeof(client_last_transaction_time))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		/*
	 	 * Set associated IPs, if requested and there are some.
	 	 */
		if (want_associated_ip && (assoc_ip_cnt > 0)) {
			if (!add_option(options, 
					DHO_ASSOCIATED_IP,
					assoc_ips,
					assoc_ip_cnt * sizeof(assoc_ips[0]))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}
	}

	/* 
	 * Set the message type.
	 */

	packet->raw->op = BOOTREPLY;

	/*
	 * Set DHCP message type.
	 */
	if (!add_option(options, 
		        DHO_DHCP_MESSAGE_TYPE,
		        &dhcpMsgType, 
			sizeof(dhcpMsgType))) {
		option_state_dereference(&options, MDL);
		lease_dereference(&lease, MDL);
		log_info("%s: error adding option, no reply sent", msgbuf);
		return;
	}

	/*
	 * Log the message we've received.
	 */
	log_info("%s", msgbuf);

	/*
	 * Figure out which address to use to send from.
	 */
	get_server_source_address(&siaddr, options, packet);

	/* 
	 * Set up the option buffer.
	 */

	memset(&prl, 0, sizeof(prl));
	oc = lookup_option(&dhcp_universe, options, 
			   DHO_DHCP_PARAMETER_REQUEST_LIST);
	if (oc != NULL) {
		evaluate_option_cache(&prl, 
				      packet, 
				      NULL,
				      NULL,
				      packet->options,
				      options,
				      &global_scope,
				      oc,
				      MDL);
	}
	if (prl.len > 0) {
		prl_ptr = &prl;
	} else {
		prl_ptr = NULL;
	}

	packet->packet_length = cons_options(packet, 
					     packet->raw, 
					     lease,
					     NULL,
					     0,
					     packet->options,
					     options,
					     &global_scope,
					     0,
					     0,
					     0, 
					     prl_ptr,
					     NULL);

	data_string_forget(&prl, MDL);	/* SK: safe, even if empty */
	option_state_dereference(&options, MDL);
	lease_dereference(&lease, MDL);

	to.sin_family = AF_INET;
#ifdef HAVE_SA_LEN
	to.sin_len = sizeof(to);
#endif
	memset(to.sin_zero, 0, sizeof(to.sin_zero));

	/* 
	 * Leasequery packets are be sent to the gateway address.
	 */
	to.sin_addr = packet->raw->giaddr;
	if (packet->raw->giaddr.s_addr != htonl(INADDR_LOOPBACK)) {
		to.sin_port = local_port;
	} else {
		to.sin_port = remote_port; /* XXXSK: For debugging. */
	}

	/* 
	 * The fallback_interface lets us send with a real IP
	 * address. The packet interface sends from all-zeros.
	 */
	if (fallback_interface != NULL) {
		interface = fallback_interface;
	} else {
		interface = packet->interface;
	}

	/*
	 * Report what we're sending.
	 */
	log_info("%s to %s for %s (%d associated IPs)",
		dhcp_msg_type_name, 
		inet_ntoa(to.sin_addr), dbg_info, assoc_ip_cnt);

	send_packet(interface,
		    NULL,
		    packet->raw, 
		    packet->packet_length,
		    siaddr,
		    &to,
		    NULL);
}

#ifdef DHCPv6

/*
 * TODO: RFC5007 query-by-clientid.
 *
 * TODO: RFC5007 look at the pools according to the link-address.
 *
 * TODO: get fixed leases too.
 *
 * TODO: RFC5007 ORO in query-options.
 *
 * TODO: RFC5007 lq-relay-data.
 *
 * TODO: RFC5007 lq-client-link.
 *
 * Note: the code is still nearly compliant and usable for the target
 * case with these missing features!
 */

/*
 * The structure to handle a leasequery.
 */
struct lq6_state {
	struct packet *packet;
	struct data_string client_id;
	struct data_string server_id;
	struct data_string lq_query;
	uint8_t query_type;
	struct in6_addr link_addr;
	struct option_state *query_opts;

	struct option_state *reply_opts;
	unsigned cursor;
	union reply_buffer {
		unsigned char data[65536];
		struct dhcpv6_packet reply;
	} buf;
};

/*
 * Options that we want to send.
 */
static const int required_opts_lq[] = {
	D6O_CLIENTID,
	D6O_SERVERID,
	D6O_STATUS_CODE,
	D6O_CLIENT_DATA,
	D6O_LQ_RELAY_DATA,
	D6O_LQ_CLIENT_LINK,
	0
};
static const int required_opt_CLIENT_DATA[] = {
	D6O_CLIENTID,
	D6O_IAADDR,
	D6O_IAPREFIX,
	D6O_CLT_TIME,
	0
};

/*
 * Get the lq-query option from the packet.
 */
static isc_result_t
get_lq_query(struct lq6_state *lq)
{
	struct data_string *lq_query = &lq->lq_query;
	struct packet *packet = lq->packet;
	struct option_cache *oc;

	/*
	 * Verify our lq_query structure is empty.
	 */
	if ((lq_query->data != NULL) || (lq_query->len != 0)) {
		return DHCP_R_INVALIDARG;
	}

	oc = lookup_option(&dhcpv6_universe, packet->options, D6O_LQ_QUERY);
	if (oc == NULL) {
		return ISC_R_NOTFOUND;
	}

	if (!evaluate_option_cache(lq_query, packet, NULL, NULL,
				   packet->options, NULL,
				   &global_scope, oc, MDL)) {
		return ISC_R_FAILURE;
	}

	return ISC_R_SUCCESS;
}

/*
 * Message validation, RFC 5007 section 4.2.1:
 *  dhcpv6.c:valid_client_msg() - unicast + lq-query option.
 */
static int
valid_query_msg(struct lq6_state *lq) {
	struct packet *packet = lq->packet;
	int ret_val = 0;
	struct option_cache *oc;

	/* INSIST((lq != NULL) || (packet != NULL)); */

	switch (get_client_id(packet, &lq->client_id)) {
		case ISC_R_SUCCESS:
			break;
		case ISC_R_NOTFOUND:
			log_debug("Discarding %s from %s; "
				  "client identifier missing", 
				  dhcpv6_type_names[packet->dhcpv6_msg_type],
				  piaddr(packet->client_addr));
			goto exit;
		default:
			log_error("Error processing %s from %s; "
				  "unable to evaluate Client Identifier",
				  dhcpv6_type_names[packet->dhcpv6_msg_type],
				  piaddr(packet->client_addr));
			goto exit;
	}

	oc = lookup_option(&dhcpv6_universe, packet->options, D6O_SERVERID);
	if (oc != NULL) {
		if (evaluate_option_cache(&lq->server_id, packet, NULL, NULL,
					  packet->options, NULL, 
					  &global_scope, oc, MDL)) {
			log_debug("Discarding %s from %s; " 
				  "server identifier found "
				  "(CLIENTID %s, SERVERID %s)", 
				  dhcpv6_type_names[packet->dhcpv6_msg_type],
				  piaddr(packet->client_addr),
				  print_hex_1(lq->client_id.len, 
				  	      lq->client_id.data, 60),
				  print_hex_2(lq->server_id.len,
				  	      lq->server_id.data, 60));
		} else {
			log_debug("Discarding %s from %s; " 
				  "server identifier found "
				  "(CLIENTID %s)", 
				  dhcpv6_type_names[packet->dhcpv6_msg_type],
				  print_hex_1(lq->client_id.len, 
				  	      lq->client_id.data, 60),
				  piaddr(packet->client_addr));
		}
		goto exit;
	}

	switch (get_lq_query(lq)) {
		case ISC_R_SUCCESS:
			break;
		case ISC_R_NOTFOUND:
			log_debug("Discarding %s from %s; lq-query missing",
				  dhcpv6_type_names[packet->dhcpv6_msg_type],
				  piaddr(packet->client_addr));
			goto exit;
		default:
			log_error("Error processing %s from %s; "
				  "unable to evaluate LQ-Query",
				  dhcpv6_type_names[packet->dhcpv6_msg_type],
				  piaddr(packet->client_addr));
			goto exit;
	}

	/* looks good */
	ret_val = 1;

exit:
	if (!ret_val) {
		if (lq->client_id.len > 0) {
			data_string_forget(&lq->client_id, MDL);
		}
		if (lq->server_id.len > 0) {
			data_string_forget(&lq->server_id, MDL);
		}
		if (lq->lq_query.len > 0) {
			data_string_forget(&lq->lq_query, MDL);
		}
	}
	return ret_val;
}

/*
 * Set an error in a status-code option (from set_status_code).
 */
static int
set_error(struct lq6_state *lq, u_int16_t code, const char *message) {
	struct data_string d;
	int ret_val;

	memset(&d, 0, sizeof(d));
	d.len = sizeof(code) + strlen(message);
	if (!buffer_allocate(&d.buffer, d.len, MDL)) {
		log_fatal("set_error: no memory for status code.");
	}
	d.data = d.buffer->data;
	putUShort(d.buffer->data, code);
	memcpy(d.buffer->data + sizeof(code), message, d.len - sizeof(code));
	if (!save_option_buffer(&dhcpv6_universe, lq->reply_opts,
				d.buffer, (unsigned char *)d.data, d.len, 
				D6O_STATUS_CODE, 0)) {
		log_error("set_error: error saving status code.");
		ret_val = 0;
	} else {
		ret_val = 1;
	}
	data_string_forget(&d, MDL);
	return ret_val;
}

/*
 * Process a by-address lease query.
 */
static int
process_lq_by_address(struct lq6_state *lq) {
	struct packet *packet = lq->packet;
	struct option_cache *oc;
	struct ipv6_pool *pool = NULL;
	struct data_string data;
	struct in6_addr addr;
	struct iasubopt *iaaddr = NULL;
	struct option_state *opt_state = NULL;
	u_int32_t lifetime;
	unsigned opt_cursor;
	int ret_val = 0;

	/*
	 * Get the IAADDR.
	 */
	oc = lookup_option(&dhcpv6_universe, lq->query_opts, D6O_IAADDR);
	if (oc == NULL) {
		if (!set_error(lq, STATUS_MalformedQuery,
			       "No OPTION_IAADDR.")) {
			log_error("process_lq_by_address: unable "
				  "to set MalformedQuery status code.");
			return 0;
		}
		return 1;
	}
	memset(&data, 0, sizeof(data));
	if (!evaluate_option_cache(&data, packet,
				   NULL, NULL,
				   lq->query_opts, NULL,
				   &global_scope, oc, MDL) ||
	    (data.len < IAADDR_OFFSET)) {
		log_error("process_lq_by_address: error evaluating IAADDR.");
		goto exit;
	}
	memcpy(&addr, data.data, sizeof(addr));
	data_string_forget(&data, MDL);

	/*
	 * Find the lease.
	 * Note the RFC 5007 says to use the link-address to find the link
	 * or the ia-aadr when it is :: but in any case the ia-addr has
	 * to be on the link, so we ignore the link-address here.
	 */
	if (find_ipv6_pool(&pool, D6O_IA_NA, &addr) != ISC_R_SUCCESS) {
		if (!set_error(lq, STATUS_NotConfigured,
			       "Address not in a pool.")) {
			log_error("process_lq_by_address: unable "
				  "to set NotConfigured status code.");
			goto exit;
		}
		ret_val = 1;
		goto exit;
	}
	if (iasubopt_hash_lookup(&iaaddr, pool->leases, &addr,
				 sizeof(addr), MDL) == 0) {
		ret_val = 1;
		goto exit;
	}
	if ((iaaddr == NULL) || (iaaddr->state != FTS_ACTIVE) ||
	    (iaaddr->ia == NULL) || (iaaddr->ia->iaid_duid.len <= 4)) {
		ret_val = 1;
		goto exit;
	}

	/*
	 * Build the client-data option (with client-id, ia-addr and clt-time).
	 */
	if (!option_state_allocate(&opt_state, MDL)) {
		log_error("process_lq_by_address: "
			  "no memory for option state.");
		goto exit;
	}

	data_string_copy(&data, &iaaddr->ia->iaid_duid, MDL);
	data.data += 4;
	data.len -= 4;
	if (!save_option_buffer(&dhcpv6_universe, opt_state,
				NULL, (unsigned char *)data.data, data.len,
				D6O_CLIENTID, 0)) {
		log_error("process_lq_by_address: error saving client ID.");
		goto exit;
	}
	data_string_forget(&data, MDL);

	data.len = IAADDR_OFFSET;
	if (!buffer_allocate(&data.buffer, data.len, MDL)) {
		log_error("process_lq_by_address: no memory for ia-addr.");
		goto exit;
	}
	data.data = data.buffer->data;
	memcpy(data.buffer->data, &iaaddr->addr, 16);
	lifetime = iaaddr->prefer;
	putULong(data.buffer->data + 16, lifetime);
	lifetime = iaaddr->valid;
	putULong(data.buffer->data + 20, lifetime);
	if (!save_option_buffer(&dhcpv6_universe, opt_state,
				NULL, (unsigned char *)data.data, data.len,
				D6O_IAADDR, 0)) {
		log_error("process_lq_by_address: error saving ia-addr.");
		goto exit;
	}
	data_string_forget(&data, MDL);

	lifetime = htonl(iaaddr->ia->cltt);
	if (!save_option_buffer(&dhcpv6_universe, opt_state,
				NULL, (unsigned char *)&lifetime, 4,
				D6O_CLT_TIME, 0)) {
		log_error("process_lq_by_address: error saving clt time.");
		goto exit;
	}

	/*
	 * Store the client-data option.
	 */
	opt_cursor = lq->cursor;
	putUShort(lq->buf.data + lq->cursor, (unsigned)D6O_CLIENT_DATA);
	lq->cursor += 2;
	/* Skip option length. */
	lq->cursor += 2;

	lq->cursor += store_options6((char *)lq->buf.data + lq->cursor,
				     sizeof(lq->buf) - lq->cursor,
				     opt_state, lq->packet,
				     required_opt_CLIENT_DATA, NULL);
	/* Reset the length. */
	putUShort(lq->buf.data + opt_cursor + 2,
		  lq->cursor - (opt_cursor + 4));

	/* Done. */
	ret_val = 1;

     exit:
	if (data.data != NULL)
		data_string_forget(&data, MDL);
	if (pool != NULL)
		ipv6_pool_dereference(&pool, MDL);
	if (iaaddr != NULL)
		iasubopt_dereference(&iaaddr, MDL);
	if (opt_state != NULL)
		option_state_dereference(&opt_state, MDL);
	return ret_val;
}


/*
 * Process a lease query.
 */
void
dhcpv6_leasequery(struct data_string *reply_ret, struct packet *packet) {
	static struct lq6_state lq;
	struct option_cache *oc;
	int allow_lq;

	/*
	 * Initialize the lease query state.
	 */
	lq.packet = NULL;
	memset(&lq.client_id, 0, sizeof(lq.client_id));
	memset(&lq.server_id, 0, sizeof(lq.server_id));
	memset(&lq.lq_query, 0, sizeof(lq.lq_query));
	lq.query_opts = NULL;
	lq.reply_opts = NULL;
	packet_reference(&lq.packet, packet, MDL);

	/*
	 * Validate our input.
	 */
	if (!valid_query_msg(&lq)) {
		goto exit;
	}

	/*
	 * Prepare our reply.
	 */
	if (!option_state_allocate(&lq.reply_opts, MDL)) {
		log_error("dhcpv6_leasequery: no memory for option state.");
		goto exit;
	}
	execute_statements_in_scope(NULL, lq.packet, NULL, NULL,
				    lq.packet->options, lq.reply_opts,
				    &global_scope, root_group, NULL);

	lq.buf.reply.msg_type = DHCPV6_LEASEQUERY_REPLY;

	memcpy(lq.buf.reply.transaction_id,
	       lq.packet->dhcpv6_transaction_id,
	       sizeof(lq.buf.reply.transaction_id));

	/* 
	 * Because LEASEQUERY has some privacy concerns, default to deny.
	 */
	allow_lq = 0;

	/*
	 * See if we are authorized to do LEASEQUERY.
	 */
	oc = lookup_option(&server_universe, lq.reply_opts, SV_LEASEQUERY);
	if (oc != NULL) {
		allow_lq = evaluate_boolean_option_cache(NULL,
							 lq.packet,
							 NULL, NULL,
							 lq.packet->options,
							 lq.reply_opts,
							 &global_scope,
							 oc, MDL);
	}

	if (!allow_lq) {
		log_info("dhcpv6_leasequery: not allowed, query ignored.");
		goto exit;
	}
	    
	/*
	 * Same than transmission of REPLY message in RFC 3315:
	 *  server-id
	 *  client-id
	 */

	oc = lookup_option(&dhcpv6_universe, lq.reply_opts, D6O_SERVERID);
	if (oc == NULL) {
		/* If not already in options, get from query then global. */
		if (lq.server_id.data == NULL)
			copy_server_duid(&lq.server_id, MDL);
		if (!save_option_buffer(&dhcpv6_universe,
					lq.reply_opts,
					NULL,
					(unsigned char *)lq.server_id.data,
					lq.server_id.len, 
					D6O_SERVERID,
					0)) {
			log_error("dhcpv6_leasequery: "
				  "error saving server identifier.");
			goto exit;
		}
	}

	if (!save_option_buffer(&dhcpv6_universe,
				lq.reply_opts,
				lq.client_id.buffer,
				(unsigned char *)lq.client_id.data,
				lq.client_id.len,
				D6O_CLIENTID,
				0)) {
		log_error("dhcpv6_leasequery: "
			  "error saving client identifier.");
		goto exit;
	}

	lq.cursor = 4;

	/*
	 * Decode the lq-query option.
	 */

	if (lq.lq_query.len <= LQ_QUERY_OFFSET) {
		if (!set_error(&lq, STATUS_MalformedQuery,
			       "OPTION_LQ_QUERY too short.")) {
			log_error("dhcpv6_leasequery: unable "
				  "to set MalformedQuery status code.");
			goto exit;
		}
		goto done;
	}

	lq.query_type = lq.lq_query.data [0];
	memcpy(&lq.link_addr, lq.lq_query.data + 1, sizeof(lq.link_addr));
	switch (lq.query_type) {
		case LQ6QT_BY_ADDRESS:
			break;
		case LQ6QT_BY_CLIENTID:
			if (!set_error(&lq, STATUS_UnknownQueryType,
				       "QUERY_BY_CLIENTID not supported.")) {
				log_error("dhcpv6_leasequery: unable to "
					  "set UnknownQueryType status code.");
				goto exit;
			}
			goto done;
		default:
			if (!set_error(&lq, STATUS_UnknownQueryType,
				       "Unknown query-type.")) {
				log_error("dhcpv6_leasequery: unable to "
					  "set UnknownQueryType status code.");
				goto exit;
			}
			goto done;
	}

	if (!option_state_allocate(&lq.query_opts, MDL)) {
		log_error("dhcpv6_leasequery: no memory for option state.");
		goto exit;
	}
	if (!parse_option_buffer(lq.query_opts,
				 lq.lq_query.data + LQ_QUERY_OFFSET,
				 lq.lq_query.len - LQ_QUERY_OFFSET,
				 &dhcpv6_universe)) {
		log_error("dhcpv6_leasequery: error parsing query-options.");
		if (!set_error(&lq, STATUS_MalformedQuery,
			       "Bad query-options.")) {
			log_error("dhcpv6_leasequery: unable "
				  "to set MalformedQuery status code.");
			goto exit;
		}
		goto done;
	}

	/* Do it. */
	if (!process_lq_by_address(&lq))
		goto exit;

      done:
	/* Store the options. */
	lq.cursor += store_options6((char *)lq.buf.data + lq.cursor,
				    sizeof(lq.buf) - lq.cursor,
				    lq.reply_opts,
				    lq.packet,
				    required_opts_lq,
				    NULL);

	/* Return our reply to the caller. */
	reply_ret->len = lq.cursor;
	reply_ret->buffer = NULL;
	if (!buffer_allocate(&reply_ret->buffer, lq.cursor, MDL)) {
		log_fatal("dhcpv6_leasequery: no memory to store Reply.");
	}
	memcpy(reply_ret->buffer->data, lq.buf.data, lq.cursor);
	reply_ret->data = reply_ret->buffer->data;

      exit:
	/* Cleanup. */
	if (lq.packet != NULL)
		packet_dereference(&lq.packet, MDL);
	if (lq.client_id.data != NULL)
		data_string_forget(&lq.client_id, MDL);
	if (lq.server_id.data != NULL)
		data_string_forget(&lq.server_id, MDL);
	if (lq.lq_query.data != NULL)
		data_string_forget(&lq.lq_query, MDL);
	if (lq.query_opts != NULL)
		option_state_dereference(&lq.query_opts, MDL);
	if (lq.reply_opts != NULL)
		option_state_dereference(&lq.reply_opts, MDL);
}

#endif /* DHCPv6 */