Standardize License information
[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 <afs/param.h>
13 # include <sys/types.h>
14 # include <errno.h>
15 # include <signal.h>
16 #ifdef AFS_NT40_ENV
17 # include <WINNT/syscfg.h>
18 #else
19 # include <sys/socket.h>
20 # include <sys/file.h>
21 # include <netdb.h>
22 # include <sys/stat.h>
23 # include <netinet/in.h>
24 # include <sys/time.h>
25 # include <net/if.h>
26 # include <sys/ioctl.h>
27 #endif
28 # include <fcntl.h>
29 #if !defined(AFS_AIX_ENV) && !defined(AFS_NT40_ENV)
30 # include <sys/syscall.h>
31 #endif
32 #include <afs/afs_args.h>
33 #include <afs/afsutil.h>
34
35 #ifndef IPPORT_USERRESERVED
36 /* If in.h doesn't define this, define it anyway.  Unfortunately, defining
37    this doesn't put the code into the kernel to restrict kernel assigned
38    port numbers to numbers below IPPORT_USERRESERVED...  */
39 #define IPPORT_USERRESERVED 5000
40 # endif
41
42 #ifndef AFS_NT40_ENV
43 # include <sys/time.h>
44 #endif
45 # include "rx.h"
46 # include "rx_globals.h"
47
48
49 extern void rxi_Delay();
50
51 #ifdef AFS_PTHREAD_ENV
52 #include <assert.h>
53
54 /*
55  * The rx_if_init_mutex mutex protects the following global variables:
56  * Inited
57  */
58
59 pthread_mutex_t rx_if_init_mutex;
60 #define LOCK_IF_INIT assert(pthread_mutex_lock(&rx_if_init_mutex)==0);
61 #define UNLOCK_IF_INIT assert(pthread_mutex_unlock(&rx_if_init_mutex)==0);
62
63 /*
64  * The rx_if_mutex mutex protects the following global variables:
65  * myNetFlags
66  * myNetMTUs
67  * myNetMasks
68  */
69
70 pthread_mutex_t rx_if_mutex;
71 #define LOCK_IF assert(pthread_mutex_lock(&rx_if_mutex)==0);
72 #define UNLOCK_IF assert(pthread_mutex_unlock(&rx_if_mutex)==0);
73 #else
74 #define LOCK_IF_INIT
75 #define UNLOCK_IF_INIT
76 #define LOCK_IF
77 #define UNLOCK_IF
78 #endif /* AFS_PTHREAD_ENV */
79
80
81 /*
82  * Make a socket for receiving/sending IP packets.  Set it into non-blocking
83  * and large buffering modes.  If port isn't specified, the kernel will pick
84  * one.  Returns the socket (>= 0) on success.  Returns OSI_NULLSOCKET on
85  * failure. Port must be in network byte order. 
86  */
87 osi_socket rxi_GetUDPSocket(u_short port)
88 {
89     int binds, code;
90     osi_socket socketFd = OSI_NULLSOCKET;
91     struct sockaddr_in taddr;
92     char *name = "rxi_GetUDPSocket: ";
93     extern int rxi_Listen(osi_socket sock);
94     int greedy;
95
96 #ifndef AFS_NT40_ENV
97     if (ntohs(port) >= IPPORT_RESERVED && ntohs(port) < IPPORT_USERRESERVED) {
98 /*      (osi_Msg "%s*WARNING* port number %d is not a reserved port number.  Use port numbers above %d\n", name, port, IPPORT_USERRESERVED);
99 */ ;
100     }
101     if (ntohs(port) > 0 && ntohs(port) < IPPORT_RESERVED && geteuid() != 0) {
102         (osi_Msg "%sport number %d is a reserved port number which may only be used by root.  Use port numbers above %d\n", name, ntohs(port), IPPORT_USERRESERVED);
103         goto error;
104     }
105 #endif
106     socketFd = socket(AF_INET, SOCK_DGRAM, 0);
107
108     if (socketFd < 0) {
109         perror("socket");
110         goto error;
111     }
112
113     taddr.sin_addr.s_addr = 0;
114     taddr.sin_family = AF_INET;
115     taddr.sin_port = (u_short)port;
116 #define MAX_RX_BINDS 10
117     for (binds=0; binds<MAX_RX_BINDS; binds++) {
118       if (binds) rxi_Delay (10);
119       code = bind(socketFd, (struct sockaddr *) &taddr, sizeof(taddr));
120       if (!code) break;
121     }
122     if (code) {
123       perror("bind");
124       (osi_Msg "%sbind failed\n", name);
125       goto error;
126     }
127
128 #ifndef AFS_NT40_ENV
129     /*
130      * Set close-on-exec on rx socket 
131      */
132     fcntl(socketFd, F_SETFD, 1);
133 #endif
134
135     /* Use one of three different ways of getting a socket buffer expanded to
136      * a reasonable size.
137      */
138     {
139         int len1, len2;
140
141         len1 = 32766;
142         len2 = rx_UdpBufSize;
143         greedy = 
144           (setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, (char *)&len2,
145                       sizeof(len2)) >= 0);
146         if (!greedy) {
147           len2=32766;  /* fall back to old size... uh-oh! */
148         }
149
150         greedy =
151           (setsockopt(socketFd, SOL_SOCKET, SO_SNDBUF, (char *)&len1,
152                       sizeof(len1)) >= 0) &&
153           (setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, (char *)&len2,
154                       sizeof(len2)) >= 0);
155     }
156
157     if (!greedy)
158         (osi_Msg "%s*WARNING* Unable to increase buffering on socket\n", name);
159     if (rxi_Listen(socketFd) < 0) {
160         goto error;
161     }
162
163     return socketFd;
164
165 error:
166 #ifdef AFS_NT40_ENV
167     if (socketFd >= 0) closesocket(socketFd);
168 #else
169     if (socketFd >= 0) close(socketFd);
170 #endif
171
172     MUTEX_ENTER(&rx_stats_mutex);
173     rx_stats.socketGreedy = greedy;
174     MUTEX_EXIT(&rx_stats_mutex);
175     return OSI_NULLSOCKET;
176 }
177
178 void osi_Panic(msg, a1, a2, a3)
179     char *msg;
180 {
181     (osi_Msg "Fatal Rx error: ");
182     (osi_Msg msg, a1, a2, a3);
183     fflush(stderr);
184     fflush(stdout);
185     afs_abort();
186 }
187
188 /*
189  * osi_AssertFailU() -- used by the osi_Assert() macro.
190  */
191
192 void osi_AssertFailU(const char *expr, const char *file, int line)
193 {
194     osi_Panic("assertion failed: %s, file: %s, line: %d\n", expr, file, line);
195 }
196
197 #ifdef  AFS_AIX32_ENV
198 #ifndef osi_Alloc
199 static const char memZero;
200 char * osi_Alloc(x)
201     afs_int32 x; 
202 {
203     /* 
204      * 0-length allocs may return NULL ptr from osi_kalloc, so we special-case
205      * things so that NULL returned iff an error occurred 
206      */
207     if (x == 0) return &memZero;
208     return ((char *) malloc(x));
209 }
210
211 osi_Free(x, size)
212     char *x;
213     afs_int32 size; 
214 {
215     if (x == &memZero) return;
216     free((char *)x);
217 }
218 #endif
219 #endif /* AFS_AIX32_ENV */
220
221 #define ADDRSPERSITE    16
222
223
224 afs_uint32 rxi_NetAddrs[ADDRSPERSITE]; /* host order */
225 static int myNetMTUs[ADDRSPERSITE];
226 static int myNetMasks[ADDRSPERSITE];
227 static int myNetFlags[ADDRSPERSITE];
228 u_int rxi_numNetAddrs;
229 static int Inited = 0;
230
231 #if defined(AFS_NT40_ENV)
232 int rxi_getaddr(void)
233 {
234     if (rxi_numNetAddrs > 0)
235         return htonl(rxi_NetAddrs[0]);
236     else
237         return 0;
238 }
239
240 /* 
241 ** return number of addresses 
242 ** and the addresses themselves in the buffer
243 ** maxSize - max number of interfaces to return.
244 */
245 int rx_getAllAddr (afs_int32 *buffer, int maxSize)
246 {
247     int count = 0;
248     for (count = 0; count < rxi_numNetAddrs && maxSize > 0; count++, maxSize--)
249         buffer[count] = htonl(rxi_NetAddrs[count]);
250
251     return count;
252 }
253
254 #endif
255
256 #ifdef AFS_NT40_ENV
257
258 void rx_GetIFInfo(void)
259 {
260     LOCK_IF_INIT
261     if (Inited) {
262         UNLOCK_IF_INIT
263         return;
264     }
265     else {
266         u_int maxsize;
267         u_int rxsize;
268         int npackets, ncbufs;
269         afs_uint32 i;
270
271         Inited = 1;
272         UNLOCK_IF_INIT
273         rxi_numNetAddrs = ADDRSPERSITE;
274
275         LOCK_IF
276         (void) syscfg_GetIFInfo(&rxi_numNetAddrs, rxi_NetAddrs,
277                                 myNetMasks, myNetMTUs, myNetFlags);
278
279         for (i=0; i<rxi_numNetAddrs; i++) {
280             rxsize = rxi_AdjustIfMTU(myNetMTUs[i] - RX_IPUDP_SIZE);
281             maxsize = rxi_nRecvFrags*rxsize + (rxi_nRecvFrags-1)*UDP_HDR_SIZE;
282             maxsize = rxi_AdjustMaxMTU(rxsize, maxsize);
283             if (rx_maxReceiveSize < maxsize)  {
284                 rx_maxReceiveSize = MIN( RX_MAX_PACKET_SIZE, maxsize);
285                 rx_maxReceiveSize = MIN( rx_maxReceiveSize,
286                                          rx_maxReceiveSizeUser);
287             }
288
289         }
290         UNLOCK_IF
291         ncbufs = (rx_maxJumboRecvSize - RX_FIRSTBUFFERSIZE);
292         if (ncbufs > 0) {
293             ncbufs = ncbufs / RX_CBUFFERSIZE;
294             npackets = rx_initSendWindow -1;
295             rxi_MorePackets(npackets*(ncbufs+1));
296         }
297     }
298 }
299     
300 #endif
301
302 static afs_uint32 fudge_netmask(addr) 
303 afs_uint32 addr;
304 {
305 afs_uint32 msk;
306
307     if (IN_CLASSA(addr)) msk = IN_CLASSA_NET;
308     else if (IN_CLASSB(addr)) msk = IN_CLASSB_NET;
309     else if (IN_CLASSC(addr)) msk = IN_CLASSC_NET;
310     else msk = 0;
311
312 return msk;
313 }
314
315
316
317 #if !defined(AFS_AIX_ENV) && !defined(AFS_NT40_ENV) && !defined(AFS_LINUX20_ENV)
318 int rxi_syscall(a3, a4, a5)
319 afs_uint32 a3, a4;
320 void * a5;
321 {
322   afs_uint32 rcode;
323   void (*old)();
324         
325   old = (void (*)())signal(SIGSYS, SIG_IGN);    
326
327 #if defined(AFS_SGI_ENV)
328   rcode = afs_syscall(a3, a4, a5);
329 #else
330   rcode = syscall (AFS_SYSCALL, 28 /* AFSCALL_CALL */, a3, a4, a5);
331 #endif /* AFS_SGI_ENV */
332
333   signal(SIGSYS, old);  
334
335 return rcode;
336 }
337 #endif /* AFS_AIX_ENV */
338
339 #ifndef AFS_NT40_ENV
340 void rx_GetIFInfo()
341 {
342     int     s;
343     int     i, j, len, res;
344     struct ifconf   ifc;
345     struct ifreq    ifs[ADDRSPERSITE];
346     struct ifreq ifreq, *ifr;
347 #ifdef  AFS_AIX41_ENV
348     char buf[BUFSIZ], *cp, *cplim;
349 #endif
350     struct sockaddr_in *a;
351
352     LOCK_IF_INIT
353     if (Inited) {
354       UNLOCK_IF_INIT
355       return;
356     }
357     Inited = 1;
358     UNLOCK_IF_INIT
359
360     LOCK_IF
361     rxi_numNetAddrs = 0;
362     bzero(rxi_NetAddrs, sizeof(rxi_NetAddrs));
363     bzero(myNetFlags, sizeof(myNetFlags));
364     bzero(myNetMTUs, sizeof(myNetMTUs));
365     bzero(myNetMasks, sizeof(myNetMasks));
366     UNLOCK_IF
367
368     s = socket(AF_INET, SOCK_DGRAM, 0);
369     if (s < 0) return;
370
371 #ifdef  AFS_AIX41_ENV
372     ifc.ifc_len = sizeof (buf);
373     ifc.ifc_buf = buf;
374     ifr = ifc.ifc_req;
375 #else
376     ifc.ifc_len = sizeof(ifs);
377     ifc.ifc_buf = (caddr_t) &ifs[0];
378     bzero(&ifs[0], sizeof(ifs));
379 #endif 
380     res = ioctl(s, SIOCGIFCONF, &ifc);
381     if (res < 0) {
382       /* fputs(stderr, "ioctl error IFCONF\n"); */
383       close(s);
384       return;
385     }
386
387     LOCK_IF
388
389 #ifdef  AFS_AIX41_ENV
390 #define size(p) MAX((p).sa_len, sizeof(p))
391     cplim = buf + ifc.ifc_len; /*skip over if's with big ifr_addr's */
392     for (cp = buf; cp < cplim ;
393          cp += sizeof(ifr->ifr_name) + MAX(a->sin_len, sizeof(*a))) {
394         if (rxi_numNetAddrs >= ADDRSPERSITE)
395             break;
396
397         ifr = (struct ifreq *)cp;
398 #else
399     len = ifc.ifc_len / sizeof(struct ifreq);
400     if (len > ADDRSPERSITE)
401       len = ADDRSPERSITE;
402
403     for (i = 0; i < len; ++i) {
404         ifr = &ifs[i];
405         res = ioctl(s, SIOCGIFADDR, ifr);
406 #endif
407         if (res < 0) {
408           /* fputs(stderr, "ioctl error IFADDR\n");
409             perror(ifr->ifr_name);   */
410           continue;
411         }
412         a = (struct sockaddr_in *) &ifr->ifr_addr;
413         if (a->sin_family != AF_INET) continue;
414         rxi_NetAddrs[rxi_numNetAddrs] = ntohl(a->sin_addr.s_addr);
415         if (rxi_NetAddrs[rxi_numNetAddrs] == 0x7f000001) {
416           /* we don't really care about "localhost" */
417           continue;
418         }
419         for (j=0; j < rxi_numNetAddrs; j++) {
420            if (rxi_NetAddrs[j] == rxi_NetAddrs[rxi_numNetAddrs])
421               break;
422         }
423         if (j < rxi_numNetAddrs) continue;
424
425         /* fprintf(stderr, "if %s addr=%x\n", ifr->ifr_name,
426                 rxi_NetAddrs[rxi_numNetAddrs]); */
427
428 #ifdef SIOCGIFFLAGS
429         res = ioctl(s, SIOCGIFFLAGS, ifr);
430         if (res == 0) {
431             myNetFlags[rxi_numNetAddrs] = ifr->ifr_flags;
432 #ifdef IFF_LOOPBACK
433             /* Handle aliased loopbacks as well. */
434             if (ifr->ifr_flags & IFF_LOOPBACK)
435                 continue;
436 #endif
437             /* fprintf(stderr, "if %s flags=%x\n", 
438                     ifr->ifr_name, ifr->ifr_flags); */
439         }
440         else { /*
441           fputs(stderr, "ioctl error IFFLAGS\n");
442           perror(ifr->ifr_name); */
443         }
444 #endif /* SIOCGIFFLAGS */
445
446 #if !defined(AFS_AIX_ENV)  && !defined(AFS_LINUX20_ENV)
447         /* this won't run on an AIX system w/o a cache manager */
448         rxi_syscallp = rxi_syscall;
449 #endif
450
451         /* If I refer to kernel extensions that aren't loaded on AIX, the 
452          * program refuses to load and run, so I simply can't include the 
453          * following code.  Fortunately, AIX is the one operating system in
454          * which the subsequent ioctl works reliably. */
455         if (rxi_syscallp) {
456           if ((*rxi_syscallp)( 20 /*AFSOP_GETMTU*/,  
457                               htonl(rxi_NetAddrs[rxi_numNetAddrs]),
458                               &(myNetMTUs[rxi_numNetAddrs]))) {
459             /* fputs(stderr, "syscall error GETMTU\n");
460                perror(ifr->ifr_name); */
461             myNetMTUs[rxi_numNetAddrs] = 0;
462           }
463           if ((*rxi_syscallp)(42 /*AFSOP_GETMASK*/,  
464                               htonl(rxi_NetAddrs[rxi_numNetAddrs]),
465                               &(myNetMasks[rxi_numNetAddrs]))) {
466             /* fputs(stderr, "syscall error GETMASK\n");
467                perror(ifr->ifr_name); */
468             myNetMasks[rxi_numNetAddrs] = 0;
469           }
470           else myNetMasks[rxi_numNetAddrs] = ntohl( myNetMasks[rxi_numNetAddrs]);
471            /* fprintf(stderr, "if %s mask=0x%x\n", 
472              ifr->ifr_name, myNetMasks[rxi_numNetAddrs]);*/
473         }
474
475         if (myNetMTUs[rxi_numNetAddrs] == 0) {
476           myNetMTUs[rxi_numNetAddrs] = OLD_MAX_PACKET_SIZE + RX_IPUDP_SIZE;
477 #ifdef SIOCGIFMTU
478           res = ioctl(s, SIOCGIFMTU, ifr);
479           if ((res == 0) && (ifr->ifr_metric > 128))  { /* sanity check */
480             myNetMTUs[rxi_numNetAddrs] = ifr->ifr_metric;
481             /* fprintf(stderr, "if %s mtu=%d\n", 
482                     ifr->ifr_name, ifr->ifr_metric); */
483           }
484           else {
485             /* fputs(stderr, "ioctl error IFMTU\n");
486                perror(ifr->ifr_name); */
487           }
488 #endif
489         }
490
491         if (myNetMasks[rxi_numNetAddrs] == 0) {
492           myNetMasks[rxi_numNetAddrs] = fudge_netmask(rxi_NetAddrs[rxi_numNetAddrs]);
493 #ifdef SIOCGIFNETMASK
494           res = ioctl(s, SIOCGIFNETMASK, ifr);
495           if ((res == 0)) {
496             a = (struct sockaddr_in *) &ifr->ifr_addr;
497             myNetMasks[rxi_numNetAddrs] = ntohl(a->sin_addr.s_addr);
498             /* fprintf(stderr, "if %s subnetmask=0x%x\n", 
499                     ifr->ifr_name, myNetMasks[rxi_numNetAddrs]); */
500           }
501           else {
502             /* fputs(stderr, "ioctl error IFMASK\n");
503                perror(ifr->ifr_name); */
504           }
505 #endif
506         }
507
508         if (rxi_NetAddrs[rxi_numNetAddrs] != 0x7f000001) { /* ignore lo0 */
509            int maxsize;
510            maxsize = rxi_nRecvFrags*(myNetMTUs[rxi_numNetAddrs] - RX_IP_SIZE);
511            maxsize -= UDP_HDR_SIZE; /* only the first frag has a UDP hdr */
512            if (rx_maxReceiveSize < maxsize) 
513                 rx_maxReceiveSize = MIN( RX_MAX_PACKET_SIZE, maxsize);
514            ++rxi_numNetAddrs;
515         }
516     }
517     UNLOCK_IF
518     close(s);
519
520     /* have to allocate at least enough to allow a single packet to reach its
521      * maximum size, so ReadPacket will work.  Allocate enough for a couple
522      * of packets to do so, for good measure */
523     {
524       int npackets, ncbufs;
525
526       rx_maxJumboRecvSize = RX_HEADER_SIZE
527                             + rxi_nDgramPackets * RX_JUMBOBUFFERSIZE
528                             + (rxi_nDgramPackets-1) * RX_JUMBOHEADERSIZE;
529       rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
530       ncbufs = (rx_maxJumboRecvSize - RX_FIRSTBUFFERSIZE);
531       if (ncbufs > 0) {
532         ncbufs = ncbufs / RX_CBUFFERSIZE;
533         npackets = rx_initSendWindow -1;
534         rxi_MorePackets(npackets*(ncbufs+1));
535       }
536     }
537 }
538 #endif /* AFS_NT40_ENV */
539
540 /* Called from rxi_FindPeer, when initializing a clear rx_peer structure,
541  * to get interesting information.
542  * Curiously enough, the rx_peerHashTable_lock currently protects the
543  * Inited variable (and hence rx_GetIFInfo). When the fs suite uses
544  * pthreads, this issue will need to be revisited.
545  */
546
547 void rxi_InitPeerParams(struct rx_peer *pp)
548 {
549     afs_uint32 ppaddr;
550     u_short rxmtu;
551     int ix;
552
553
554
555     LOCK_IF_INIT
556     if (!Inited) {
557         UNLOCK_IF_INIT
558         /*
559          * there's a race here since more than one thread could call
560          * rx_GetIFInfo.  The race stops in rx_GetIFInfo.
561          */
562         rx_GetIFInfo();
563     } else {
564         UNLOCK_IF_INIT
565     }
566
567 #ifdef ADAPT_MTU
568     /* try to second-guess IP, and identify which link is most likely to
569      * be used for traffic to/from this host. */
570     ppaddr = ntohl(pp->host);
571
572     pp->ifMTU = 0;
573     pp->timeout.sec = 2;
574     pp->rateFlag = 2;   /* start timing after two full packets */
575     /* I don't initialize these, because I presume they are bzero'd... 
576      * pp->burstSize pp->burst pp->burstWait.sec pp->burstWait.usec
577      * pp->timeout.usec */
578   
579     LOCK_IF
580     for (ix = 0; ix < rxi_numNetAddrs; ++ix) {
581       if ((rxi_NetAddrs[ix] & myNetMasks[ix]) == (ppaddr & myNetMasks[ix])) {
582 #ifdef IFF_POINTOPOINT
583         if (myNetFlags[ix] & IFF_POINTOPOINT) 
584            pp->timeout.sec = 4;
585 #endif /* IFF_POINTOPOINT */
586         rxmtu = myNetMTUs[ix] - RX_IPUDP_SIZE;
587         if ( rxmtu < RX_MIN_PACKET_SIZE ) 
588           rxmtu = RX_MIN_PACKET_SIZE ;
589         if (pp->ifMTU < rxmtu) 
590           pp->ifMTU = MIN(rx_MyMaxSendSize, rxmtu);
591       }
592     }
593     UNLOCK_IF
594
595     if (!pp->ifMTU) { /* not local */
596         pp->timeout.sec = 3;
597         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
598     }
599 #else /* ADAPT_MTU */
600     pp->rateFlag = 2;   /* start timing after two full packets */
601     pp->timeout.sec = 2;
602     pp->ifMTU = OLD_MAX_PACKET_SIZE;
603 #endif /* ADAPT_MTU */
604     pp->ifMTU = rxi_AdjustIfMTU(pp->ifMTU);
605     pp->maxMTU = OLD_MAX_PACKET_SIZE;  /* for compatibility with old guys */
606     pp->natMTU = MIN((int)pp->ifMTU, OLD_MAX_PACKET_SIZE); 
607     pp->maxDgramPackets = MIN(rxi_nDgramPackets,
608                               rxi_AdjustDgramPackets(RX_MAX_FRAGS, pp->ifMTU));
609     pp->ifDgramPackets = MIN(rxi_nDgramPackets,
610                              rxi_AdjustDgramPackets(RX_MAX_FRAGS, pp->ifMTU));
611     pp->maxDgramPackets = 1;
612     /* Initialize slow start parameters */
613     pp->MTU = MIN(pp->natMTU, pp->maxMTU);
614     pp->cwind = 1;
615     pp->nDgramPackets = 1;
616     pp->congestSeq = 0;
617 }
618
619 /* Don't expose jumobgram internals. */
620 void rx_SetNoJumbo(void)
621 {
622     rx_maxReceiveSize = OLD_MAX_PACKET_SIZE;
623     rxi_nSendFrags = rxi_nRecvFrags = 1;
624 }