summaryrefslogtreecommitdiff
path: root/sys/netinet6/in6_pcb.c
blob: ec2a27b665ee798ada05c2376d20498471dd1a19 (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
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
/*
%%% copyright-nrl-95
This software is Copyright 1995-1998 by Randall Atkinson, Ronald Lee,
Daniel McDonald, Bao Phan, and Chris Winters. All Rights Reserved. All
rights under this copyright have been assigned to the US Naval Research
Laboratory (NRL). The NRL Copyright Notice and License Agreement Version
1.1 (January 17, 1995) applies to this software.
You should have received a copy of the license with this software. If you
didn't get a copy, you may request one from <license@ipv6.nrl.navy.mil>.

*/
/*
 * Copyright (c) 1982, 1986, 1990, 1993, 1995
 *	Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#if __FreeBSD__
#include <sys/queue.h>
#endif /* __FreeBSD__ */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
/*#include <sys/ioctl.h>*/
#include <sys/errno.h>
#include <sys/time.h>
#include <sys/proc.h>

#include <net/if.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>

#include <netinet6/in6.h>
#include <netinet6/in6_var.h>
#include <netinet6/ipv6.h>
#include <netinet6/ipv6_var.h>

#if __OpenBSD__ && defined(NRL_IPSEC)
#define IPSEC 1
#endif /* __OpenBSD__ && defined(NRL_IPSEC) */

#ifdef IPSEC
#include <sys/osdep.h>
#include <net/netproc.h>
#include <net/netproc_var.h>
#endif /* IPSEC */

#include <sys/debug.h>

#if defined(_BSDI_VERSION) && (_BSDI_VERSION >= 199802)
#include <machine/pcpu.h>
#endif /* defined(_BSDI_VERSION) && (_BSDI_VERSION >= 199802) */

/*
 * External globals
 */

#if __OpenBSD__
#include <dev/rndvar.h>
#endif /* __OpenBSD__ */

#if __FreeBSD__
/*
 * These configure the range of local port addresses assigned to
 * "unspecified" outgoing connections/packets/whatever.
 */
static int ipport_lowfirstauto  = IPPORT_RESERVED - 1;	/* 1023 */
static int ipport_lowlastauto = IPPORT_RESERVEDSTART;	/* 600 */
static int ipport_firstauto = IPPORT_RESERVED;		/* 1024 */
static int ipport_lastauto  = IPPORT_USERRESERVED;	/* 5000 */
static int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;	/* 49152 */
static int ipport_hilastauto  = IPPORT_HILASTAUTO;	/* 65535 */
extern void in_rtchange(struct inpcb *, int);
#endif /* __FreeBSD__ */

extern struct in6_ifaddr *in6_ifaddr;
#if __FreeBSD__
int in6_pcbladdr(register struct inpcb *, struct sockaddr *, struct sockaddr **);
extern  TAILQ_HEAD(in_ifaddrhead, in_ifaddr) in_ifaddrhead;
#else /* __FreeBSD__ */
extern struct in_ifaddr *in_ifaddr;
#endif /* __FreeBSD__ */
/*
 * Globals
 */

struct in6_addr zeroin6_addr;

#if __OpenBSD__
extern int ipport_firstauto;
extern int ipport_lastauto;
extern int ipport_hifirstauto;
extern int ipport_hilastauto;
#endif /* __OpenBSD__ */

#if __OpenBSD__
int in_baddynamic __P((u_int16_t, u_int16_t));
#endif /* __OpenBSD__ */

/*
 * Keep separate inet6ctlerrmap, because I may remap some of these.
 * I also put it here, because, quite frankly, it belongs here, not in
 * ip{v6,}_input().
 */
u_char inet6ctlerrmap[PRC_NCMDS] = {
        0,              0,              0,              0,
        0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
        EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
        EMSGSIZE,       EHOSTUNREACH,   0,              0,
        0,              0,              0,              0,
        ENOPROTOOPT
};

/*----------------------------------------------------------------------
 * Bind an address (or at least a port) to an PF_INET6 socket.
 ----------------------------------------------------------------------*/
int
in6_pcbbind(inp, nam)
     register struct inpcb *inp;
#if __FreeBSD__
     struct sockaddr *nam;
#else /* __FreeBSD__ */
     struct mbuf *nam;
#endif /* __FreeBSD__ */
{
  register struct socket *so = inp->inp_socket;

#if __NetBSD__ || __OpenBSD__
  register struct inpcbtable *head = inp->inp_table;
#else /* __OpenBSD__ */
#ifndef __FreeBSD__
  register struct inpcb *head = inp->inp_head;
#else /* __FreeBSD__ */
    struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
#endif /* __FreeBSD__ */
#endif /* __NetBSD__ || __OpenBSD__ */
  register struct sockaddr_in6 *sin6;
#if !defined(_BSDI_VERSION) || (_BSDI_VERSION < 199802)
  struct proc *p = curproc;		/* XXX */
#else /* !defined(_BSDI_VERSION) || (_BSDI_VERSION < 199802) */
  struct proc *p = PCPU(curproc);		/* XXX */
#endif /* !defined(_BSDI_VERSION) || (_BSDI_VERSION < 199802) */
  u_short lport = 0;
  int wild = INPLOOKUP_IPV6, reuseport = (so->so_options & SO_REUSEPORT);
  int error;

  /*
   * REMINDER:  Once up to speed, flow label processing should go here,
   *            too.  (Same with in6_pcbconnect.)  
   */

#if __FreeBSD__
  if (in6_ifaddr == 0 || in_ifaddrhead.tqh_first == 0)
    return EADDRNOTAVAIL;
#else /* __FreeBSD__ */
  if (in6_ifaddr == 0 || in_ifaddr == 0)
    return EADDRNOTAVAIL;
#endif/* __FreeBSD__ */
  if (inp->inp_lport != 0 || !IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
    return EINVAL;   /* If already bound, EINVAL! */

  if ((so->so_options & (SO_REUSEADDR | SO_REUSEPORT)) == 0 &&
      ((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0 ||
       (so->so_options & SO_ACCEPTCONN) == 0))
    wild |= INPLOOKUP_WILDCARD;

  /*
   * If I did get a sockaddr passed in...
   */
  if (nam)
    {
#if __FreeBSD__
      sin6 = (struct sockaddr_in6 *)nam;
      if (nam->sa_len != sizeof (*sin6))
	return EINVAL;
#else /* __FreeBSD__ */
      sin6 = mtod(nam, struct sockaddr_in6 *);
      if (nam->m_len != sizeof (*sin6))
	return EINVAL;
#endif /* __FreeBSD__ */

      /*
       * Unlike v4, I have no qualms about EAFNOSUPPORT if the
       * wretched family is not filled in!
       */
      if (sin6->sin6_family != AF_INET6)
	return EAFNOSUPPORT;
      lport = sin6->sin6_port;

      if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
	{
	  /*
	   * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
	   * allow complete duplication of binding if
	   * SO_REUSEPORT is set, or if SO_REUSEADDR is set
	   * and a multicast address is bound on both
	   * new and duplicated sockets.
	   */
	  if (so->so_options & SO_REUSEADDR)
	    reuseport = SO_REUSEADDR | SO_REUSEPORT;
	}
      else if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
	{
	  struct sockaddr_in sin;

	  sin.sin_port = 0;
	  sin.sin_len = sizeof(sin);
	  sin.sin_family = AF_INET;
	  sin.sin_addr.s_addr = sin6->sin6_addr.in6a_words[3];
	  bzero(&sin.sin_zero,8);

	  sin6->sin6_port = 0;  /* Yechhhh, because of upcoming call to
				   ifa_ifwithaddr(), which does bcmp's
				   over the PORTS as well.  (What about flow?)
				   */
	  sin6->sin6_flowinfo = 0;
	  if (ifa_ifwithaddr((struct sockaddr *)sin6) == 0)
	    if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ||
		ifa_ifwithaddr((struct sockaddr *)&sin) == 0)
	      return EADDRNOTAVAIL;
	}
      if (lport)
	{
	  struct inpcb *t;
	  struct in_addr fa,la;

	  /* Question:  Do we wish to continue the Berkeley tradition of
	     ports < IPPORT_RESERVED be only for root? 

	     Answer:  For now yes, but IMHO, it should be REMOVED! 

	     OUCH:  One other thing, is there no better way of finding
	     a process for a socket instead of using curproc?  (Marked
	     with BSD's {in,}famous XXX ? */
	  if (ntohs(lport) < IPPORT_RESERVED &&
	      (error = suser(p->p_ucred, &p->p_acflag)))
	    return error;

	  if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
	    {
	      fa.s_addr = 0;
	      la.s_addr = sin6->sin6_addr.in6a_words[3];
	      wild &= ~INPLOOKUP_IPV6;

#if __FreeBSD__
	      t = in_pcblookup_local(inp->inp_pcbinfo, 
			       (struct in_addr *)&la, lport, wild);
#else /* __FreeBSD__ */
#if __NetBSD__
	      t = in_pcblookup_port(inp->inp_table, (struct in_addr *)&la,
				    lport, wild);
#else /* __NetBSD__ */
	      t = in_pcblookup(head, (struct in_addr *)&fa, 0,
			       (struct in_addr *)&la, lport, wild);
#endif /* __NetBSD__ */
#endif /* __FreeBSD__ */

	    }
	  else
	    {
#if __FreeBSD__
	      t = in_pcblookup_local(inp->inp_pcbinfo, 
			(struct in_addr *)&sin6->sin6_addr, lport, wild);
#else /* __FreeBSD__ */
#if __NetBSD__
	      t = in_pcblookup_port(inp->inp_table,
			          (struct in_addr *)&in6addr_any, lport, wild);
#else /* __NetBSD__ */
	      t = in_pcblookup(head, (struct in_addr *)&zeroin6_addr, 0,
			(struct in_addr *)&sin6->sin6_addr, lport, wild);
#endif /* __NetBSD__ */
#endif /* __FreeBSD__ */
	    }

	  if (t && (reuseport & t->inp_socket->so_options) == 0)
	    return EADDRINUSE;
	}
      inp->inp_laddr6 = sin6->sin6_addr;

      if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
	inp->inp_ipv6.ipv6_versfl = htonl(0x60000000) | 
	  (sin6->sin6_flowinfo & htonl(0x0fffffff));

      /*
       * Unroll first 2 compares of {UNSPEC,V4MAPPED}.
       * Mark PF_INET6 socket as undecided (bound to port-only) or
       * mapped (INET6 socket talking IPv4) here.  I may need to move
       * this code out of this if (nam) clause, and put it just before
       * function return.
       *
       * Then again, the only time this function is called with NULL nam
       * might be during a *_pcbconnect(), which then sets the local address
       * ANYWAY.
       */
      if (inp->inp_laddr6.in6a_words[0] == 0 && 
	  inp->inp_laddr6.in6a_words[1] == 0)
	{
	  if (inp->inp_laddr6.in6a_words[2] == ntohl(0xffff))
	    inp->inp_flags |= INP_IPV6_MAPPED;
	  if (inp->inp_laddr6.in6a_words[2] == 0 &&
	      inp->inp_laddr6.in6a_words[3] == 0)
	    inp->inp_flags |= INP_IPV6_UNDEC;
	}
    }

  if (lport == 0) {
    /* This code block was derived from OpenBSD */
    uint16_t first, last, old = 0;
    int count;
    int loopcount = 0;
    struct in_addr fa, la;
    u_int16_t *lastport;
#if defined(_BSDI_VERSION) && (_BSDI_VERSION >= 199802)
    u_int16_t last_port = head->inp_lport;

    lastport = &last_port;
#endif /* defined(_BSDI_VERSION) && (_BSDI_VERSION >= 199802) */
#if __NetBSD__ || __OpenBSD__
    lastport = &inp->inp_table->inpt_lastport;
#endif /* __NetBSD__ || __OpenBSD__ */

    if (inp->inp_flags & INP_IPV6_MAPPED) {
      la.s_addr = inp->inp_laddr6.in6a_words[3];
      fa.s_addr = 0;
      wild &= ~INPLOOKUP_IPV6;
    };

#if __OpenBSD__ || __FreeBSD__
#if __FreeBSD__
    inp->inp_flags |= INP_ANONPORT;
#endif /* __FreeBSD__ */

    if (inp->inp_flags & INP_HIGHPORT) {
      first = ipport_hifirstauto;	/* sysctl */
      last = ipport_hilastauto;
#if __FreeBSD__
      lastport = &pcbinfo->lasthi;
#endif /* __FreeBSD__ */
    } else if (inp->inp_flags & INP_LOWPORT) {
      if ((error = suser(p->p_ucred, &p->p_acflag)))
	return (EACCES);
#if __FreeBSD__
      first = ipport_lowfirstauto;
      last = ipport_lowlastauto;
      lastport = &pcbinfo->lastlow;
#else /* __FreeBSD__ */
      first = IPPORT_RESERVED-1; /* 1023 */
      last = 600;		   /* not IPPORT_RESERVED/2 */
#endif /* __FreeBSD__ */
    } else {
      first = ipport_firstauto;	/* sysctl */
      last  = ipport_lastauto;
#if __FreeBSD__
      lastport = &pcbinfo->lastport;
#endif /* __FreeBSD__ */
    }
#else /* __OpenBSD__ */
#if __bsdi__
    first = IPPORT_DYNAMIC;
    last = IPPORT_DYNAMIC_LAST;
#else /* __bsdi__ */
    first = IPPORT_RESERVED;
    last = IPPORT_USERRESERVED;
#endif /* __bsdi__ */
#endif /* __OpenBSD__ */

    /*
     * Simple check to ensure all ports are not used up causing
     * a deadlock here.
     *
     * We split the two cases (up and down) so that the direction
     * is not being tested on each round of the loop.
     */

portloop:
    if (first > last) {
      /*
       * counting down
       */
      if (loopcount == 0) {	/* only do this once. */
	old = first;
#if __OpenBSD__
	first -= (arc4random() % (first - last));
#else /* __OpenBSD__ */
	first -= (random() % (first - last));
#endif /* __OpenBSD__ */
      }
      count = first - last;
      *lastport = first;		/* restart each time */
      
      do {
	if (count-- <= 0) {	/* completely used? */
	  if (loopcount == 0) {
	    last = old;
	    loopcount++;
	    goto portloop;
	  }
	  return (EADDRNOTAVAIL);
	}
	--*lastport;
	if (*lastport > first || *lastport < last)
	  *lastport = first;
	lport = htons(*lastport);
#if __OpenBSD__
      } while (in_baddynamic(*lastport, so->so_proto->pr_protocol) ||
#else /* __OpenBSD__ */
      } while (
#endif /* __OpenBSD__ */
	       ((wild & INPLOOKUP_IPV6) ?
#ifdef __FreeBSD__ 
		in_pcblookup_local(pcbinfo,
			(struct in_addr *)&inp->inp_laddr6, lport, wild) :
		in_pcblookup_local(pcbinfo,
			(struct in_addr *)&la, lport, wild)));
#else /* __FreeBSD__ */
#if __NetBSD__
		in_pcblookup_port(head, (struct in_addr *)&inp->inp_laddr6,
				  lport, wild) :
		in_pcblookup_port(head, (struct in_addr *)&la, lport, wild)));
#else /* __NetBSD__ */
		in_pcblookup(head, (struct in_addr *)&zeroin6_addr, 0,
			(struct in_addr *)&inp->inp_laddr6, lport, wild) :
		in_pcblookup(head, (struct in_addr *)&fa, 0,
			(struct in_addr *)&la, lport, wild)));
#endif /* __NetBSD__ */
#endif /* __FreeBSD__ */
    } else {
      /*
       * counting up
       */
      if (loopcount == 0) {	/* only do this once. */
	old = first;
#if __OpenBSD__
	first += (arc4random() % (last - first));
#else /* __OpenBSD__ */
	first += (random() % (last - first));
#endif /* __OpenBSD__ */
      }
      count = last - first;
      *lastport = first;		/* restart each time */
      
      do {
	if (count-- <= 0) {	/* completely used? */
	  if (loopcount == 0) {
	    first = old;
	    loopcount++;
	    goto portloop;
	  }
	  return (EADDRNOTAVAIL);
	}
	++*lastport;
	if (*lastport < first || *lastport > last)
	  *lastport = first;
	lport = htons(*lastport);
#if __OpenBSD__
      } while (in_baddynamic(*lastport, so->so_proto->pr_protocol) ||
#else /* __OpenBSD__ */
      } while (
#endif /* __OpenBSD__ */
	       ((wild & INPLOOKUP_IPV6) ?
#ifdef __FreeBSD__ 
		in_pcblookup_local(pcbinfo,
			(struct in_addr *)&inp->inp_laddr6, lport, wild) :
		in_pcblookup_local(pcbinfo,
			(struct in_addr *)&la, lport, wild)));
#else /* __FreeBSD__ */
#if __NetBSD__
		in_pcblookup_port(head, (struct in_addr *)&inp->inp_laddr6,
		  lport, wild) :
		in_pcblookup_port(head, (struct in_addr *)&la, lport, wild)));
