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