Path: blob/main/crypto/krb5/src/lib/rpc/bindresvport.c
39537 views
/* lib/rpc/bindresvport.c */1/*2* Copyright (c) 2010, Oracle America, Inc.3*4* All rights reserved.5*6* Redistribution and use in source and binary forms, with or without7* modification, are permitted provided that the following conditions are met:8*9* * Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11*12* * Redistributions in binary form must reproduce the above copyright13* notice, this list of conditions and the following disclaimer in14* the documentation and/or other materials provided with the15* distribution.16*17* * Neither the name of the "Oracle America, Inc." nor the names of18* its contributors may be used to endorse or promote products19* derived from this software without specific prior written permission.20*21* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS22* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED23* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A24* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT25* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,26* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED27* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR28* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF29* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING30* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS31* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.32*/3334#include <string.h>35#include <stdlib.h>36#include <stdint.h>37#include <unistd.h>38#include <sys/types.h>39#include <sys/errno.h>40#include <sys/socket.h>41#include <netinet/in.h>42#include <gssrpc/rpc.h>43#include <errno.h>44#include "socket-utils.h"4546/*47* Bind a socket to a privileged IP port48*/49int50bindresvport_sa(int sd, struct sockaddr *sa)51{52int res;53static short port;54struct sockaddr_storage myaddr;55socklen_t salen;56int i;5758#define STARTPORT 60059#define ENDPORT (IPPORT_RESERVED - 1)60#define NPORTS (ENDPORT - STARTPORT + 1)61if (sa == NULL) {62salen = sizeof(myaddr);63sa = ss2sa(&myaddr);64res = getsockname(sd, sa, &salen);65if (res < 0)66return (-1);67}68if (!sa_is_inet(sa)) {69errno = EPFNOSUPPORT;70return (-1);71}72if (port == 0) {73port = (getpid() % NPORTS) + STARTPORT;74}75res = -1;76errno = EADDRINUSE;77for (i = 0; i < NPORTS && res < 0 && errno == EADDRINUSE; i++) {78sa_setport(sa, port++);79if (port > ENDPORT) {80port = STARTPORT;81}82res = bind(sd, sa, sa_socklen(sa));83}84return (res);85}8687int88bindresvport(int sd, struct sockaddr_in *sockin)89{90return (bindresvport_sa(sd, (struct sockaddr *)sockin));91}929394