#else /* __NetBSD__ */
		in_pcblookup(head, (struct in_addr *)&zeroin6_addr, 0,
			(struct in_addr *)&inp->inp_laddr6, lport, wild) :
		in_pcblookup(head, (struct in_addr *)&fa, 0,
			(struct in_addr *)&la, lport, wild)));
#endif /* __NetBSD__ */
#endif /* __FreeBSD__ */
    }
  }

  inp->inp_lport = lport;

#if __FreeBSD__ 
#if 0
	 inp->inp_laddr.s_addr = inp->inp_laddr6.in6a_words[3]
	                       ^ inp->inp_laddr6.in6a_words[1];
  	/* 
	 * If this is FreeBSD then it requires the inpcb structure to be 
	 * inserted into various hash-tables.  Right now this is copies 
	 * directly from FreeBSD's source, but this will have to change for
	 * v6 addresses soon I think.  We're still not sure if word2 XOR word4
	 * is a good subject for the hash function.
	 */
#endif /* 0 */
	if (in_pcbinshash(inp) != 0) {
		bzero(&inp->inp_laddru, sizeof(inp->inp_laddru));
		inp->inp_lport = 0;
		return (EAGAIN);
	}
#endif /* __FreeBSD__ */
#if __NetBSD__
  in_pcbstate(inp, INP_BOUND);
