Add system headers
[openafs.git] / src / rx / rx_user.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /* rx_user.c contains routines specific to the user space UNIX implementation of rx */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15
16 # include <sys/types.h>
17 # include <errno.h>
18 # include <signal.h>
19 # include <string.h>
20 #ifdef AFS_NT40_ENV
21 # include <WINNT/syscfg.h>
22 #else
23 # include <sys/socket.h>
24 # include <sys/file.h>
25 # include <netdb.h>
26 # include <sys/stat.h>
27 # include <netinet/in.h>
28 # include <sys/time.h>
29 # include <net/if.h>
30 # include <sys/ioctl.h>
31 # include <unistd.h>
32 #endif
33 # include <fcntl.h>
34 #if !defined(AFS_AIX_ENV) && !defined(AFS_NT40_ENV) 
35 # include <sys/syscall.h>
36 #endif
37 #include <afs/afs_args.h>
38 #include <afs/afsutil.h>
39
40 #ifndef IPPORT_USERRESERVED
41 /* If in.h doesn't define this, define it anyway.  Unfortunately, defining
42    this doesn't put the code into the kernel to restrict kernel assigned
43    port numbers to numbers below IPPORT_USERRESERVED...  */
44 #define IPPORT_USERRESERVED 5000
45 # endif
46
47 #ifndef AFS_NT40_ENV
48 # include <sys/time.h>
49 #endif
50 # include "rx.h"
51 # include "rx_globals.h"
52
53 #ifdef AFS_PTHREAD_ENV
54 #include <assert.h>
55
56 /*
57  * The rx_if_init_mutex mutex protects the following global variables:
58  * Inited
59  */
60
61 afs_kmutex_t rx_if_init_mutex;
62 #define LOCK_IF_INIT MUTEX_ENTER(&rx_if_init_mutex)
63 #define UNLOCK_IF_INIT MUTEX_EXIT(&rx_if_init_mutex)
64
65 /*
66  * The rx_if_mutex mutex protects the following global variables:
67  * myNetFlags
68  * myNetMTUs
69  * myNetMasks
70  */
71
72 afs_kmutex_t rx_if_mutex;
73 #define LOCK_IF MUTEX_ENTER(&rx_if_mutex)
74 #define UNLOCK_IF MUTEX_EXIT(&rx_if_mutex)
75 #else
76 #define LOCK_IF_INIT
77 #define UNLOCK_IF_INIT
78 #define LOCK_IF
79 #define UNLOCK_IF
80 #endif /* AFS_PTHREAD_ENV */
81
82
83 /*
84  * Make a socket for receiving/sending IP packets.  Set it into non-blocking
85  * and large buffering modes.  If port isn't specified, the kernel will pick
86  * one.  Returns the socket (>= 0) on success.  Returns OSI_NULLSOCKET on
87  * failure. Port must be in network byte order. 
88  */
89 osi_socket
90 rxi_GetHostUDPSocket(u_int ahost, u_short port)
91 {
92     int binds, code = 0;
93     osi_socket socketFd = OSI_NULLSOCKET;
94     struct sockaddr_in taddr;
95     char *name = "rxi_GetUDPSocket: ";
96 #ifdef AFS_LINUX22_ENV
97 #if defined(ADAPT_PMTU)
98     int pmtu=IP_PMTUDISC_WANT;
99     int recverr=1;
100 #else
101     int pmtu=IP_PMTUDISC_DONT;
102 #endif
103 #endif
104 #if defined(HAVE_LINUX_ERRQUEUE_H) && defined(ADAPT_PMTU)
105 #include <linux/types.h>
106 #include <linux/errqueue.h>
107 #ifndef IP_MTU
108 #define IP_MTU 14
109 #endif
110 #endif
111
112 #if !defined(AFS_NT40_ENV) 
113     if (ntohs(port) >= IPPORT_RESERVED && ntohs(port) < IPPORT_USERRESERVED) {
114 /*      (osi_Msg "%s*WARNING* port number %d is not a reserved port number.  Use port numbers above %d\n", name, port, IPPORT_USERRESERVED);
115 */ ;
116     }
117     if (ntohs(port) > 0 && ntohs(port) < IPPORT_RESERVED && geteuid() != 0) {
118         (osi_Msg
119          "%sport number %d is a reserved port number which may only be used by root.  Use port numbers above %d\n",
120          name, ntohs(port), IPPORT_USERRESERVED);
121         goto error;
122     }
123 #endif
124     socketFd = socket(AF_INET, SOCK_DGRAM, 0);
125
126     if (socketFd < 0) {
127         perror("socket");
128         goto error;
129     }
130
131 #ifdef AFS_NT40_ENV
132     rxi_xmit_init(socketFd);
133 #endif /* AFS_NT40_ENV */
134
135     taddr.sin_addr.s_addr = ahost;
136     taddr.sin_family = AF_INET;
137     taddr.sin_port = (u_short) port;
138 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
139     taddr.sin_len = sizeof(struct sockaddr_in);
140 #endif
141 #define MAX_RX_BINDS 10
142     for (binds = 0; binds < MAX_RX_BINDS; binds++) {
143         if (binds)
144             rxi_Delay(10);
145         code = bind(socketFd, (struct sockaddr *)&taddr, sizeof(taddr));
146         if (!code)
147             break;
148     }
149     if (code) {
150         perror("bind");
151         (osi_Msg "%sbind failed\n", name);
152         goto error;
153     }
154 #if !defined(AFS_NT40_ENV) 
155     /*
156      * Set close-on-exec on rx socket 
157      */
158     fcntl(socketFd, F_SETFD, 1);
159 #endif
160
161     /* Use one of three different ways of getting a socket buffer expanded to
162      * a reasonable size.
163      */
164     {
165         int greedy = 0;
166         int len1, len2;
167
168         len1 = 32766;
169         len2 = rx_UdpBufSize;
170
171         /* find the size closest to rx_UdpBufSize that will be accepted */
172         while (!greedy && len2 > len1) {
173             greedy =
174                 (setsockopt
175                   (socketFd, SOL_SOCKET, SO_RCVBUF, (char *)&len2,
176                    sizeof(len2)) >= 0);
177             if (!greedy)
178                 len2 /= 2;
179         }
180
181         /* but do not let it get smaller than 32K */ 
182         if (len2 < len1)
183             len2 = len1;
184
185         if (len1 < len2)
186             len1 = len2;
187
188
189         greedy =
190             (setsockopt
191              (socketFd, SOL_SOCKET, SO_SNDBUF, (char *)&len1,
192               sizeof(len1)) >= 0)
193             &&
194             (setsockopt
195              (socketFd, SOL_SOCKET, SO_RCVBUF, (char *)&len2,
196               sizeof(len2)) >= 0);
197         if (!greedy)
198             (osi_Msg "%s*WARNING* Unable to increase buffering on socket\n",
199              name);
200         if (rx_stats_active) {
201             MUTEX_ENTER(&rx_stats_mutex);
202             rx_stats.socketGreedy = greedy;
203             MUTEX_EXIT(&rx_stats_mutex);
204         }
205     }
206
207 #ifdef AFS_LINUX22_ENV
208     setsockopt(socketFd, SOL_IP, IP_MTU_DISCOVER, &pmtu, sizeof(pmtu));
209 #if defined(ADAPT_PMTU)
210     setsockopt(socketFd, SOL_IP, IP_RECVERR, &recverr, sizeof(recverr));
211 #endif
212 #endif
213     if (rxi_Listen(socketFd) < 0) {
214         goto error;
215     }
216
217     return socketFd;
218
219   error:
220 #ifdef AFS_NT40_ENV
221     if (socketFd >= 0)
222         closesocket(socketFd);
223 #else
224     if (socketFd >= 0)
225         close(socketFd);
226 #endif
227
228     return OSI_NULLSOCKET;
229 }
230
231 osi_socket
232 rxi_GetUDPSocket(u_short port)
233 {
234     return rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
235 }
236
237 void
238 osi_Panic(char *msg, ...)
239 {
240     va_list ap;
241     va_start(ap, msg);
242     (osi_Msg "Fatal Rx error: ");
243     (osi_VMsg msg, ap);
244     va_end(ap);
245     fflush(stderr);
246     fflush(stdout);
247     afs_abort();
248 }
249
250 /*
251  * osi_AssertFailU() -- used by the osi_Assert() macro.
252  */
253
254 void
255 osi_AssertFailU(const char *expr, const char *file, int line)
256 {
257     osi_Panic("assertion failed: %s, file: %s, line: %d\n", expr,
258               file, line);
259 }
260
261 #if defined(AFS_AIX32_ENV) && !defined(KERNEL)
262 #ifndef osi_Alloc
263 static const char memZero;
264 void *
265 osi_Alloc(afs_int32 x)
266 {
267     /* 
268      * 0-length allocs may return NULL ptr from malloc, so we special-case
269      * things so that NULL returned iff an error occurred 
270      */
271     if (x == 0)
272         return (void *)&memZero;
273     return(malloc(x));
274 }
275
276 void
277 osi_Free(void *x, afs_int32 size)
278 {
279     if (x == &memZero)
280         return;
281     free(x);
282 }
283 #endif
284 #endif /* defined(AFS_AIX32_ENV) && !defined(KERNEL) */
285
286 #define ADDRSPERSITE    16
287
288
289 static afs_uint32 rxi_NetAddrs[ADDRSPERSITE];   /* host order */
290 static int myNetMTUs[ADDRSPERSITE];
291 static int myNetMasks[ADDRSPERSITE];
292 static int myNetFlags[ADDRSPERSITE];
293 static u_int rxi_numNetAddrs;
294 static int Inited = 0;
295
296 #if defined(AFS_NT40_ENV) 
297 int
298 rxi_getaddr(void)
299 {
300     /* The IP address list can change so we must query for it */
301     rx_GetIFInfo();
302
303     /* we don't want to use the loopback adapter which is first */
304     /* this is a bad bad hack */
305     if (rxi_numNetAddrs > 1)
306         return htonl(rxi_NetAddrs[1]);  
307     else if (rxi_numNetAddrs > 0)
308         return htonl(rxi_NetAddrs[0]);
309     else
310         return 0;
311 }
312
313 /* 
314 ** return number of addresses 
315 ** and the addresses themselves in the buffer
316 ** maxSize - max number of interfaces to return.
317 */
318 int
319 rx_getAllAddr(afs_uint32 * buffer, int maxSize)
320 {
321     int count = 0, offset = 0;
322
323     /* The IP address list can change so we must query for it */
324     rx_GetIFInfo();
325
326 #ifdef AFS_DJGPP_ENV
327     /* we don't want to use the loopback adapter which is first */
328     /* this is a bad bad hack.
329      * and doesn't hold true on Windows.
330      */
331     if ( rxi_numNetAddrs > 1 )
332         offset = 1;
333 #endif /* AFS_DJGPP_ENV */
334
335     for (count = 0; offset < rxi_numNetAddrs && maxSize > 0;
336          count++, offset++, maxSize--)
337         buffer[count] = htonl(rxi_NetAddrs[offset]);
338
339     return count;
340 }
341
342 /* this function returns the total number of interface addresses
343  * the buffer has to be passed in by the caller. It also returns
344  * the matching interface mask and mtu.  All values are returned
345  * in network byte order.
346  */
347 int
348 rx_getAllAddrMaskMtu(afs_uint32 addrBuffer[], afs_uint32 maskBuffer[],
349                      afs_uint32 mtuBuffer[], int maxSize)
350 {
351     int count = 0, offset = 0;
352
353     /* The IP address list can change so we must query for it */
354     rx_GetIFInfo();
355
356 #ifdef AFS_DJGPP_ENV
357     /* we don't want to use the loopback adapter which is first */
358     /* this is a bad bad hack.
359      * and doesn't hold true on Windows.
360      */
361     if ( rxi_numNetAddrs > 1 )
362         offset = 1;
363 #endif /* AFS_DJGPP_ENV */
364
365     for (count = 0; 
366          offset < rxi_numNetAddrs && maxSize > 0;
367          count++, offset++, maxSize--) {
368         addrBuffer[count] = htonl(rxi_NetAddrs[offset]);
369         maskBuffer[count] = htonl(myNetMasks[offset]);
370         mtuBuffer[count]  = htonl(myNetMTUs[offset]);
371     }
372     return count;
373 }
374 #endif
375
376 #ifdef AFS_NT40_ENV
377 extern int rxinit_status;
378 void 
379 rxi_InitMorePackets(void) {
380     int npackets, ncbufs;
381
382     ncbufs = (rx_maxJumboRecvSize - RX_FIRSTBUFFERSIZE);
383     if (ncbufs > 0) {
384         ncbufs = ncbufs / RX_CBUFFERSIZE;
385         npackets = rx_initSendWindow - 1;
386         rxi_MorePackets(npackets * (ncbufs + 1));
387     }
388 }
389 void
390 rx_GetIFInfo(void)
391 {
392     u_int maxsize;
393     u_int rxsize;
394     afs_uint32 i;
395
396     LOCK_IF_INIT;
397     if (Inited) {
398         if (Inited < 2 && rxinit_status == 0) {
399             /* We couldn't initialize more packets earlier.
400              * Do it now. */
401             rxi_InitMorePackets();
402             Inited = 2;
403         }
404         UNLOCK_IF_INIT;
405         return;
406     }
407     Inited = 1;
408     UNLOCK_IF_INIT;
409
410     LOCK_IF;
411     rxi_numNetAddrs = ADDRSPERSITE;
412     (void)syscfg_GetIFInfo(&rxi_numNetAddrs, rxi_NetAddrs,
413                            myNetMasks, myNetMTUs, myNetFlags);
414
415     for (i = 0; i < rxi_numNetAddrs; i++) {
416         rxsize = rxi_AdjustIfMTU(myNetMTUs[i] - RX_IPUDP_SIZE);
417         maxsize =
418             rxi_nRecvFrags * rxsize + (rxi_nRecvFrags - 1) * UDP_HDR_SIZE;
419         maxsize = rxi_AdjustMaxMTU(rxsize, maxsize);
420         if (rx_maxReceiveSize < maxsize) {
421             rx_maxReceiveSize = MIN(RX_MAX_PACKET_SIZE, maxsize);
422             rx_maxReceiveSize =
423                 MIN(rx_maxReceiveSize, rx_maxReceiveSizeUser);
424         }
425
426     }
427     UNLOCK_IF;
428
429     /*
430      * If rxinit_status is still set, rx_InitHost() has yet to be called
431      * and we therefore do not have any mutex locks initialized.  As a
432      * result we cannot call rxi_MorePackets() without crashing.
433      */
434     if (rxinit_status)
435         return;
436
437     rxi_InitMorePackets();
438 }
439 #endif
440
441 static afs_uint32
442 fudge_netmask(afs_uint32 addr)
443 {
444     afs_uint32 msk;
445
446     if (IN_CLASSA(addr))
447         msk = IN_CLASSA_NET;
448     else if (IN_CLASSB(addr))
449         msk = IN_CLASSB_NET;
450     else if (IN_CLASSC(addr))
451         msk = IN_CLASSC_NET;
452     else
453         msk = 0;
454
455     return msk;
456 }
457
458
459
460 #if !defined(AFS_AIX_ENV) && !defined(AFS_NT40_ENV) && !defined(AFS_LINUX20_ENV) 
461 int
462 rxi_syscall(a3, a4, a5)
463      afs_uint32 a3, a4;
464      void *a5;
465 {
466     afs_uint32 rcode;
467     void (*old) ();
468
469     old = (void (*)())signal(SIGSYS, SIG_IGN);
470
471 #if defined(AFS_SGI_ENV)
472     rcode = afs_syscall(a3, a4, a5);
473 #else
474     rcode = syscall(AFS_SYSCALL, 28 /* AFSCALL_CALL */ , a3, a4, a5);
475 #endif /* AFS_SGI_ENV */
476
477     signal(SIGSYS, old);
478
479     return rcode;
480 }
481 #endif /* AFS_AIX_ENV */
482
483 #ifndef AFS_NT40_ENV
484 void
485 rx_GetIFInfo(void)
486 {
487     int s;
488     int i, j, len, res;
489     struct ifconf ifc;
490     struct ifreq ifs[ADDRSPERSITE];
491     struct ifreq *ifr;
492 #ifdef  AFS_AIX41_ENV
493     char buf[BUFSIZ], *cp, *cplim;
494 #endif
495     struct sockaddr_in *a;
496
497     LOCK_IF_INIT;
498     if (Inited) {
499         UNLOCK_IF_INIT;
500         return;
501     }
502     Inited = 1;
503     UNLOCK_IF_INIT;
504     LOCK_IF;
505     rxi_numNetAddrs = 0;
506     memset(rxi_NetAddrs, 0, sizeof(rxi_NetAddrs));
507     memset(myNetFlags, 0, sizeof(myNetFlags));
508     memset(myNetMTUs, 0, sizeof(myNetMTUs));
509     memset(myNetMasks, 0, sizeof(myNetMasks));
510     UNLOCK_IF;
511     s = socket(AF_INET, SOCK_DGRAM, 0);
512     if (s < 0)
513         return;
514
515 #ifdef  AFS_AIX41_ENV
516     ifc.ifc_len = sizeof(buf);
517     ifc.ifc_buf = buf;
518     ifr = ifc.ifc_req;
519 #else
520     ifc.ifc_len = sizeof(ifs);
521     ifc.ifc_buf = (caddr_t) & ifs[0];
522     memset(&ifs[0], 0, sizeof(ifs));
523 #endif
524     res = ioctl(s, SIOCGIFCONF, &ifc);
525     if (res < 0) {
526         /* fputs(stderr, "ioctl error IFCONF\n"); */
527         close(s);
528         return;
529     }
530
531     LOCK_IF;
532 #ifdef  AFS_AIX41_ENV
533 #define size(p) MAX((p).sa_len, sizeof(p))
534     cplim = buf + ifc.ifc_len;  /*skip over if's with big ifr_addr's */
535     for (cp = buf; cp < cplim;
536          cp += sizeof(ifr->ifr_name) + MAX(a->sin_len, sizeof(*a))) {
537         if (rxi_numNetAddrs >= ADDRSPERSITE)
538             break;
539
540         ifr = (struct ifreq *)cp;
541 #else
542     len = ifc.ifc_len / sizeof(struct ifreq);
543     if (len > ADDRSPERSITE)
544         len = ADDRSPERSITE;
545
546     for (i = 0; i < len; ++i) {
547         ifr = &ifs[i];
548         res = ioctl(s, SIOCGIFADDR, ifr);
549 #endif
550         if (res < 0) {
551             /* fputs(stderr, "ioctl error IFADDR\n");
552              * perror(ifr->ifr_name);   */
553             continue;
554         }
555         a = (struct sockaddr_in *)&ifr->ifr_addr;
556         if (a->sin_family != AF_INET)
557             continue;
558         rxi_NetAddrs[rxi_numNetAddrs] = ntohl(a->sin_addr.s_addr);
559         if (rxi_NetAddrs[rxi_numNetAddrs] == 0x7f000001) {
560             /* we don't really care about "localhost" */
561             continue;
562         }
563         for (j = 0; j < rxi_numNetAddrs; j++) {
564             if (rxi_NetAddrs[j] == rxi_NetAddrs[rxi_numNetAddrs])
565                 break;
566         }
567         if (j < rxi_numNetAddrs)
568             continue;
569
570         /* fprintf(stderr, "if %s addr=%x\n", ifr->ifr_name,
571          * rxi_NetAddrs[rxi_numNetAddrs]); */
572
573 #ifdef SIOCGIFFLAGS
574         res = ioctl(s, SIOCGIFFLAGS, ifr);
575         if (res == 0) {
576             myNetFlags[rxi_numNetAddrs] = ifr->ifr_flags;
577 #ifdef IFF_LOOPBACK
578             /* Handle aliased loopbacks as well. */
579             if (ifr->ifr_flags & IFF_LOOPBACK)
580                 continue;
581 #endif
582             /* fprintf(stderr, "if %s flags=%x\n", 
583              * ifr->ifr_name, ifr->ifr_flags); */
584         } else {                /*
585                                  * fputs(stderr, "ioctl error IFFLAGS\n");
586                                  * perror(ifr->ifr_name); */
587         }
588 #endif /* SIOCGIFFLAGS */
589
590 #if !defined(AFS_AIX_ENV)  && !defined(AFS_LINUX20_ENV)
591         /* this won't run on an AIX system w/o a cache manager */
592         rxi_syscallp = rxi_syscall;
593 #endif
594
595         /* If I refer to kernel extensions that aren't loaded on AIX, the 
596          * program refuses to load and run, so I simply can't include the 
597          * following code.  Fortunately, AIX is the one operating system in
598          * which the subsequent ioctl works reliably. */
599         if (rxi_syscallp) {
600             if ((*rxi_syscallp) (20 /*AFSOP_GETMTU */ ,
601                                  htonl(rxi_NetAddrs[rxi_numNetAddrs]),
602                                  &(myNetMTUs[rxi_numNetAddrs]))) {
603                 /* fputs(stderr, "syscall error GETMTU\n");
604                  * perror(ifr->ifr_name); */
605                 myNetMTUs[rxi_numNetAddrs] = 0;
606             }
607             if ((*rxi_syscallp) (42 /*AFSOP_GETMASK */ ,
608                                  htonl(rxi_NetAddrs[rxi_numNetAddrs]),
609                                  &(myNetMasks[rxi_numNetAddrs]))) {
610                 /* fputs(stderr, "syscall error GETMASK\n");
611                  * perror(ifr->ifr_name); */
612                 myNetMasks[rxi_numNetAddrs] = 0;
613             } else
614                 myNetMasks[rxi_numNetAddrs] =
615                     ntohl(myNetMasks[rxi_numNetAddrs]);
616             /* fprintf(stderr, "if %s mask=0x%x\n", 
617              * ifr->ifr_name, myNetMasks[rxi_numNetAddrs]); */
618         }
619
620         if (myNetMTUs[rxi_numNetAddrs] == 0) {
621             myNetMTUs[rxi_numNetAddrs] = OLD_MAX_PACKET_SIZE + RX_IPUDP_SIZE;
622 #ifdef SIOCGIFMTU
623             res = ioctl(s, SIOCGIFMTU, ifr);
624             if ((res == 0) && (ifr->ifr_metric > 128)) {        /* sanity check */
625                 myNetMTUs[rxi_numNetAddrs] = ifr->ifr_metric;
626                 /* fprintf(stderr, "if %s mtu=%d\n", 
627                  * ifr->ifr_name, ifr->ifr_metric); */
628             } else {
629                 /* fputs(stderr, "ioctl error IFMTU\n");
630                  * perror(ifr->ifr_name); */
631             }
632 #endif
633         }
634
635         if (myNetMasks[rxi_numNetAddrs] == 0) {
636             myNetMasks[rxi_numNetAddrs] =
637                 fudge_netmask(rxi_NetAddrs[rxi_numNetAddrs]);
638 #ifdef SIOCGIFNETMASK
639             res = ioctl(s, SIOCGIFNETMASK, ifr);
640             if ((res == 0)) {
641                 a = (struct sockaddr_in *)&ifr->ifr_addr;
642                 myNetMasks[rxi_numNetAddrs] = ntohl(a->sin_addr.s_addr);
643                 /* fprintf(stderr, "if %s subnetmask=0x%x\n", 
644                  * ifr->ifr_name, myNetMasks[rxi_numNetAddrs]); */
645             } else {
646                 /* fputs(stderr, "ioctl error IFMASK\n");
647                  * perror(ifr->ifr_name); */
648             }
649 #endif
650         }
651
652         if (rxi_NetAddrs[rxi_numNetAddrs] != 0x7f000001) {      /* ignore lo0 */
653             int maxsize;
654             maxsize =
655                 rxi_nRecvFrags * (myNetMTUs[rxi_numNetAddrs] - RX_IP_SIZE);
656             maxsize -= UDP_HDR_SIZE;    /* only the first frag has a UDP hdr */
657             if (rx_maxReceiveSize < maxsize)
658                 rx_maxReceiveSize = MIN(RX_MAX_PACKET_SIZE, maxsize);
659             ++rxi_numNetAddrs;
660         }
661     }
662     UNLOCK_IF;
663     close(s);
664
665     /* have to allocate at least enough to allow a single packet to reach its
666      * maximum size, so ReadPacket will work.  Allocate enough for a couple
667      * of packets to do so, for good measure */
668     {
669         int npackets, ncbufs;
670
671         rx_maxJumboRecvSize =
672             RX_HEADER_SIZE + rxi_nDgramPackets * RX_JUMBOBUFFERSIZE +
673             (rxi_nDgramPackets - 1) * RX_JUMBOHEADERSIZE;
674         rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
675         ncbufs = (rx_maxJumboRecvSize - RX_FIRSTBUFFERSIZE);
676         if (ncbufs > 0) {
677             ncbufs = ncbufs / RX_CBUFFERSIZE;
678             npackets = rx_initSendWindow - 1;
679             rxi_MorePackets(npackets * (ncbufs + 1));
680         }
681     }
682 }
683 #endif /* AFS_NT40_ENV */
684
685 /* Called from rxi_FindPeer, when initializing a clear rx_peer structure,
686  * to get interesting information.
687  * Curiously enough, the rx_peerHashTable_lock currently protects the
688  * Inited variable (and hence rx_GetIFInfo). When the fs suite uses
689  * pthreads, this issue will need to be revisited.
690  */
691
692 void
693 rxi_InitPeerParams(struct rx_peer *pp)
694 {
695     afs_uint32 ppaddr;
696     u_short rxmtu;
697     int ix;
698 #if defined(ADAPT_PMTU) && defined(IP_MTU)
699     int sock;
700     struct sockaddr_in addr;
701 #endif
702
703
704
705     LOCK_IF_INIT;
706     if (!Inited) {
707         UNLOCK_IF_INIT;
708         /*
709          * there's a race here since more than one thread could call
710          * rx_GetIFInfo.  The race stops in rx_GetIFInfo.
711          */
712         rx_GetIFInfo();
713     } else {
714         UNLOCK_IF_INIT;
715     }
716
717 #ifdef ADAPT_MTU
718     /* try to second-guess IP, and identify which link is most likely to
719      * be used for traffic to/from this host. */
720     ppaddr = ntohl(pp->host);
721
722     pp->ifMTU = 0;
723     pp->timeout.sec = 2;
724     pp->rateFlag = 2;           /* start timing after two full packets */
725     /* I don't initialize these, because I presume they are bzero'd... 
726      * pp->burstSize pp->burst pp->burstWait.sec pp->burstWait.usec
727      * pp->timeout.usec */
728
729     LOCK_IF;
730     for (ix = 0; ix < rxi_numNetAddrs; ++ix) {
731         if ((rxi_NetAddrs[ix] & myNetMasks[ix]) == (ppaddr & myNetMasks[ix])) {
732 #ifdef IFF_POINTOPOINT
733             if (myNetFlags[ix] & IFF_POINTOPOINT)
734                 pp->timeout.sec = 4;
735 #endif /* IFF_POINTOPOINT */
736             rxmtu = myNetMTUs[ix] - RX_IPUDP_SIZE;
737             if (rxmtu < RX_MIN_PACKET_SIZE)
738                 rxmtu = RX_MIN_PACKET_SIZE;
739             if (pp->ifMTU < rxmtu)
740                 pp->ifMTU = MIN(rx_MyMaxSendSize, rxmtu);
741         }
742     }
743     UNLOCK_IF;
744     if (!pp->ifMTU) {           /* not local */
745         pp->timeout.sec = 3;
746         pp->ifMTU = MIN(rx_MyMaxSendSize, RX_REMOTE_PACKET_SIZE);
747     }
748 #else /* ADAPT_MTU */
749     pp->rateFlag = 2;           /* start timing after two full packets */
750     pp->timeout.sec = 2;
751     pp->ifMTU = MIN(rx_MyMaxSendSize, OLD_MAX_PACKET_SIZE);
752 #endif /* ADAPT_MTU */
753 #if defined(ADAPT_PMTU) && defined(IP_MTU)
754     sock=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
755     if (sock >= 0) {
756       addr.sin_family = AF_INET;
757       addr.sin_addr.s_addr = pp->host;
758       addr.sin_port = pp->port;
759       if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
760         int mtu=0;
761         socklen_t s = sizeof(mtu);
762         if (getsockopt(sock, SOL_IP, IP_MTU, &mtu, &s)== 0) {
763           pp->ifMTU = MIN(mtu - RX_IPUDP_SIZE, pp->ifMTU);
764         }
765       }
766       close(sock);
767     }
768 #endif
769     pp->ifMTU = rxi_AdjustIfMTU(pp->ifMTU);
770     pp->maxMTU = OLD_MAX_PACKET_SIZE;   /* for compatibility with old guys */
771     pp->natMTU = MIN((int)pp->ifMTU, OLD_MAX_PACKET_SIZE);
772     pp->maxDgramPackets =
773         MIN(rxi_nDgramPackets,
774             rxi_AdjustDgramPackets(rxi_nSendFrags, pp->ifMTU));
775     pp->ifDgramPackets =
776         MIN(rxi_nDgramPackets,
777             rxi_AdjustDgramPackets(rxi_nSendFrags, pp->ifMTU));
778     pp->maxDgramPackets = 1;
779     /* Initialize slow start parameters */
780     pp->MTU = MIN(pp->natMTU, pp->maxMTU);
781     pp->cwind = 1;
782     pp->nDgramPackets = 1;
783     pp->congestSeq = 0;
784 }
785
786 /* Don't expose jumobgram internals. */
787 void
788 rx_SetNoJumbo(void)
789 {
790     rx_maxReceiveSize = OLD_MAX_PACKET_SIZE;
791     rxi_nSendFrags = rxi_nRecvFrags = 1;
792 }
793
794 /* Override max MTU.  If rx_SetNoJumbo is called, it must be 
795    called before calling rx_SetMaxMTU since SetNoJumbo clobbers rx_maxReceiveSize */
796 void
797 rx_SetMaxMTU(int mtu)
798 {
799     rx_MyMaxSendSize = rx_maxReceiveSizeUser = rx_maxReceiveSize = mtu;
800 }
801
802 #if defined(HAVE_LINUX_ERRQUEUE_H) && defined(ADAPT_PMTU)
803 int
804 rxi_HandleSocketError(int socket)
805 {
806     struct msghdr msg;
807     struct cmsghdr *cmsg;
808     struct sock_extended_err *err;
809     struct sockaddr_in addr;
810     struct sockaddr *offender;
811     char controlmsgbuf[256];
812     int ret=0;
813     int code;
814
815     msg.msg_name = &addr;
816     msg.msg_namelen = sizeof(addr);
817     msg.msg_iov = NULL;
818     msg.msg_iovlen = 0;
819     msg.msg_control = controlmsgbuf;
820     msg.msg_controllen = 256;
821     msg.msg_flags = 0;
822     code = recvmsg(socket, &msg, MSG_ERRQUEUE|MSG_DONTWAIT|MSG_TRUNC);
823
824     if (code < 0 || !(msg.msg_flags & MSG_ERRQUEUE))
825         goto out;
826
827     for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
828        if ((char *)cmsg - controlmsgbuf > msg.msg_controllen - CMSG_SPACE(0) ||
829            (char *)cmsg - controlmsgbuf > msg.msg_controllen - CMSG_SPACE(cmsg->cmsg_len) ||
830            cmsg->cmsg_len == 0) {
831            cmsg = 0;
832            break;
833         }
834         if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_RECVERR)
835             break;
836     }
837     if (!cmsg)
838         goto out;
839     ret=1;
840     err =(struct sock_extended_err *) CMSG_DATA(cmsg);
841     
842     if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
843         rxi_SetPeerMtu(addr.sin_addr.s_addr, addr.sin_port,
844                        err->ee_info - RX_IPUDP_SIZE);
845     }
846     /* other DEST_UNREACH's and TIME_EXCEEDED should be dealt with too */
847     
848 out:
849     return ret;
850 }
851 #endif