#endif /* __NetBSD__ */

  /* XXX hash */
  return 0;
}

/*----------------------------------------------------------------------
 * This is maximum suckage point value.  This function is the first 
 * half or so of in6_pcbconnect.  It exists because FreeBSD's code 
 * supports this function for T/TCP.  If we want TCP to work with our 
 * code it must be supported. 
 ----------------------------------------------------------------------*/
#if __FreeBSD__ 
int
in6_pcbladdr(inp, nam, plocal_sin)
	 register struct inpcb *inp;
	 struct sockaddr *nam;
	 struct sockaddr **plocal_sin;
{

  struct in6_ifaddr *i6a;
  struct sockaddr_in  *ifaddr = NULL;

  register struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
  if (nam->sa_len != sizeof(struct sockaddr_in6))
    return (EINVAL);
    
  if (sin6->sin6_family != AF_INET6)
    return (EAFNOSUPPORT);
  if (sin6->sin6_port == 0)
    return (EADDRNOTAVAIL);


  if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
    {
      struct domain hackdomain, *save;
      struct sockaddr_in *sin;
      int rc;

      /*
       * FreeBSD doesn't want an mbuf to pcbconnect.
       */
      struct sockaddr_in hacksin;

      /*
       * Hmmm, if this is a v4-mapped v6 address, re-call in_pcbconnect
       * with a fake domain for now.  Then re-adjust the socket, and
       * return out of here.  Since this is called at splnet(), I don't
       * think temporarily altering the socket will matter.  XXX
       */

      /*
       * Can't have v6 talking to v4, now can we!
       */
      if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6) && 
	  !IN6_IS_ADDR_V4MAPPED(&inp->inp_laddr6))
	return EINVAL;  

      bzero(&hackdomain,sizeof(hackdomain));
      save = inp->inp_socket->so_proto->pr_domain;
      inp->inp_socket->so_proto->pr_domain = &hackdomain;
      hackdomain.dom_family = PF_INET;

      sin = &hacksin;
      sin->sin_len = sizeof(*sin);
      sin->sin_family = AF_INET;
      sin->sin_port = sin6->sin6_port;
      sin->sin_addr.s_addr = sin6->sin6_addr.in6a_words[3];

      /* CHANGE */
      rc = in_pcbladdr(inp, (struct sockaddr *) sin, &ifaddr);

      inp->inp_socket->so_proto->pr_domain = save;

      if (rc == 0)
	{
	  inp->inp_laddr6.in6a_words[2] = htonl(0xffff);
	  inp->inp_faddr6.in6a_words[2] = htonl(0xffff);
	  inp->inp_flags |= INP_IPV6_MAPPED;
	  inp->inp_flags &= ~INP_IPV6_UNDEC;
	}
      *plocal_sin = (struct sockaddr *)ifaddr;

      return rc;
    }

  if (in6_ifaddr && IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
    {
      /*
       * If the destination address is all 0's,
       * use the first non-loopback (and if possibly, non-link-local, else
       * use the LAST link-local, non-loopback) address as the destination.
       */
#define	satosin6(sa)	((struct sockaddr_in6 *)(sa))
#define sin6tosa(sin6)	((struct sockaddr *)(sin6))
#define ifatoi6a(ifa)	((struct in6_ifaddr *)(ifa))
      struct in6_ifaddr *ti6a = NULL;

      for (i6a = in6_ifaddr; i6a; i6a = i6a->i6a_next)
        {
          /* Find first (non-link-local if possible) address for
             source usage.  If multiple link-locals, use last one found. */
	  if (IN6_IS_ADDR_LINKLOCAL(&I6A_SIN(i6a)->sin6_addr))
	    ti6a=i6a;
	  else if (!IN6_IS_ADDR_LOOPBACK(&I6A_SIN(i6a)->sin6_addr))
	    break;
        }
      if (i6a == NULL && ti6a != NULL)
	i6a = ti6a;
    }

  if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
    {
      register struct route6 *ro;

      i6a = NULL;
      /* 
       * If route is known or can be allocated now,
       * our src addr is taken from the rt_ifa, else punt.
       */
      ro = &inp->inp_route6;
      if (ro->ro_rt &&
	  (ro->ro_dst.sin6_family != sin6->sin6_family ||	
	   rt_key(ro->ro_rt)->sa_family != sin6->sin6_family ||
	   !IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &sin6->sin6_addr) ||
	   inp->inp_socket->so_options & SO_DONTROUTE))
	{
	  RTFREE(ro->ro_rt);
	  ro->ro_rt = NULL;
	}
      if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0 && /*XXX*/
	  (ro->ro_rt == NULL || ro->ro_rt->rt_ifp == NULL))
	{
	  /* No route yet, try and acquire one. */
	  ro->ro_dst.sin6_family = AF_INET6;  /* Is ro blanked out? */
	  ro->ro_dst.sin6_len = sizeof(struct sockaddr_in6);
	  ro->ro_dst.sin6_addr = sin6->sin6_addr;
	  /* 
	   *  Need to wipe out the flowlabel for ifa_ifwith*
	   *  but don't need to for rtalloc.
	   */
	  rtalloc((struct route *)ro);
	}

      if (ro->ro_rt == NULL)
	{
	  /*
	   * No route of any kind, so spray neighbor solicits out all
	   * interfaces, unless it's a multicast address.
	   */
	  if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
	    return ENETUNREACH;
	  ipv6_onlink_query((struct sockaddr_in6 *)&ro->ro_dst);
	  rtalloc((struct route *)ro);
	}
      if (ro->ro_rt == NULL)
	{
	  /*
	   * ipv6_onlink_query() should've added a route.  It probably
	   * failed.
	   */
	  DPRINTF(IDL_GROSS_EVENT, ("v6_output: onlink_query didn't add route!\n"));
	  return ENETUNREACH;
	}

      if (ro->ro_rt->rt_ifa == NULL)
	{
	  /*
	   * We have a route where we don't quite know which interface 
	   * the neighbor belongs to yet.  If I get here, I know that this
	   * route is not pre-allocated (such as done by in6_pcbconnect()),
	   * because those pre-allocators will do the same ipv6_onlink_query()
	   * and ipv6_verify_onlink() in advance.
	   *
	   * I can therefore free the route, and get it again.
	   */
	  int error;

	  RTFREE(ro->ro_rt);
	  ro->ro_rt = NULL;
	  switch (error = ipv6_verify_onlink(&ro->ro_dst))
	    {
	    case -1:
	      return ENETUNREACH;
	    case 0:
	      break;
	    default:
	      return error;
	    }
	  rtalloc((struct route *)ro);
	  if (ro->ro_rt == NULL || ro->ro_rt->rt_ifa == NULL)
	    panic("Oops2, I'm forgetting something after verify_onlink().");
	}


      /*
       * If we found a route, use the address
       * corresponding to the outgoing interface
       * unless it is the loopback (in case a route
       * to our address on another net goes to loopback).
       *
       * This code may be simplified if the above gyrations work.
       */
      if (ro->ro_rt && ro->ro_rt->rt_ifp &&
		!(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK))
	i6a = ifatoi6a(ro->ro_rt->rt_ifa);
      if (i6a == NULL)
	{
	  u_short fport = sin6->sin6_port;

	  /*
	   * Source address selection when there is no route.
	   *
	   * If ND out all if's is to be used, this is the point to do it.
	   * (Similar to when the route lookup fails in ipv6_output.c, and
	   * the 'on-link' assumption kicks in.)
	   *
	   * For multicast, use i6a of mcastdef.
	   */

	  sin6->sin6_port = 0;
	  i6a = ifatoi6a(ifa_ifwithdstaddr(sin6tosa(sin6)));
	  if (i6a == NULL)
	    i6a = ifatoi6a(ifa_ifwithnet(sin6tosa(sin6)));
	  sin6->sin6_port = fport;
	  if (i6a == NULL)
	    {
	      struct in6_ifaddr *ti6a = NULL;
	      
	      for (i6a = in6_ifaddr; i6a; i6a = i6a->i6a_next)
		{
		  /* Find first (non-local if possible) address for
		     source usage.  If multiple locals, use last one found. */
		  if (IN6_IS_ADDR_LINKLOCAL(&I6A_SIN(i6a)->sin6_addr))
		    ti6a=i6a;
		  else if (!IN6_IS_ADDR_LOOPBACK(&I6A_SIN(i6a)->sin6_addr))
		    break;
		}
	      if (i6a == NULL && ti6a != NULL)
		i6a = ti6a;
	    }
	  if (i6a == NULL)
	    return EADDRNOTAVAIL;
	}

      /*
       * If I'm "connecting" to a multicast address, gyrate properly to
       * get a source address based upon the user-requested mcast interface.
       */
      if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) && inp->inp_moptions6 != NULL &&
	  (inp->inp_flags & INP_IPV6_MCAST))
	{
	  struct ipv6_moptions *i6mo;
	  struct ifnet *ifp;
	  
	  i6mo = inp->inp_moptions6;
	  if (i6mo->i6mo_multicast_ifp != NULL)
	    {
	      ifp = i6mo->i6mo_multicast_ifp;
	      for (i6a = in6_ifaddr; i6a; i6a = i6a->i6a_next)
		if (i6a->i6a_ifp == ifp)  /* Linkloc vs. global? */
		  break;
	      if (i6a == NULL)
		return EADDRNOTAVAIL;
	    }
	}

      *plocal_sin = (struct sockaddr *)&i6a->i6a_addr;
    }

    return (0);
}
#endif /* __FreeBSD__ */

/*----------------------------------------------------------------------
 * Connect from a socket to a specified address.
 * Both address and port must be specified in argument sin6.
 * Eventually, flow labels will have to be dealt with here, as well.
 *
 * If don't have a local address for this socket yet,
 * then pick one.
 *
 * I believe this has to be called at splnet().
 ----------------------------------------------------------------------*/

int
in6_pcbconnect(inp, nam)
	register struct inpcb *inp;
#if __FreeBSD__
	struct sockaddr *nam;
#else /* __FreeBSD__ */
	struct mbuf *nam;
#endif /* __FreeBSD__ */
{
  struct in6_ifaddr *i6a;
  struct sockaddr_in6 *ifaddr = NULL;

#if __FreeBSD__
  register struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
#else /* __FreeBSD__ */
  register struct sockaddr_in6 *sin6 = mtod(nam, struct sockaddr_in6 *);
  if (nam->m_len != sizeof(struct sockaddr_in6))
    return (EINVAL);
#endif /* __FreeBSD__ */

  if (sin6->sin6_len != sizeof(struct sockaddr_in6))
    return (EINVAL);
  if (sin6->sin6_family != AF_INET6)
    return (EAFNOSUPPORT);
  if (sin6->sin6_port == 0)
    return (EADDRNOTAVAIL);

  if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
    {
      struct domain hackdomain, *save;
      struct mbuf hackmbuf;
      struct sockaddr_in *sin;
      int rc;

#if __FreeBSD__ 
      /*
       * FreeBSD doesn't want an mbuf to pcbconnect.
       */
      struct sockaddr_in hacksin;
#endif /* __FreeBSD__ */

      /*
       * Hmmm, if this is a v4-mapped v6 address, re-call in_pcbconnect
       * with a fake domain for now.  Then re-adjust the socket, and
       * return out of here.  Since this is called at splnet(), I don't
       * think temporarily altering the socket will matter.  XXX
       */

      /*
       * Can't have v6 talking to v4, now can we!
       */
      if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6) && 
	  !IN6_IS_ADDR_V4MAPPED(&inp->inp_laddr6))
	return EINVAL;  

      bzero(&hackdomain,sizeof(hackdomain));
      bzero(&hackmbuf,sizeof(hackmbuf));
      save = inp->inp_socket->so_proto->pr_domain;
      inp->inp_socket->so_proto->pr_domain = &hackdomain;
      hackdomain.dom_family = PF_INET;
#ifndef __FreeBSD__ 
      hackmbuf.m_hdr = nam->m_hdr;
#endif /* __FreeBSD__ */
      hackmbuf.m_len = sizeof(*sin);
      hackmbuf.m_data = hackmbuf.m_dat;

#if __FreeBSD__ 
      sin = &hacksin;
#else /* __FreeBSD__ */
      sin = mtod(&hackmbuf,struct sockaddr_in *);
#endif /* __FreeBSD__ */
      sin->sin_len = sizeof(*sin);
      sin->sin_family = AF_INET;
      sin->sin_port = sin6->sin6_port;
      sin->sin_addr.s_addr = sin6->sin6_addr.in6a_words[3];

#if __FreeBSD__
  {
#if !defined(_BSDI_VERSION) || (_BSDI_VERSION < 199802)
  struct proc *p = curproc;		/* XXX */
#else /* !defined(_BSDI_VERSION) || (_BSDI_VERSION < 199802) */
  struct proc *p = PCPU(curproc);		/* XXX */
#endif /* !defined(_BSDI_VERSION) || (_BSDI_VERSION < 199802) */
      rc = in_pcbconnect(inp, (struct sockaddr *) sin, p);
  }
#else /* __FreeBSD__ */
      rc = in_pcbconnect(inp,&hackmbuf);
#endif /* __FreeBSD__ */

      inp->inp_socket->so_proto->pr_domain = save;

      if (rc == 0)
	{
	  inp->inp_laddr6.in6a_words[2] = htonl(0xffff);
	  inp->inp_faddr6.in6a_words[2] = htonl(0xffff);
	  inp->inp_flags |= INP_IPV6_MAPPED;
	  inp->inp_flags &= ~INP_IPV6_UNDEC;
	}

      return rc;
    }

  if (in6_ifaddr && IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
    {
      /*
       * If the destination address is all 0's,
       * use the first non-loopback (and if possibly, non-link-local, else
       * use the LAST link-local, non-loopback) address as the destination.
       */
#define	satosin6(sa)	((struct sockaddr_in6 *)(sa))
#define sin6tosa(sin6)	((struct sockaddr *)(sin6))
#define ifatoi6a(ifa)	((struct in6_ifaddr *)(ifa))
      struct in6_ifaddr *ti6a = NULL;

      for (i6a = in6_ifaddr; i6a; i6a = i6a->i6a_next)
        {
          /* Find first (non-link-local if possible) address for
             source usage.  If multiple link-locals, use last one found. */
	  if (IN6_IS_ADDR_LINKLOCAL(&I6A_SIN(i6a)->sin6_addr))
	    ti6a=i6a;
	  else if (!IN6_IS_ADDR_LOOPBACK(&I6A_SIN(i6a)->sin6_addr))
	    break;
        }
      if (i6a == NULL && ti6a != NULL)
	i6a = ti6a;
    }

  if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
    {
      register struct route6 *ro;


      i6a = NULL;
      /* 
       * If route is known or can be allocated now,
       * our src addr is taken from the rt_ifa, else punt.
       */
      ro = &inp->inp_route6;
      if (ro->ro_rt &&
	  (ro->ro_dst.sin6_family != sin6->sin6_family ||	
	   rt_key(ro->ro_rt)->sa_family != sin6->sin6_family ||
	   !IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &sin6->sin6_addr) ||
	   inp->inp_socket->so_options & SO_DONTROUTE))
	{
	  RTFREE(ro->ro_rt);
	  ro->ro_rt = NULL;
	}
      if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0 && /*XXX*/
	  (ro->ro_rt == NULL || ro->ro_rt->rt_ifp == NULL))
	{
	  /* No route yet, try and acquire one. */
	  ro->ro_dst.sin6_family = AF_INET6;  /* Is ro blanked out? */
	  ro->ro_dst.sin6_len = sizeof(struct sockaddr_in6);
	  ro->ro_dst.sin6_addr = sin6->sin6_addr;
	  /* 
	   *  Need to wipe out the flowlabel for ifa_ifwith*
	   *  but don't need to for rtalloc.
	   */
	  rtalloc((struct route *)ro);
	}

      if (ro->ro_rt == NULL)
	{
	  /*
	   * No route of any kind, so spray neighbor solicits out all
	   * interfaces, unless it's a multicast address.
	   */
	  if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
	    return ENETUNREACH;
	  ipv6_onlink_query((struct sockaddr_in6 *)&ro->ro_dst);
	  rtalloc((struct route *)ro);
	}
      if (ro->ro_rt == NULL)
	{
	  /*
	   * ipv6_onlink_query() should've added a route.  It probably
	   * failed.
	   */
	  DPRINTF(GROSSEVENT, ("v6_output: onlink_query didn't add route!\n"));
	  return ENETUNREACH;
	}

      if (ro->ro_rt->rt_ifa == NULL)
	{
	  /*
	   * We have a route where we don't quite know which interface 
	   * the neighbor belongs to yet.  If I get here, I know that this
	   * route is not pre-allocated (such as done by in6_pcbconnect()),
	   * because those pre-allocators will do the same ipv6_onlink_query()
	   * and ipv6_verify_onlink() in advance.
	   *
	   * I can therefore free the route, and get it again.
	   */
	  int error;

	  RTFREE(ro->ro_rt);
	  ro->ro_rt = NULL;
	  switch (error = ipv6_verify_onlink(&ro->ro_dst))
	    {
	    case -1:
	      return ENETUNREACH;
	    case 0:
	      break;
	    default:
	      return error;
	    }
	  rtalloc((struct route *)ro);
	  if (ro->ro_rt == NULL || ro->ro_rt->rt_ifa == NULL)
	    panic("Oops2, I'm forgetting something after verify_onlink().");
	}


      /*
       * If we found a route, use the address
       * corresponding to the outgoing interface
       * unless it is the loopback (in case a route
       * to our address on another net goes to loopback).
       *
       * This code may be simplified if the above gyrations work.
       */
      if (ro->ro_rt && ro->ro_rt->rt_ifp &&
		!(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK))
	i6a = ifatoi6a(ro->ro_rt->rt_ifa);
      if (i6a == NULL)
	{
	  u_short fport = sin6->sin6_port;

	  /*
	   * Source address selection when there is no route.
	   *
	   * If ND out all if's is to be used, this is the point to do it.
	   * (Similar to when the route lookup fails in ipv6_output.c, and
	   * the 'on-link' assumption kicks in.)
	   *
	   * For multicast, use i6a of mcastdef.
	   */

	  sin6->sin6_port = 0;
	  i6a = ifatoi6a(ifa_ifwithdstaddr(sin6tosa(sin6)));
	  if (i6a == NULL)
	    i6a = ifatoi6a(ifa_ifwithnet(sin6tosa(sin6)));
	  sin6->sin6_port = fport;
	  if (i6a == NULL)
	    {
	      struct in6_ifaddr *ti6a = NULL;
	      
	      for (i6a = in6_ifaddr; i6a; i6a = i6a->i6a_next)
		{
		  /* Find first (non-local if possible) address for
		     source usage.  If multiple locals, use last one found. */
		  if (IN6_IS_ADDR_LINKLOCAL(&I6A_SIN(i6a)->sin6_addr))
		    ti6a=i6a;
		  else if (!IN6_IS_ADDR_LOOPBACK(&I6A_SIN(i6a)->sin6_addr))
		    break;
		}
	      if (i6a == NULL && ti6a != NULL)
		i6a = ti6a;
	    }
	  if (i6a == NULL)
	    return EADDRNOTAVAIL;
	}

      /*
       * If I'm "connecting" to a multicast address, gyrate properly to
       * get a source address based upon the user-requested mcast interface.
       */
      if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) && inp->inp_moptions6 != NULL &&
	  (inp->inp_flags & INP_IPV6_MCAST))
	{
	  struct ipv6_moptions *i6mo;
	  struct ifnet *ifp;
	  
	  i6mo = inp->inp_moptions6;
	  if (i6mo->i6mo_multicast_ifp != NULL)
	    {
	      ifp = i6mo->i6mo_multicast_ifp;
	      for (i6a = in6_ifaddr; i6a; i6a = i6a->i6a_next)
		if (i6a->i6a_ifp == ifp)  /* Linkloc vs. global? */
		  break;
	      if (i6a == NULL)
		return EADDRNOTAVAIL;
	    }
	}

      ifaddr = (struct sockaddr_in6 *)&i6a->i6a_addr;
    }

#if __FreeBSD__
  if (in_pcblookup_hash(inp->inp_pcbinfo,
    ((IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6)) ?
    	(struct in_addr *)&ifaddr->sin6_addr :
	(struct in_addr *)&inp->inp_laddr6),
    	sin6->sin6_port, (struct in_addr *)&sin6->sin6_addr,
	inp->inp_lport, INPLOOKUP_IPV6)) return EADDRINUSE;
#else /* __FreeBSD__ */
#if __NetBSD__
  if (in6_pcblookup_connect(inp->inp_table,
    ((IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6)) ? &ifaddr->sin6_addr :
    &inp->inp_laddr6), sin6->sin6_port, &sin6->sin6_addr, inp->inp_lport))
     return EADDRINUSE;
#else /* __NetBSD__ */
#ifdef __OpenBSD__
  if (in_pcblookup(inp->inp_table, ((IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6)) ?
#else /* __OpenBSD__ */
  if (in_pcblookup(inp->inp_head, ((IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6)) ?
#endif /* __OpenBSD__ */
    	(struct in_addr *)&ifaddr->sin6_addr :
	(struct in_addr *)&inp->inp_laddr6),
    	sin6->sin6_port, (struct in_addr *)&sin6->sin6_addr,
	inp->inp_lport, INPLOOKUP_IPV6)) return EADDRINUSE;
#endif /* __NetBSD__ */
#endif /* __FreeBSD__ */

  if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
    {
      if (inp->inp_lport == 0)
	(void)in6_pcbbind(inp, NULL);  /* To find free port & bind to it. */
      inp->inp_laddr6 = ifaddr->sin6_addr;
    }
  inp->inp_faddr6 = sin6->sin6_addr;
  inp->inp_fport = sin6->sin6_port;

  /*
   * Assumes user specify flowinfo in network order.
   */
  inp->inp_ipv6.ipv6_versfl = htonl(0x60000000) | 
    (sin6->sin6_flowinfo & htonl(0x0fffffff));

#if __NetBSD__
  in_pcbstate(inp, INP_CONNECTED);
#endif /* __NetBSD__ */
  
#if __FreeBSD__ 
  /*
   * See pcbbind near the end for reasoning on setting this for a value to 
   * hash on. 
   */
#if 0
  inp->inp_laddr.s_addr = inp->inp_laddr6.in6a_words[3]
                        ^ inp->inp_laddr6.in6a_words[1];
#endif /* 0 */
  in_pcbrehash(inp);
#endif /* __FreeBSD__ */
  return 0;
}

/*----------------------------------------------------------------------
 * Pass some notification to all connections of a protocol
 * associated with address dst.  The local address and/or port numbers
 * may be specified to limit the search.  The "usual action" will be
 * taken, depending on the ctlinput cmd.  The caller must filter any
 * cmds that are uninteresting (e.g., no error in the map).
 * Call the protocol specific routine (if any) to report
 * any errors for each matching socket.
 *
 * Also perform input-side security policy check 
 *    once PCB to be notified has been located.
 *
 * Must be called at splnet.
 ----------------------------------------------------------------------*/

int
#ifdef IPSEC
in6_pcbnotify(head, dst, fport_arg, la, lport_arg, cmd, notify, m, nexthdr)
#else /* IPSEC */
in6_pcbnotify(head, dst, fport_arg, la, lport_arg, cmd, notify)
#endif /* IPSEC */
#if __NetBSD__ || __OpenBSD__
     struct inpcbtable *head;
#else /* __NetBSD__ || __OpenBSD__ */
#if __FreeBSD__ 
     struct inpcbhead *head;
#else /* __FreeBSD__ */
     struct inpcb *head;
#endif /* __FreeBSD__ */
#endif /* __NetBSD__ || __OpenBSD__ */
     struct sockaddr *dst;
     uint fport_arg;
     struct in6_addr *la;
     uint lport_arg;
     int cmd;
     void (*notify) __P((struct inpcb *, int));
#ifdef IPSEC
     struct mbuf *m;
     int nexthdr;
#endif /* IPSEC */
{
  register struct inpcb *inp, *oinp;
  struct in6_addr *faddr,laddr = *la;
  u_short fport = fport_arg, lport = lport_arg;
  int errno;
#ifdef IPSEC
  struct sockaddr_in6 srcsa, dstsa;
#endif /* IPSEC */

  DPRINTF(IDL_EVENT,("Entering in6_pcbnotify.  head = 0x%lx, dst is\n", (unsigned long)head));
  DDO(IDL_EVENT,dump_smart_sockaddr(dst));
  DPRINTF(IDL_EVENT,("fport_arg = %d, lport_arg = %d, cmd = %d\n",\
			   fport_arg, lport_arg, cmd));
  DDO(IDL_EVENT,printf("la is ");dump_in6_addr(la));

  if ((unsigned)cmd > PRC_NCMDS || dst->sa_family != AF_INET6)
    return 1;
  faddr = &(((struct sockaddr_in6 *)dst)->sin6_addr);
  if (IN6_IS_ADDR_UNSPECIFIED(faddr))
    return 1;
  if (IN6_IS_ADDR_V4MAPPED(faddr))
    {
      printf("Huh?  Thought in6_pcbnotify() never got called with mapped!\n");
    }
  
  /*
   * Redirects go to all references to the destination,
   * and use in_rtchange to invalidate the route cache.
   * Dead host indications: notify all references to the destination.
   * Otherwise, if we have knowledge of the local port and address,
   * deliver only to that socket.
   */

  if (PRC_IS_REDIRECT(cmd) || cmd == PRC_HOSTDEAD)
    {
      fport = 0;
      lport = 0;
      laddr = in6addr_any;
      if (cmd != PRC_HOSTDEAD)
	notify = in_rtchange;
    }
  errno = inet6ctlerrmap[cmd];

#ifdef IPSEC
  /* Build these again because args aren't necessarily correctly formed
     sockaddrs, and the policy code will eventually need that. -cmetz */

  memset(&srcsa, 0, sizeof(struct sockaddr_in6));
  srcsa.sin6_len = sizeof(struct sockaddr_in6);
  srcsa.sin6_family = AF_INET6;
  /* defer port */
  srcsa.sin6_addr = *faddr;

  memset(&dstsa, 0, sizeof(struct sockaddr_in6));
  dstsa.sin6_len = sizeof(struct sockaddr_in6);
  dstsa.sin6_family = AF_INET6;
  /* defer port */
  dstsa.sin6_addr = laddr;
#endif /* IPSEC */

#if __NetBSD__ || __OpenBSD__
  for (inp = head->inpt_queue.cqh_first;
       inp != (struct inpcb *)&head->inpt_queue;)
#else /* __NetBSD__ || __OpenBSD__ */
#if __FreeBSD__
  for (inp = head->lh_first; inp != NULL;)
#else /* __FreeBSD__ */
  for (inp = head->inp_next; inp != head;)
#endif /* __FreeBSD__ */
#endif /* __NetBSD__ || __OpenBSD__ */
    {
      if (!IN6_ARE_ADDR_EQUAL(&inp->inp_faddr6, faddr) ||
	  !inp->inp_socket ||
	  (lport && inp->inp_lport != lport) ||
	  (!IN6_IS_ADDR_UNSPECIFIED(&laddr) && !IN6_ARE_ADDR_EQUAL(&inp->inp_laddr6, &laddr)) ||
	  (fport && inp->inp_fport != fport))
	{
#if __NetBSD__ || __OpenBSD__
	  inp = inp->inp_queue.cqe_next;
#else /* __NetBSD__ || __OpenBSD__ */
#if __FreeBSD__
	  inp = inp->inp_list.le_next;
#else /* __FreeBSD__ */
	  inp = inp->inp_next;
#endif /* __FreeBSD__ */
#endif /* __NetBSD__ || __OpenBSD__ */
	  continue;
	}
      oinp = inp;

#if __NetBSD__ || __OpenBSD__
      inp = inp->inp_queue.cqe_next;
#else /* __NetBSD__ || __OpenBSD__ */
#if __FreeBSD__
      inp = inp->inp_list.le_next;
#else /* __FreeBSD__ */
      inp = inp->inp_next;
#endif /* __FreeBSD__ */
#endif /* __NetBSD__ || __OpenBSD__ */

      if (notify)
#ifdef IPSEC
	{
	  /* Pretend the packet came in for this source/destination port pair,
	     since that's what we care about for policy. If the passed in
	     fport and/or lport were nonzero, the comparison will make sure
	     they match that of the PCB and the right thing will happen.
	     -cmetz */
	  srcsa.sin6_port = oinp->inp_fport;
	  dstsa.sin6_port = oinp->inp_lport;

	  /* XXX - state arg should not be NULL */
	  if (!netproc_inputpolicy(oinp->inp_socket, (struct sockaddr *)&srcsa,
			          (struct sockaddr *)&dstsa, nexthdr, m, NULL,
				   NULL))
#endif /* IPSEC */
	  (*notify)(oinp, errno);
#ifdef IPSEC
	}
#endif /* IPSEC */
    }
   return 0;
}

/*----------------------------------------------------------------------
 * Get the local address/port, and put it in a sockaddr_in6.
 * This services the getsockname(2) call.
 ----------------------------------------------------------------------*/

int
in6_setsockaddr(inp, nam)
     register struct inpcb *inp;
#if __FreeBSD__
     struct sockaddr **nam; 
#else /* __FreeBSD__ */
     struct mbuf *nam;
#endif /* __FreeBSD__ */
{
  register struct sockaddr_in6 *sin6;


#if __FreeBSD__ 
  /*
   * In FreeBSD we have to allocate the sockaddr_in6 structure since we aren't
   * given an mbuf, but a sockaddr ** as the second argument. (i.e. a location
   * to reference the space this routine allocates.  
   */
  if (!(sin6 = (struct sockaddr_in6 *)malloc(sizeof(struct sockaddr_in6),M_SONAME, M_DONTWAIT)))
  	return ENOBUFS; /* XXX */

#else /* __FreeBSD__ */

  nam->m_len = sizeof(struct sockaddr_in6);
  sin6 = mtod(nam,struct sockaddr_in6 *);

#endif /* __FreeBSD__ */

  bzero ((caddr_t)sin6,sizeof(struct sockaddr_in6));
  sin6->sin6_family = AF_INET6;
  sin6->sin6_len = sizeof(struct sockaddr_in6);
  sin6->sin6_port = inp->inp_lport;
  sin6->sin6_addr = inp->inp_laddr6;

#if __FreeBSD__
  *nam = (struct sockaddr *) sin6;
#endif /* __FreeBSD__ */

  return 0;
}

/*----------------------------------------------------------------------
 * Get the foreign address/port, and put it in a sockaddr_in6.
 * This services the getpeername(2) call.
 ----------------------------------------------------------------------*/

int
in6_setpeeraddr(inp, nam)
     register struct inpcb *inp;
#if __FreeBSD__
     struct sockaddr **nam; 
#else /* __FreeBSD__ */
     struct mbuf *nam;
#endif /* __FreeBSD__ */
{
  register struct sockaddr_in6 *sin6;

#if __FreeBSD__ 
  /*
   * In FreeBSD we have to allocate the sockaddr_in6 structure since we aren't
   * given an mbuf, but a sockaddr ** as the second argument. (i.e. a location
   * to reference the space this routine allocates.  
   */
  if (!(sin6 = (struct sockaddr_in6 *)malloc(sizeof(struct sockaddr_in6),M_SONAME, M_DONTWAIT)))
  	return ENOBUFS; /* XXX */

#else /* __FreeBSD__ */

  nam->m_len = sizeof(struct sockaddr_in6);
  sin6 = mtod(nam,struct sockaddr_in6 *);

#endif /* __FreeBSD__ */

  bzero ((caddr_t)sin6,sizeof(struct sockaddr_in6));
  sin6->sin6_family = AF_INET6;
  sin6->sin6_len = sizeof(struct sockaddr_in6);
  sin6->sin6_port = inp->inp_fport;
  sin6->sin6_addr = inp->inp_faddr6;
  sin6->sin6_flowinfo = inp->inp_fflowinfo;

#if __FreeBSD__
  *nam = (struct sockaddr *) sin6;
#endif /* __FreeBSD__ */

  return 0;
}