LCOV - code coverage report
Current view: top level - src/backend/utils/adt - network.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 537 696 77.2 %
Date: 2025-04-02 19:16:25 Functions: 60 70 85.7 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  *  PostgreSQL type definitions for the INET and CIDR types.
       3             :  *
       4             :  *  src/backend/utils/adt/network.c
       5             :  *
       6             :  *  Jon Postel RIP 16 Oct 1998
       7             :  */
       8             : 
       9             : #include "postgres.h"
      10             : 
      11             : #include <sys/socket.h>
      12             : #include <netinet/in.h>
      13             : #include <arpa/inet.h>
      14             : 
      15             : #include "access/stratnum.h"
      16             : #include "catalog/pg_opfamily.h"
      17             : #include "catalog/pg_type.h"
      18             : #include "common/hashfn.h"
      19             : #include "common/ip.h"
      20             : #include "lib/hyperloglog.h"
      21             : #include "libpq/libpq-be.h"
      22             : #include "libpq/pqformat.h"
      23             : #include "miscadmin.h"
      24             : #include "nodes/makefuncs.h"
      25             : #include "nodes/nodeFuncs.h"
      26             : #include "nodes/supportnodes.h"
      27             : #include "utils/builtins.h"
      28             : #include "utils/fmgroids.h"
      29             : #include "utils/guc.h"
      30             : #include "utils/inet.h"
      31             : #include "utils/lsyscache.h"
      32             : #include "utils/sortsupport.h"
      33             : 
      34             : 
      35             : /*
      36             :  * An IPv4 netmask size is a value in the range of 0 - 32, which is
      37             :  * represented with 6 bits in inet/cidr abbreviated keys where possible.
      38             :  *
      39             :  * An IPv4 inet/cidr abbreviated key can use up to 25 bits for subnet
      40             :  * component.
      41             :  */
      42             : #define ABBREV_BITS_INET4_NETMASK_SIZE  6
      43             : #define ABBREV_BITS_INET4_SUBNET        25
      44             : 
      45             : /* sortsupport for inet/cidr */
      46             : typedef struct
      47             : {
      48             :     int64       input_count;    /* number of non-null values seen */
      49             :     bool        estimating;     /* true if estimating cardinality */
      50             : 
      51             :     hyperLogLogState abbr_card; /* cardinality estimator */
      52             : } network_sortsupport_state;
      53             : 
      54             : static int32 network_cmp_internal(inet *a1, inet *a2);
      55             : static int  network_fast_cmp(Datum x, Datum y, SortSupport ssup);
      56             : static bool network_abbrev_abort(int memtupcount, SortSupport ssup);
      57             : static Datum network_abbrev_convert(Datum original, SortSupport ssup);
      58             : static List *match_network_function(Node *leftop,
      59             :                                     Node *rightop,
      60             :                                     int indexarg,
      61             :                                     Oid funcid,
      62             :                                     Oid opfamily);
      63             : static List *match_network_subset(Node *leftop,
      64             :                                   Node *rightop,
      65             :                                   bool is_eq,
      66             :                                   Oid opfamily);
      67             : static bool addressOK(unsigned char *a, int bits, int family);
      68             : static inet *internal_inetpl(inet *ip, int64 addend);
      69             : 
      70             : 
      71             : /*
      72             :  * Common INET/CIDR input routine
      73             :  */
      74             : static inet *
      75        6712 : network_in(char *src, bool is_cidr, Node *escontext)
      76             : {
      77             :     int         bits;
      78             :     inet       *dst;
      79             : 
      80        6712 :     dst = (inet *) palloc0(sizeof(inet));
      81             : 
      82             :     /*
      83             :      * First, check to see if this is an IPv6 or IPv4 address.  IPv6 addresses
      84             :      * will have a : somewhere in them (several, in fact) so if there is one
      85             :      * present, assume it's V6, otherwise assume it's V4.
      86             :      */
      87             : 
      88        6712 :     if (strchr(src, ':') != NULL)
      89        1266 :         ip_family(dst) = PGSQL_AF_INET6;
      90             :     else
      91        5446 :         ip_family(dst) = PGSQL_AF_INET;
      92             : 
      93        9138 :     bits = pg_inet_net_pton(ip_family(dst), src, ip_addr(dst),
      94        2426 :                             is_cidr ? ip_addrsize(dst) : -1);
      95        6712 :     if ((bits < 0) || (bits > ip_maxbits(dst)))
      96          30 :         ereturn(escontext, NULL,
      97             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
      98             :         /* translator: first %s is inet or cidr */
      99             :                  errmsg("invalid input syntax for type %s: \"%s\"",
     100             :                         is_cidr ? "cidr" : "inet", src)));
     101             : 
     102             :     /*
     103             :      * Error check: CIDR values must not have any bits set beyond the masklen.
     104             :      */
     105        6682 :     if (is_cidr)
     106             :     {
     107        2408 :         if (!addressOK(ip_addr(dst), bits, ip_family(dst)))
     108          30 :             ereturn(escontext, NULL,
     109             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     110             :                      errmsg("invalid cidr value: \"%s\"", src),
     111             :                      errdetail("Value has bits set to right of mask.")));
     112             :     }
     113             : 
     114        6652 :     ip_bits(dst) = bits;
     115        6652 :     SET_INET_VARSIZE(dst);
     116             : 
     117        6652 :     return dst;
     118             : }
     119             : 
     120             : Datum
     121        4286 : inet_in(PG_FUNCTION_ARGS)
     122             : {
     123        4286 :     char       *src = PG_GETARG_CSTRING(0);
     124             : 
     125        4286 :     PG_RETURN_INET_P(network_in(src, false, fcinfo->context));
     126             : }
     127             : 
     128             : Datum
     129        2426 : cidr_in(PG_FUNCTION_ARGS)
     130             : {
     131        2426 :     char       *src = PG_GETARG_CSTRING(0);
     132             : 
     133        2426 :     PG_RETURN_INET_P(network_in(src, true, fcinfo->context));
     134             : }
     135             : 
     136             : 
     137             : /*
     138             :  * Common INET/CIDR output routine
     139             :  */
     140             : static char *
     141       21498 : network_out(inet *src, bool is_cidr)
     142             : {
     143             :     char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];
     144             :     char       *dst;
     145             :     int         len;
     146             : 
     147       21498 :     dst = pg_inet_net_ntop(ip_family(src), ip_addr(src), ip_bits(src),
     148             :                            tmp, sizeof(tmp));
     149       21498 :     if (dst == NULL)
     150           0 :         ereport(ERROR,
     151             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     152             :                  errmsg("could not format inet value: %m")));
     153             : 
     154             :     /* For CIDR, add /n if not present */
     155       21498 :     if (is_cidr && strchr(tmp, '/') == NULL)
     156             :     {
     157        1902 :         len = strlen(tmp);
     158        1902 :         snprintf(tmp + len, sizeof(tmp) - len, "/%u", ip_bits(src));
     159             :     }
     160             : 
     161       21498 :     return pstrdup(tmp);
     162             : }
     163             : 
     164             : Datum
     165       12556 : inet_out(PG_FUNCTION_ARGS)
     166             : {
     167       12556 :     inet       *src = PG_GETARG_INET_PP(0);
     168             : 
     169       12556 :     PG_RETURN_CSTRING(network_out(src, false));
     170             : }
     171             : 
     172             : Datum
     173        8942 : cidr_out(PG_FUNCTION_ARGS)
     174             : {
     175        8942 :     inet       *src = PG_GETARG_INET_PP(0);
     176             : 
     177        8942 :     PG_RETURN_CSTRING(network_out(src, true));
     178             : }
     179             : 
     180             : 
     181             : /*
     182             :  *      network_recv        - converts external binary format to inet
     183             :  *
     184             :  * The external representation is (one byte apiece for)
     185             :  * family, bits, is_cidr, address length, address in network byte order.
     186             :  *
     187             :  * Presence of is_cidr is largely for historical reasons, though it might
     188             :  * allow some code-sharing on the client side.  We send it correctly on
     189             :  * output, but ignore the value on input.
     190             :  */
     191             : static inet *
     192           0 : network_recv(StringInfo buf, bool is_cidr)
     193             : {
     194             :     inet       *addr;
     195             :     char       *addrptr;
     196             :     int         bits;
     197             :     int         nb,
     198             :                 i;
     199             : 
     200             :     /* make sure any unused bits in a CIDR value are zeroed */
     201           0 :     addr = (inet *) palloc0(sizeof(inet));
     202             : 
     203           0 :     ip_family(addr) = pq_getmsgbyte(buf);
     204           0 :     if (ip_family(addr) != PGSQL_AF_INET &&
     205           0 :         ip_family(addr) != PGSQL_AF_INET6)
     206           0 :         ereport(ERROR,
     207             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     208             :         /* translator: %s is inet or cidr */
     209             :                  errmsg("invalid address family in external \"%s\" value",
     210             :                         is_cidr ? "cidr" : "inet")));
     211           0 :     bits = pq_getmsgbyte(buf);
     212           0 :     if (bits < 0 || bits > ip_maxbits(addr))
     213           0 :         ereport(ERROR,
     214             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     215             :         /* translator: %s is inet or cidr */
     216             :                  errmsg("invalid bits in external \"%s\" value",
     217             :                         is_cidr ? "cidr" : "inet")));
     218           0 :     ip_bits(addr) = bits;
     219           0 :     i = pq_getmsgbyte(buf);     /* ignore is_cidr */
     220           0 :     nb = pq_getmsgbyte(buf);
     221           0 :     if (nb != ip_addrsize(addr))
     222           0 :         ereport(ERROR,
     223             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     224             :         /* translator: %s is inet or cidr */
     225             :                  errmsg("invalid length in external \"%s\" value",
     226             :                         is_cidr ? "cidr" : "inet")));
     227             : 
     228           0 :     addrptr = (char *) ip_addr(addr);
     229           0 :     for (i = 0; i < nb; i++)
     230           0 :         addrptr[i] = pq_getmsgbyte(buf);
     231             : 
     232             :     /*
     233             :      * Error check: CIDR values must not have any bits set beyond the masklen.
     234             :      */
     235           0 :     if (is_cidr)
     236             :     {
     237           0 :         if (!addressOK(ip_addr(addr), bits, ip_family(addr)))
     238           0 :             ereport(ERROR,
     239             :                     (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     240             :                      errmsg("invalid external \"cidr\" value"),
     241             :                      errdetail("Value has bits set to right of mask.")));
     242             :     }
     243             : 
     244           0 :     SET_INET_VARSIZE(addr);
     245             : 
     246           0 :     return addr;
     247             : }
     248             : 
     249             : Datum
     250           0 : inet_recv(PG_FUNCTION_ARGS)
     251             : {
     252           0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     253             : 
     254           0 :     PG_RETURN_INET_P(network_recv(buf, false));
     255             : }
     256             : 
     257             : Datum
     258           0 : cidr_recv(PG_FUNCTION_ARGS)
     259             : {
     260           0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     261             : 
     262           0 :     PG_RETURN_INET_P(network_recv(buf, true));
     263             : }
     264             : 
     265             : 
     266             : /*
     267             :  *      network_send        - converts inet to binary format
     268             :  */
     269             : static bytea *
     270           0 : network_send(inet *addr, bool is_cidr)
     271             : {
     272             :     StringInfoData buf;
     273             :     char       *addrptr;
     274             :     int         nb,
     275             :                 i;
     276             : 
     277           0 :     pq_begintypsend(&buf);
     278           0 :     pq_sendbyte(&buf, ip_family(addr));
     279           0 :     pq_sendbyte(&buf, ip_bits(addr));
     280           0 :     pq_sendbyte(&buf, is_cidr);
     281           0 :     nb = ip_addrsize(addr);
     282           0 :     if (nb < 0)
     283           0 :         nb = 0;
     284           0 :     pq_sendbyte(&buf, nb);
     285           0 :     addrptr = (char *) ip_addr(addr);
     286           0 :     for (i = 0; i < nb; i++)
     287           0 :         pq_sendbyte(&buf, addrptr[i]);
     288           0 :     return pq_endtypsend(&buf);
     289             : }
     290             : 
     291             : Datum
     292           0 : inet_send(PG_FUNCTION_ARGS)
     293             : {
     294           0 :     inet       *addr = PG_GETARG_INET_PP(0);
     295             : 
     296           0 :     PG_RETURN_BYTEA_P(network_send(addr, false));
     297             : }
     298             : 
     299             : Datum
     300           0 : cidr_send(PG_FUNCTION_ARGS)
     301             : {
     302           0 :     inet       *addr = PG_GETARG_INET_PP(0);
     303             : 
     304           0 :     PG_RETURN_BYTEA_P(network_send(addr, true));
     305             : }
     306             : 
     307             : 
     308             : Datum
     309        3540 : inet_to_cidr(PG_FUNCTION_ARGS)
     310             : {
     311        3540 :     inet       *src = PG_GETARG_INET_PP(0);
     312             :     int         bits;
     313             : 
     314        3540 :     bits = ip_bits(src);
     315             : 
     316             :     /* safety check */
     317        3540 :     if ((bits < 0) || (bits > ip_maxbits(src)))
     318           0 :         elog(ERROR, "invalid inet bit length: %d", bits);
     319             : 
     320        3540 :     PG_RETURN_INET_P(cidr_set_masklen_internal(src, bits));
     321             : }
     322             : 
     323             : Datum
     324         258 : inet_set_masklen(PG_FUNCTION_ARGS)
     325             : {
     326         258 :     inet       *src = PG_GETARG_INET_PP(0);
     327         258 :     int         bits = PG_GETARG_INT32(1);
     328             :     inet       *dst;
     329             : 
     330         258 :     if (bits == -1)
     331         150 :         bits = ip_maxbits(src);
     332             : 
     333         258 :     if ((bits < 0) || (bits > ip_maxbits(src)))
     334           6 :         ereport(ERROR,
     335             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     336             :                  errmsg("invalid mask length: %d", bits)));
     337             : 
     338             :     /* clone the original data */
     339         252 :     dst = (inet *) palloc(VARSIZE_ANY(src));
     340         252 :     memcpy(dst, src, VARSIZE_ANY(src));
     341             : 
     342         252 :     ip_bits(dst) = bits;
     343             : 
     344         252 :     PG_RETURN_INET_P(dst);
     345             : }
     346             : 
     347             : Datum
     348         210 : cidr_set_masklen(PG_FUNCTION_ARGS)
     349             : {
     350         210 :     inet       *src = PG_GETARG_INET_PP(0);
     351         210 :     int         bits = PG_GETARG_INT32(1);
     352             : 
     353         210 :     if (bits == -1)
     354         102 :         bits = ip_maxbits(src);
     355             : 
     356         210 :     if ((bits < 0) || (bits > ip_maxbits(src)))
     357           6 :         ereport(ERROR,
     358             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     359             :                  errmsg("invalid mask length: %d", bits)));
     360             : 
     361         204 :     PG_RETURN_INET_P(cidr_set_masklen_internal(src, bits));
     362             : }
     363             : 
     364             : /*
     365             :  * Copy src and set mask length to 'bits' (which must be valid for the family)
     366             :  */
     367             : inet *
     368        4188 : cidr_set_masklen_internal(const inet *src, int bits)
     369             : {
     370        4188 :     inet       *dst = (inet *) palloc0(sizeof(inet));
     371             : 
     372        4188 :     ip_family(dst) = ip_family(src);
     373        4188 :     ip_bits(dst) = bits;
     374             : 
     375        4188 :     if (bits > 0)
     376             :     {
     377             :         Assert(bits <= ip_maxbits(dst));
     378             : 
     379             :         /* Clone appropriate bytes of the address, leaving the rest 0 */
     380        4188 :         memcpy(ip_addr(dst), ip_addr(src), (bits + 7) / 8);
     381             : 
     382             :         /* Clear any unwanted bits in the last partial byte */
     383        4188 :         if (bits % 8)
     384         276 :             ip_addr(dst)[bits / 8] &= ~(0xFF >> (bits % 8));
     385             :     }
     386             : 
     387             :     /* Set varlena header correctly */
     388        4188 :     SET_INET_VARSIZE(dst);
     389             : 
     390        4188 :     return dst;
     391             : }
     392             : 
     393             : /*
     394             :  *  Basic comparison function for sorting and inet/cidr comparisons.
     395             :  *
     396             :  * Comparison is first on the common bits of the network part, then on
     397             :  * the length of the network part, and then on the whole unmasked address.
     398             :  * The effect is that the network part is the major sort key, and for
     399             :  * equal network parts we sort on the host part.  Note this is only sane
     400             :  * for CIDR if address bits to the right of the mask are guaranteed zero;
     401             :  * otherwise logically-equal CIDRs might compare different.
     402             :  */
     403             : 
     404             : static int32
     405      159200 : network_cmp_internal(inet *a1, inet *a2)
     406             : {
     407      159200 :     if (ip_family(a1) == ip_family(a2))
     408             :     {
     409             :         int         order;
     410             : 
     411      137918 :         order = bitncmp(ip_addr(a1), ip_addr(a2),
     412      137918 :                         Min(ip_bits(a1), ip_bits(a2)));
     413      137918 :         if (order != 0)
     414      122170 :             return order;
     415       15748 :         order = ((int) ip_bits(a1)) - ((int) ip_bits(a2));
     416       15748 :         if (order != 0)
     417         876 :             return order;
     418       14872 :         return bitncmp(ip_addr(a1), ip_addr(a2), ip_maxbits(a1));
     419             :     }
     420             : 
     421       21282 :     return ip_family(a1) - ip_family(a2);
     422             : }
     423             : 
     424             : Datum
     425         268 : network_cmp(PG_FUNCTION_ARGS)
     426             : {
     427         268 :     inet       *a1 = PG_GETARG_INET_PP(0);
     428         268 :     inet       *a2 = PG_GETARG_INET_PP(1);
     429             : 
     430         268 :     PG_RETURN_INT32(network_cmp_internal(a1, a2));
     431             : }
     432             : 
     433             : /*
     434             :  * SortSupport strategy routine
     435             :  */
     436             : Datum
     437         322 : network_sortsupport(PG_FUNCTION_ARGS)
     438             : {
     439         322 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
     440             : 
     441         322 :     ssup->comparator = network_fast_cmp;
     442         322 :     ssup->ssup_extra = NULL;
     443             : 
     444         322 :     if (ssup->abbreviate)
     445             :     {
     446             :         network_sortsupport_state *uss;
     447             :         MemoryContext oldcontext;
     448             : 
     449         160 :         oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
     450             : 
     451         160 :         uss = palloc(sizeof(network_sortsupport_state));
     452         160 :         uss->input_count = 0;
     453         160 :         uss->estimating = true;
     454         160 :         initHyperLogLog(&uss->abbr_card, 10);
     455             : 
     456         160 :         ssup->ssup_extra = uss;
     457             : 
     458         160 :         ssup->comparator = ssup_datum_unsigned_cmp;
     459         160 :         ssup->abbrev_converter = network_abbrev_convert;
     460         160 :         ssup->abbrev_abort = network_abbrev_abort;
     461         160 :         ssup->abbrev_full_comparator = network_fast_cmp;
     462             : 
     463         160 :         MemoryContextSwitchTo(oldcontext);
     464             :     }
     465             : 
     466         322 :     PG_RETURN_VOID();
     467             : }
     468             : 
     469             : /*
     470             :  * SortSupport comparison func
     471             :  */
     472             : static int
     473       27048 : network_fast_cmp(Datum x, Datum y, SortSupport ssup)
     474             : {
     475       27048 :     inet       *arg1 = DatumGetInetPP(x);
     476       27048 :     inet       *arg2 = DatumGetInetPP(y);
     477             : 
     478       27048 :     return network_cmp_internal(arg1, arg2);
     479             : }
     480             : 
     481             : /*
     482             :  * Callback for estimating effectiveness of abbreviated key optimization.
     483             :  *
     484             :  * We pay no attention to the cardinality of the non-abbreviated data, because
     485             :  * there is no equality fast-path within authoritative inet comparator.
     486             :  */
     487             : static bool
     488          42 : network_abbrev_abort(int memtupcount, SortSupport ssup)
     489             : {
     490          42 :     network_sortsupport_state *uss = ssup->ssup_extra;
     491             :     double      abbr_card;
     492             : 
     493          42 :     if (memtupcount < 10000 || uss->input_count < 10000 || !uss->estimating)
     494          42 :         return false;
     495             : 
     496           0 :     abbr_card = estimateHyperLogLog(&uss->abbr_card);
     497             : 
     498             :     /*
     499             :      * If we have >100k distinct values, then even if we were sorting many
     500             :      * billion rows we'd likely still break even, and the penalty of undoing
     501             :      * that many rows of abbrevs would probably not be worth it. At this point
     502             :      * we stop counting because we know that we're now fully committed.
     503             :      */
     504           0 :     if (abbr_card > 100000.0)
     505             :     {
     506           0 :         if (trace_sort)
     507           0 :             elog(LOG,
     508             :                  "network_abbrev: estimation ends at cardinality %f"
     509             :                  " after " INT64_FORMAT " values (%d rows)",
     510             :                  abbr_card, uss->input_count, memtupcount);
     511           0 :         uss->estimating = false;
     512           0 :         return false;
     513             :     }
     514             : 
     515             :     /*
     516             :      * Target minimum cardinality is 1 per ~2k of non-null inputs. 0.5 row
     517             :      * fudge factor allows us to abort earlier on genuinely pathological data
     518             :      * where we've had exactly one abbreviated value in the first 2k
     519             :      * (non-null) rows.
     520             :      */
     521           0 :     if (abbr_card < uss->input_count / 2000.0 + 0.5)
     522             :     {
     523           0 :         if (trace_sort)
     524           0 :             elog(LOG,
     525             :                  "network_abbrev: aborting abbreviation at cardinality %f"
     526             :                  " below threshold %f after " INT64_FORMAT " values (%d rows)",
     527             :                  abbr_card, uss->input_count / 2000.0 + 0.5, uss->input_count,
     528             :                  memtupcount);
     529           0 :         return true;
     530             :     }
     531             : 
     532           0 :     if (trace_sort)
     533           0 :         elog(LOG,
     534             :              "network_abbrev: cardinality %f after " INT64_FORMAT
     535             :              " values (%d rows)", abbr_card, uss->input_count, memtupcount);
     536             : 
     537           0 :     return false;
     538             : }
     539             : 
     540             : /*
     541             :  * SortSupport conversion routine. Converts original inet/cidr representation
     542             :  * to abbreviated key representation that works with simple 3-way unsigned int
     543             :  * comparisons. The network_cmp_internal() rules for sorting inet/cidr datums
     544             :  * are followed by abbreviated comparisons by an encoding scheme that
     545             :  * conditions keys through careful use of padding.
     546             :  *
     547             :  * Some background: inet values have three major components (take for example
     548             :  * the address 1.2.3.4/24):
     549             :  *
     550             :  *     * A network, or netmasked bits (1.2.3.0).
     551             :  *     * A netmask size (/24).
     552             :  *     * A subnet, or bits outside of the netmask (0.0.0.4).
     553             :  *
     554             :  * cidr values are the same except that with only the first two components --
     555             :  * all their subnet bits *must* be zero (1.2.3.0/24).
     556             :  *
     557             :  * IPv4 and IPv6 are identical in this makeup, with the difference being that
     558             :  * IPv4 addresses have a maximum of 32 bits compared to IPv6's 64 bits, so in
     559             :  * IPv6 each part may be larger.
     560             :  *
     561             :  * inet/cidr types compare using these sorting rules. If inequality is detected
     562             :  * at any step, comparison is finished. If any rule is a tie, the algorithm
     563             :  * drops through to the next to break it:
     564             :  *
     565             :  *     1. IPv4 always appears before IPv6.
     566             :  *     2. Network bits are compared.
     567             :  *     3. Netmask size is compared.
     568             :  *     4. All bits are compared (having made it here, we know that both
     569             :  *        netmasked bits and netmask size are equal, so we're in effect only
     570             :  *        comparing subnet bits).
     571             :  *
     572             :  * When generating abbreviated keys for SortSupport, we pack as much as we can
     573             :  * into a datum while ensuring that when comparing those keys as integers,
     574             :  * these rules will be respected. Exact contents depend on IP family and datum
     575             :  * size.
     576             :  *
     577             :  * IPv4
     578             :  * ----
     579             :  *
     580             :  * 4 byte datums:
     581             :  *
     582             :  * Start with 1 bit for the IP family (IPv4 or IPv6; this bit is present in
     583             :  * every case below) followed by all but 1 of the netmasked bits.
     584             :  *
     585             :  * +----------+---------------------+
     586             :  * | 1 bit IP |   31 bits network   |     (1 bit network
     587             :  * |  family  |     (truncated)     |      omitted)
     588             :  * +----------+---------------------+
     589             :  *
     590             :  * 8 byte datums:
     591             :  *
     592             :  * We have space to store all netmasked bits, followed by the netmask size,
     593             :  * followed by 25 bits of the subnet (25 bits is usually more than enough in
     594             :  * practice). cidr datums always have all-zero subnet bits.
     595             :  *
     596             :  * +----------+-----------------------+--------------+--------------------+
     597             :  * | 1 bit IP |    32 bits network    |    6 bits    |   25 bits subnet   |
     598             :  * |  family  |        (full)         | network size |    (truncated)     |
     599             :  * +----------+-----------------------+--------------+--------------------+
     600             :  *
     601             :  * IPv6
     602             :  * ----
     603             :  *
     604             :  * 4 byte datums:
     605             :  *
     606             :  * +----------+---------------------+
     607             :  * | 1 bit IP |   31 bits network   |    (up to 97 bits
     608             :  * |  family  |     (truncated)     |   network omitted)
     609             :  * +----------+---------------------+
     610             :  *
     611             :  * 8 byte datums:
     612             :  *
     613             :  * +----------+---------------------------------+
     614             :  * | 1 bit IP |         63 bits network         |    (up to 65 bits
     615             :  * |  family  |           (truncated)           |   network omitted)
     616             :  * +----------+---------------------------------+
     617             :  */
     618             : static Datum
     619        1548 : network_abbrev_convert(Datum original, SortSupport ssup)
     620             : {
     621        1548 :     network_sortsupport_state *uss = ssup->ssup_extra;
     622        1548 :     inet       *authoritative = DatumGetInetPP(original);
     623             :     Datum       res,
     624             :                 ipaddr_datum,
     625             :                 subnet_bitmask,
     626             :                 network;
     627             :     int         subnet_size;
     628             : 
     629             :     Assert(ip_family(authoritative) == PGSQL_AF_INET ||
     630             :            ip_family(authoritative) == PGSQL_AF_INET6);
     631             : 
     632             :     /*
     633             :      * Get an unsigned integer representation of the IP address by taking its
     634             :      * first 4 or 8 bytes. Always take all 4 bytes of an IPv4 address. Take
     635             :      * the first 8 bytes of an IPv6 address with an 8 byte datum and 4 bytes
     636             :      * otherwise.
     637             :      *
     638             :      * We're consuming an array of unsigned char, so byteswap on little endian
     639             :      * systems (an inet's ipaddr field stores the most significant byte
     640             :      * first).
     641             :      */
     642        1548 :     if (ip_family(authoritative) == PGSQL_AF_INET)
     643             :     {
     644             :         uint32      ipaddr_datum32;
     645             : 
     646        1170 :         memcpy(&ipaddr_datum32, ip_addr(authoritative), sizeof(uint32));
     647             : 
     648             :         /* Must byteswap on little-endian machines */
     649             : #ifndef WORDS_BIGENDIAN
     650        1170 :         ipaddr_datum = pg_bswap32(ipaddr_datum32);
     651             : #else
     652             :         ipaddr_datum = ipaddr_datum32;
     653             : #endif
     654             : 
     655             :         /* Initialize result without setting ipfamily bit */
     656        1170 :         res = (Datum) 0;
     657             :     }
     658             :     else
     659             :     {
     660         378 :         memcpy(&ipaddr_datum, ip_addr(authoritative), sizeof(Datum));
     661             : 
     662             :         /* Must byteswap on little-endian machines */
     663         378 :         ipaddr_datum = DatumBigEndianToNative(ipaddr_datum);
     664             : 
     665             :         /* Initialize result with ipfamily (most significant) bit set */
     666         378 :         res = ((Datum) 1) << (SIZEOF_DATUM * BITS_PER_BYTE - 1);
     667             :     }
     668             : 
     669             :     /*
     670             :      * ipaddr_datum must be "split": high order bits go in "network" component
     671             :      * of abbreviated key (often with zeroed bits at the end due to masking),
     672             :      * while low order bits go in "subnet" component when there is space for
     673             :      * one. This is often accomplished by generating a temp datum subnet
     674             :      * bitmask, which we may reuse later when generating the subnet bits
     675             :      * themselves.  (Note that subnet bits are only used with IPv4 datums on
     676             :      * platforms where datum is 8 bytes.)
     677             :      *
     678             :      * The number of bits in subnet is used to generate a datum subnet
     679             :      * bitmask. For example, with a /24 IPv4 datum there are 8 subnet bits
     680             :      * (since 32 - 24 is 8), so the final subnet bitmask is B'1111 1111'. We
     681             :      * need explicit handling for cases where the ipaddr bits cannot all fit
     682             :      * in a datum, though (otherwise we'd incorrectly mask the network
     683             :      * component with IPv6 values).
     684             :      */
     685        1548 :     subnet_size = ip_maxbits(authoritative) - ip_bits(authoritative);
     686             :     Assert(subnet_size >= 0);
     687             :     /* subnet size must work with prefix ipaddr cases */
     688        1548 :     subnet_size %= SIZEOF_DATUM * BITS_PER_BYTE;
     689        1548 :     if (ip_bits(authoritative) == 0)
     690             :     {
     691             :         /* Fit as many ipaddr bits as possible into subnet */
     692         168 :         subnet_bitmask = ((Datum) 0) - 1;
     693         168 :         network = 0;
     694             :     }
     695        1380 :     else if (ip_bits(authoritative) < SIZEOF_DATUM * BITS_PER_BYTE)
     696             :     {
     697             :         /* Split ipaddr bits between network and subnet */
     698        1170 :         subnet_bitmask = (((Datum) 1) << subnet_size) - 1;
     699        1170 :         network = ipaddr_datum & ~subnet_bitmask;
     700             :     }
     701             :     else
     702             :     {
     703             :         /* Fit as many ipaddr bits as possible into network */
     704         210 :         subnet_bitmask = 0;
     705         210 :         network = ipaddr_datum;
     706             :     }
     707             : 
     708             : #if SIZEOF_DATUM == 8
     709        1548 :     if (ip_family(authoritative) == PGSQL_AF_INET)
     710             :     {
     711             :         /*
     712             :          * IPv4 with 8 byte datums: keep all 32 netmasked bits, netmask size,
     713             :          * and most significant 25 subnet bits
     714             :          */
     715        1170 :         Datum       netmask_size = (Datum) ip_bits(authoritative);
     716             :         Datum       subnet;
     717             : 
     718             :         /*
     719             :          * Shift left 31 bits: 6 bits netmask size + 25 subnet bits.
     720             :          *
     721             :          * We don't make any distinction between network bits that are zero
     722             :          * due to masking and "true"/non-masked zero bits.  An abbreviated
     723             :          * comparison that is resolved by comparing a non-masked and non-zero
     724             :          * bit to a masked/zeroed bit is effectively resolved based on
     725             :          * ip_bits(), even though the comparison won't reach the netmask_size
     726             :          * bits.
     727             :          */
     728        1170 :         network <<= (ABBREV_BITS_INET4_NETMASK_SIZE +
     729             :                      ABBREV_BITS_INET4_SUBNET);
     730             : 
     731             :         /* Shift size to make room for subnet bits at the end */
     732        1170 :         netmask_size <<= ABBREV_BITS_INET4_SUBNET;
     733             : 
     734             :         /* Extract subnet bits without shifting them */
     735        1170 :         subnet = ipaddr_datum & subnet_bitmask;
     736             : 
     737             :         /*
     738             :          * If we have more than 25 subnet bits, we can't fit everything. Shift
     739             :          * subnet down to avoid clobbering bits that are only supposed to be
     740             :          * used for netmask_size.
     741             :          *
     742             :          * Discarding the least significant subnet bits like this is correct
     743             :          * because abbreviated comparisons that are resolved at the subnet
     744             :          * level must have had equal netmask_size/ip_bits() values in order to
     745             :          * get that far.
     746             :          */
     747        1170 :         if (subnet_size > ABBREV_BITS_INET4_SUBNET)
     748         144 :             subnet >>= subnet_size - ABBREV_BITS_INET4_SUBNET;
     749             : 
     750             :         /*
     751             :          * Assemble the final abbreviated key without clobbering the ipfamily
     752             :          * bit that must remain a zero.
     753             :          */
     754        1170 :         res |= network | netmask_size | subnet;
     755             :     }
     756             :     else
     757             : #endif
     758             :     {
     759             :         /*
     760             :          * 4 byte datums, or IPv6 with 8 byte datums: Use as many of the
     761             :          * netmasked bits as will fit in final abbreviated key. Avoid
     762             :          * clobbering the ipfamily bit that was set earlier.
     763             :          */
     764         378 :         res |= network >> 1;
     765             :     }
     766             : 
     767        1548 :     uss->input_count += 1;
     768             : 
     769             :     /* Hash abbreviated key */
     770        1548 :     if (uss->estimating)
     771             :     {
     772             :         uint32      tmp;
     773             : 
     774             : #if SIZEOF_DATUM == 8
     775        1548 :         tmp = (uint32) res ^ (uint32) ((uint64) res >> 32);
     776             : #else                           /* SIZEOF_DATUM != 8 */
     777             :         tmp = (uint32) res;
     778             : #endif
     779             : 
     780        1548 :         addHyperLogLog(&uss->abbr_card, DatumGetUInt32(hash_uint32(tmp)));
     781             :     }
     782             : 
     783        1548 :     return res;
     784             : }
     785             : 
     786             : /*
     787             :  *  Boolean ordering tests.
     788             :  */
     789             : Datum
     790       47020 : network_lt(PG_FUNCTION_ARGS)
     791             : {
     792       47020 :     inet       *a1 = PG_GETARG_INET_PP(0);
     793       47020 :     inet       *a2 = PG_GETARG_INET_PP(1);
     794             : 
     795       47020 :     PG_RETURN_BOOL(network_cmp_internal(a1, a2) < 0);
     796             : }
     797             : 
     798             : Datum
     799       18860 : network_le(PG_FUNCTION_ARGS)
     800             : {
     801       18860 :     inet       *a1 = PG_GETARG_INET_PP(0);
     802       18860 :     inet       *a2 = PG_GETARG_INET_PP(1);
     803             : 
     804       18860 :     PG_RETURN_BOOL(network_cmp_internal(a1, a2) <= 0);
     805             : }
     806             : 
     807             : Datum
     808       24118 : network_eq(PG_FUNCTION_ARGS)
     809             : {
     810       24118 :     inet       *a1 = PG_GETARG_INET_PP(0);
     811       24118 :     inet       *a2 = PG_GETARG_INET_PP(1);
     812             : 
     813       24118 :     PG_RETURN_BOOL(network_cmp_internal(a1, a2) == 0);
     814             : }
     815             : 
     816             : Datum
     817       19100 : network_ge(PG_FUNCTION_ARGS)
     818             : {
     819       19100 :     inet       *a1 = PG_GETARG_INET_PP(0);
     820       19100 :     inet       *a2 = PG_GETARG_INET_PP(1);
     821             : 
     822       19100 :     PG_RETURN_BOOL(network_cmp_internal(a1, a2) >= 0);
     823             : }
     824             : 
     825             : Datum
     826       22300 : network_gt(PG_FUNCTION_ARGS)
     827             : {
     828       22300 :     inet       *a1 = PG_GETARG_INET_PP(0);
     829       22300 :     inet       *a2 = PG_GETARG_INET_PP(1);
     830             : 
     831       22300 :     PG_RETURN_BOOL(network_cmp_internal(a1, a2) > 0);
     832             : }
     833             : 
     834             : Datum
     835         102 : network_ne(PG_FUNCTION_ARGS)
     836             : {
     837         102 :     inet       *a1 = PG_GETARG_INET_PP(0);
     838         102 :     inet       *a2 = PG_GETARG_INET_PP(1);
     839             : 
     840         102 :     PG_RETURN_BOOL(network_cmp_internal(a1, a2) != 0);
     841             : }
     842             : 
     843             : /*
     844             :  * MIN/MAX support functions.
     845             :  */
     846             : Datum
     847         192 : network_smaller(PG_FUNCTION_ARGS)
     848             : {
     849         192 :     inet       *a1 = PG_GETARG_INET_PP(0);
     850         192 :     inet       *a2 = PG_GETARG_INET_PP(1);
     851             : 
     852         192 :     if (network_cmp_internal(a1, a2) < 0)
     853         114 :         PG_RETURN_INET_P(a1);
     854             :     else
     855          78 :         PG_RETURN_INET_P(a2);
     856             : }
     857             : 
     858             : Datum
     859         192 : network_larger(PG_FUNCTION_ARGS)
     860             : {
     861         192 :     inet       *a1 = PG_GETARG_INET_PP(0);
     862         192 :     inet       *a2 = PG_GETARG_INET_PP(1);
     863             : 
     864         192 :     if (network_cmp_internal(a1, a2) > 0)
     865         156 :         PG_RETURN_INET_P(a1);
     866             :     else
     867          36 :         PG_RETURN_INET_P(a2);
     868             : }
     869             : 
     870             : /*
     871             :  * Support function for hash indexes on inet/cidr.
     872             :  */
     873             : Datum
     874        6608 : hashinet(PG_FUNCTION_ARGS)
     875             : {
     876        6608 :     inet       *addr = PG_GETARG_INET_PP(0);
     877        6608 :     int         addrsize = ip_addrsize(addr);
     878             : 
     879             :     /* XXX this assumes there are no pad bytes in the data structure */
     880        6608 :     return hash_any((unsigned char *) VARDATA_ANY(addr), addrsize + 2);
     881             : }
     882             : 
     883             : Datum
     884          60 : hashinetextended(PG_FUNCTION_ARGS)
     885             : {
     886          60 :     inet       *addr = PG_GETARG_INET_PP(0);
     887          60 :     int         addrsize = ip_addrsize(addr);
     888             : 
     889          60 :     return hash_any_extended((unsigned char *) VARDATA_ANY(addr), addrsize + 2,
     890          60 :                              PG_GETARG_INT64(1));
     891             : }
     892             : 
     893             : /*
     894             :  *  Boolean network-inclusion tests.
     895             :  */
     896             : Datum
     897        6132 : network_sub(PG_FUNCTION_ARGS)
     898             : {
     899        6132 :     inet       *a1 = PG_GETARG_INET_PP(0);
     900        6132 :     inet       *a2 = PG_GETARG_INET_PP(1);
     901             : 
     902        6132 :     if (ip_family(a1) == ip_family(a2))
     903             :     {
     904        4932 :         PG_RETURN_BOOL(ip_bits(a1) > ip_bits(a2) &&
     905             :                        bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0);
     906             :     }
     907             : 
     908        1200 :     PG_RETURN_BOOL(false);
     909             : }
     910             : 
     911             : Datum
     912        9906 : network_subeq(PG_FUNCTION_ARGS)
     913             : {
     914        9906 :     inet       *a1 = PG_GETARG_INET_PP(0);
     915        9906 :     inet       *a2 = PG_GETARG_INET_PP(1);
     916             : 
     917        9906 :     if (ip_family(a1) == ip_family(a2))
     918             :     {
     919        6138 :         PG_RETURN_BOOL(ip_bits(a1) >= ip_bits(a2) &&
     920             :                        bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0);
     921             :     }
     922             : 
     923        3768 :     PG_RETURN_BOOL(false);
     924             : }
     925             : 
     926             : Datum
     927        6180 : network_sup(PG_FUNCTION_ARGS)
     928             : {
     929        6180 :     inet       *a1 = PG_GETARG_INET_PP(0);
     930        6180 :     inet       *a2 = PG_GETARG_INET_PP(1);
     931             : 
     932        6180 :     if (ip_family(a1) == ip_family(a2))
     933             :     {
     934        4980 :         PG_RETURN_BOOL(ip_bits(a1) < ip_bits(a2) &&
     935             :                        bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0);
     936             :     }
     937             : 
     938        1200 :     PG_RETURN_BOOL(false);
     939             : }
     940             : 
     941             : Datum
     942       18856 : network_supeq(PG_FUNCTION_ARGS)
     943             : {
     944       18856 :     inet       *a1 = PG_GETARG_INET_PP(0);
     945       18856 :     inet       *a2 = PG_GETARG_INET_PP(1);
     946             : 
     947       18856 :     if (ip_family(a1) == ip_family(a2))
     948             :     {
     949       10492 :         PG_RETURN_BOOL(ip_bits(a1) <= ip_bits(a2) &&
     950             :                        bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0);
     951             :     }
     952             : 
     953        8364 :     PG_RETURN_BOOL(false);
     954             : }
     955             : 
     956             : Datum
     957       21030 : network_overlap(PG_FUNCTION_ARGS)
     958             : {
     959       21030 :     inet       *a1 = PG_GETARG_INET_PP(0);
     960       21030 :     inet       *a2 = PG_GETARG_INET_PP(1);
     961             : 
     962       21030 :     if (ip_family(a1) == ip_family(a2))
     963             :     {
     964       12798 :         PG_RETURN_BOOL(bitncmp(ip_addr(a1), ip_addr(a2),
     965             :                                Min(ip_bits(a1), ip_bits(a2))) == 0);
     966             :     }
     967             : 
     968        8232 :     PG_RETURN_BOOL(false);
     969             : }
     970             : 
     971             : /*
     972             :  * Planner support function for network subset/superset operators
     973             :  */
     974             : Datum
     975        1488 : network_subset_support(PG_FUNCTION_ARGS)
     976             : {
     977        1488 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
     978        1488 :     Node       *ret = NULL;
     979             : 
     980        1488 :     if (IsA(rawreq, SupportRequestIndexCondition))
     981             :     {
     982             :         /* Try to convert operator/function call to index conditions */
     983          48 :         SupportRequestIndexCondition *req = (SupportRequestIndexCondition *) rawreq;
     984             : 
     985          48 :         if (is_opclause(req->node))
     986             :         {
     987          48 :             OpExpr     *clause = (OpExpr *) req->node;
     988             : 
     989             :             Assert(list_length(clause->args) == 2);
     990             :             ret = (Node *)
     991          48 :                 match_network_function((Node *) linitial(clause->args),
     992          48 :                                        (Node *) lsecond(clause->args),
     993             :                                        req->indexarg,
     994             :                                        req->funcid,
     995             :                                        req->opfamily);
     996             :         }
     997           0 :         else if (is_funcclause(req->node))   /* be paranoid */
     998             :         {
     999           0 :             FuncExpr   *clause = (FuncExpr *) req->node;
    1000             : 
    1001             :             Assert(list_length(clause->args) == 2);
    1002             :             ret = (Node *)
    1003           0 :                 match_network_function((Node *) linitial(clause->args),
    1004           0 :                                        (Node *) lsecond(clause->args),
    1005             :                                        req->indexarg,
    1006             :                                        req->funcid,
    1007             :                                        req->opfamily);
    1008             :         }
    1009             :     }
    1010             : 
    1011        1488 :     PG_RETURN_POINTER(ret);
    1012             : }
    1013             : 
    1014             : /*
    1015             :  * match_network_function
    1016             :  *    Try to generate an indexqual for a network subset/superset function.
    1017             :  *
    1018             :  * This layer is just concerned with identifying the function and swapping
    1019             :  * the arguments if necessary.
    1020             :  */
    1021             : static List *
    1022          48 : match_network_function(Node *leftop,
    1023             :                        Node *rightop,
    1024             :                        int indexarg,
    1025             :                        Oid funcid,
    1026             :                        Oid opfamily)
    1027             : {
    1028          48 :     switch (funcid)
    1029             :     {
    1030          12 :         case F_NETWORK_SUB:
    1031             :             /* indexkey must be on the left */
    1032          12 :             if (indexarg != 0)
    1033           0 :                 return NIL;
    1034          12 :             return match_network_subset(leftop, rightop, false, opfamily);
    1035             : 
    1036          12 :         case F_NETWORK_SUBEQ:
    1037             :             /* indexkey must be on the left */
    1038          12 :             if (indexarg != 0)
    1039           0 :                 return NIL;
    1040          12 :             return match_network_subset(leftop, rightop, true, opfamily);
    1041             : 
    1042          12 :         case F_NETWORK_SUP:
    1043             :             /* indexkey must be on the right */
    1044          12 :             if (indexarg != 1)
    1045           0 :                 return NIL;
    1046          12 :             return match_network_subset(rightop, leftop, false, opfamily);
    1047             : 
    1048          12 :         case F_NETWORK_SUPEQ:
    1049             :             /* indexkey must be on the right */
    1050          12 :             if (indexarg != 1)
    1051           0 :                 return NIL;
    1052          12 :             return match_network_subset(rightop, leftop, true, opfamily);
    1053             : 
    1054           0 :         default:
    1055             : 
    1056             :             /*
    1057             :              * We'd only get here if somebody attached this support function
    1058             :              * to an unexpected function.  Maybe we should complain, but for
    1059             :              * now, do nothing.
    1060             :              */
    1061           0 :             return NIL;
    1062             :     }
    1063             : }
    1064             : 
    1065             : /*
    1066             :  * match_network_subset
    1067             :  *    Try to generate an indexqual for a network subset function.
    1068             :  */
    1069             : static List *
    1070          48 : match_network_subset(Node *leftop,
    1071             :                      Node *rightop,
    1072             :                      bool is_eq,
    1073             :                      Oid opfamily)
    1074             : {
    1075             :     List       *result;
    1076             :     Datum       rightopval;
    1077          48 :     Oid         datatype = INETOID;
    1078             :     Oid         opr1oid;
    1079             :     Oid         opr2oid;
    1080             :     Datum       opr1right;
    1081             :     Datum       opr2right;
    1082             :     Expr       *expr;
    1083             : 
    1084             :     /*
    1085             :      * Can't do anything with a non-constant or NULL comparison value.
    1086             :      *
    1087             :      * Note that since we restrict ourselves to cases with a hard constant on
    1088             :      * the RHS, it's a-fortiori a pseudoconstant, and we don't need to worry
    1089             :      * about verifying that.
    1090             :      */
    1091          48 :     if (!IsA(rightop, Const) ||
    1092          48 :         ((Const *) rightop)->constisnull)
    1093           0 :         return NIL;
    1094          48 :     rightopval = ((Const *) rightop)->constvalue;
    1095             : 
    1096             :     /*
    1097             :      * create clause "key >= network_scan_first( rightopval )", or ">" if the
    1098             :      * operator disallows equality.
    1099             :      */
    1100          48 :     opr1oid = get_opfamily_member_for_cmptype(opfamily, datatype, datatype, is_eq ? COMPARE_GE : COMPARE_GT);
    1101          48 :     if (opr1oid == InvalidOid)
    1102           0 :         return NIL;
    1103             : 
    1104          48 :     opr1right = network_scan_first(rightopval);
    1105             : 
    1106          48 :     expr = make_opclause(opr1oid, BOOLOID, false,
    1107             :                          (Expr *) leftop,
    1108          48 :                          (Expr *) makeConst(datatype, -1,
    1109             :                                             InvalidOid, /* not collatable */
    1110             :                                             -1, opr1right,
    1111             :                                             false, false),
    1112             :                          InvalidOid, InvalidOid);
    1113          48 :     result = list_make1(expr);
    1114             : 
    1115             :     /* create clause "key <= network_scan_last( rightopval )" */
    1116             : 
    1117          48 :     opr2oid = get_opfamily_member_for_cmptype(opfamily, datatype, datatype, COMPARE_LE);
    1118          48 :     if (opr2oid == InvalidOid)
    1119           0 :         return NIL;
    1120             : 
    1121          48 :     opr2right = network_scan_last(rightopval);
    1122             : 
    1123          48 :     expr = make_opclause(opr2oid, BOOLOID, false,
    1124             :                          (Expr *) leftop,
    1125          48 :                          (Expr *) makeConst(datatype, -1,
    1126             :                                             InvalidOid, /* not collatable */
    1127             :                                             -1, opr2right,
    1128             :                                             false, false),
    1129             :                          InvalidOid, InvalidOid);
    1130          48 :     result = lappend(result, expr);
    1131             : 
    1132          48 :     return result;
    1133             : }
    1134             : 
    1135             : 
    1136             : /*
    1137             :  * Extract data from a network datatype.
    1138             :  */
    1139             : Datum
    1140         102 : network_host(PG_FUNCTION_ARGS)
    1141             : {
    1142         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1143             :     char       *ptr;
    1144             :     char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];
    1145             : 
    1146             :     /* force display of max bits, regardless of masklen... */
    1147         102 :     if (pg_inet_net_ntop(ip_family(ip), ip_addr(ip), ip_maxbits(ip),
    1148             :                          tmp, sizeof(tmp)) == NULL)
    1149           0 :         ereport(ERROR,
    1150             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1151             :                  errmsg("could not format inet value: %m")));
    1152             : 
    1153             :     /* Suppress /n if present (shouldn't happen now) */
    1154         102 :     if ((ptr = strchr(tmp, '/')) != NULL)
    1155           0 :         *ptr = '\0';
    1156             : 
    1157         102 :     PG_RETURN_TEXT_P(cstring_to_text(tmp));
    1158             : }
    1159             : 
    1160             : /*
    1161             :  * network_show implements the inet and cidr casts to text.  This is not
    1162             :  * quite the same behavior as network_out, hence we can't drop it in favor
    1163             :  * of CoerceViaIO.
    1164             :  */
    1165             : Datum
    1166         530 : network_show(PG_FUNCTION_ARGS)
    1167             : {
    1168         530 :     inet       *ip = PG_GETARG_INET_PP(0);
    1169             :     int         len;
    1170             :     char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];
    1171             : 
    1172         530 :     if (pg_inet_net_ntop(ip_family(ip), ip_addr(ip), ip_maxbits(ip),
    1173             :                          tmp, sizeof(tmp)) == NULL)
    1174           0 :         ereport(ERROR,
    1175             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1176             :                  errmsg("could not format inet value: %m")));
    1177             : 
    1178             :     /* Add /n if not present (which it won't be) */
    1179         530 :     if (strchr(tmp, '/') == NULL)
    1180             :     {
    1181         530 :         len = strlen(tmp);
    1182         530 :         snprintf(tmp + len, sizeof(tmp) - len, "/%u", ip_bits(ip));
    1183             :     }
    1184             : 
    1185         530 :     PG_RETURN_TEXT_P(cstring_to_text(tmp));
    1186             : }
    1187             : 
    1188             : Datum
    1189         102 : inet_abbrev(PG_FUNCTION_ARGS)
    1190             : {
    1191         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1192             :     char       *dst;
    1193             :     char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];
    1194             : 
    1195         102 :     dst = pg_inet_net_ntop(ip_family(ip), ip_addr(ip),
    1196         102 :                            ip_bits(ip), tmp, sizeof(tmp));
    1197             : 
    1198         102 :     if (dst == NULL)
    1199           0 :         ereport(ERROR,
    1200             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1201             :                  errmsg("could not format inet value: %m")));
    1202             : 
    1203         102 :     PG_RETURN_TEXT_P(cstring_to_text(tmp));
    1204             : }
    1205             : 
    1206             : Datum
    1207         102 : cidr_abbrev(PG_FUNCTION_ARGS)
    1208             : {
    1209         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1210             :     char       *dst;
    1211             :     char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];
    1212             : 
    1213         102 :     dst = pg_inet_cidr_ntop(ip_family(ip), ip_addr(ip),
    1214         102 :                             ip_bits(ip), tmp, sizeof(tmp));
    1215             : 
    1216         102 :     if (dst == NULL)
    1217           0 :         ereport(ERROR,
    1218             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1219             :                  errmsg("could not format cidr value: %m")));
    1220             : 
    1221         102 :     PG_RETURN_TEXT_P(cstring_to_text(tmp));
    1222             : }
    1223             : 
    1224             : Datum
    1225         354 : network_masklen(PG_FUNCTION_ARGS)
    1226             : {
    1227         354 :     inet       *ip = PG_GETARG_INET_PP(0);
    1228             : 
    1229         354 :     PG_RETURN_INT32(ip_bits(ip));
    1230             : }
    1231             : 
    1232             : Datum
    1233         102 : network_family(PG_FUNCTION_ARGS)
    1234             : {
    1235         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1236             : 
    1237         102 :     switch (ip_family(ip))
    1238             :     {
    1239          84 :         case PGSQL_AF_INET:
    1240          84 :             PG_RETURN_INT32(4);
    1241             :             break;
    1242          18 :         case PGSQL_AF_INET6:
    1243          18 :             PG_RETURN_INT32(6);
    1244             :             break;
    1245           0 :         default:
    1246           0 :             PG_RETURN_INT32(0);
    1247             :             break;
    1248             :     }
    1249             : }
    1250             : 
    1251             : Datum
    1252         252 : network_broadcast(PG_FUNCTION_ARGS)
    1253             : {
    1254         252 :     inet       *ip = PG_GETARG_INET_PP(0);
    1255             :     inet       *dst;
    1256             :     int         byte;
    1257             :     int         bits;
    1258             :     int         maxbytes;
    1259             :     unsigned char mask;
    1260             :     unsigned char *a,
    1261             :                *b;
    1262             : 
    1263             :     /* make sure any unused bits are zeroed */
    1264         252 :     dst = (inet *) palloc0(sizeof(inet));
    1265             : 
    1266         252 :     maxbytes = ip_addrsize(ip);
    1267         252 :     bits = ip_bits(ip);
    1268         252 :     a = ip_addr(ip);
    1269         252 :     b = ip_addr(dst);
    1270             : 
    1271        1692 :     for (byte = 0; byte < maxbytes; byte++)
    1272             :     {
    1273        1440 :         if (bits >= 8)
    1274             :         {
    1275         990 :             mask = 0x00;
    1276         990 :             bits -= 8;
    1277             :         }
    1278         450 :         else if (bits == 0)
    1279         426 :             mask = 0xff;
    1280             :         else
    1281             :         {
    1282          24 :             mask = 0xff >> bits;
    1283          24 :             bits = 0;
    1284             :         }
    1285             : 
    1286        1440 :         b[byte] = a[byte] | mask;
    1287             :     }
    1288             : 
    1289         252 :     ip_family(dst) = ip_family(ip);
    1290         252 :     ip_bits(dst) = ip_bits(ip);
    1291         252 :     SET_INET_VARSIZE(dst);
    1292             : 
    1293         252 :     PG_RETURN_INET_P(dst);
    1294             : }
    1295             : 
    1296             : Datum
    1297         252 : network_network(PG_FUNCTION_ARGS)
    1298             : {
    1299         252 :     inet       *ip = PG_GETARG_INET_PP(0);
    1300             :     inet       *dst;
    1301             :     int         byte;
    1302             :     int         bits;
    1303             :     unsigned char mask;
    1304             :     unsigned char *a,
    1305             :                *b;
    1306             : 
    1307             :     /* make sure any unused bits are zeroed */
    1308         252 :     dst = (inet *) palloc0(sizeof(inet));
    1309             : 
    1310         252 :     bits = ip_bits(ip);
    1311         252 :     a = ip_addr(ip);
    1312         252 :     b = ip_addr(dst);
    1313             : 
    1314         252 :     byte = 0;
    1315             : 
    1316        1266 :     while (bits)
    1317             :     {
    1318        1014 :         if (bits >= 8)
    1319             :         {
    1320         990 :             mask = 0xff;
    1321         990 :             bits -= 8;
    1322             :         }
    1323             :         else
    1324             :         {
    1325          24 :             mask = 0xff << (8 - bits);
    1326          24 :             bits = 0;
    1327             :         }
    1328             : 
    1329        1014 :         b[byte] = a[byte] & mask;
    1330        1014 :         byte++;
    1331             :     }
    1332             : 
    1333         252 :     ip_family(dst) = ip_family(ip);
    1334         252 :     ip_bits(dst) = ip_bits(ip);
    1335         252 :     SET_INET_VARSIZE(dst);
    1336             : 
    1337         252 :     PG_RETURN_INET_P(dst);
    1338             : }
    1339             : 
    1340             : Datum
    1341         102 : network_netmask(PG_FUNCTION_ARGS)
    1342             : {
    1343         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1344             :     inet       *dst;
    1345             :     int         byte;
    1346             :     int         bits;
    1347             :     unsigned char mask;
    1348             :     unsigned char *b;
    1349             : 
    1350             :     /* make sure any unused bits are zeroed */
    1351         102 :     dst = (inet *) palloc0(sizeof(inet));
    1352             : 
    1353         102 :     bits = ip_bits(ip);
    1354         102 :     b = ip_addr(dst);
    1355             : 
    1356         102 :     byte = 0;
    1357             : 
    1358         474 :     while (bits)
    1359             :     {
    1360         372 :         if (bits >= 8)
    1361             :         {
    1362         360 :             mask = 0xff;
    1363         360 :             bits -= 8;
    1364             :         }
    1365             :         else
    1366             :         {
    1367          12 :             mask = 0xff << (8 - bits);
    1368          12 :             bits = 0;
    1369             :         }
    1370             : 
    1371         372 :         b[byte] = mask;
    1372         372 :         byte++;
    1373             :     }
    1374             : 
    1375         102 :     ip_family(dst) = ip_family(ip);
    1376         102 :     ip_bits(dst) = ip_maxbits(ip);
    1377         102 :     SET_INET_VARSIZE(dst);
    1378             : 
    1379         102 :     PG_RETURN_INET_P(dst);
    1380             : }
    1381             : 
    1382             : Datum
    1383         102 : network_hostmask(PG_FUNCTION_ARGS)
    1384             : {
    1385         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1386             :     inet       *dst;
    1387             :     int         byte;
    1388             :     int         bits;
    1389             :     int         maxbytes;
    1390             :     unsigned char mask;
    1391             :     unsigned char *b;
    1392             : 
    1393             :     /* make sure any unused bits are zeroed */
    1394         102 :     dst = (inet *) palloc0(sizeof(inet));
    1395             : 
    1396         102 :     maxbytes = ip_addrsize(ip);
    1397         102 :     bits = ip_maxbits(ip) - ip_bits(ip);
    1398         102 :     b = ip_addr(dst);
    1399             : 
    1400         102 :     byte = maxbytes - 1;
    1401             : 
    1402         366 :     while (bits)
    1403             :     {
    1404         264 :         if (bits >= 8)
    1405             :         {
    1406         252 :             mask = 0xff;
    1407         252 :             bits -= 8;
    1408             :         }
    1409             :         else
    1410             :         {
    1411          12 :             mask = 0xff >> (8 - bits);
    1412          12 :             bits = 0;
    1413             :         }
    1414             : 
    1415         264 :         b[byte] = mask;
    1416         264 :         byte--;
    1417             :     }
    1418             : 
    1419         102 :     ip_family(dst) = ip_family(ip);
    1420         102 :     ip_bits(dst) = ip_maxbits(ip);
    1421         102 :     SET_INET_VARSIZE(dst);
    1422             : 
    1423         102 :     PG_RETURN_INET_P(dst);
    1424             : }
    1425             : 
    1426             : /*
    1427             :  * Returns true if the addresses are from the same family, or false.  Used to
    1428             :  * check that we can create a network which contains both of the networks.
    1429             :  */
    1430             : Datum
    1431         480 : inet_same_family(PG_FUNCTION_ARGS)
    1432             : {
    1433         480 :     inet       *a1 = PG_GETARG_INET_PP(0);
    1434         480 :     inet       *a2 = PG_GETARG_INET_PP(1);
    1435             : 
    1436         480 :     PG_RETURN_BOOL(ip_family(a1) == ip_family(a2));
    1437             : }
    1438             : 
    1439             : /*
    1440             :  * Returns the smallest CIDR which contains both of the inputs.
    1441             :  */
    1442             : Datum
    1443         450 : inet_merge(PG_FUNCTION_ARGS)
    1444             : {
    1445         450 :     inet       *a1 = PG_GETARG_INET_PP(0),
    1446         450 :                *a2 = PG_GETARG_INET_PP(1);
    1447             :     int         commonbits;
    1448             : 
    1449         450 :     if (ip_family(a1) != ip_family(a2))
    1450           6 :         ereport(ERROR,
    1451             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1452             :                  errmsg("cannot merge addresses from different families")));
    1453             : 
    1454         444 :     commonbits = bitncommon(ip_addr(a1), ip_addr(a2),
    1455         444 :                             Min(ip_bits(a1), ip_bits(a2)));
    1456             : 
    1457         444 :     PG_RETURN_INET_P(cidr_set_masklen_internal(a1, commonbits));
    1458             : }
    1459             : 
    1460             : /*
    1461             :  * Convert a value of a network datatype to an approximate scalar value.
    1462             :  * This is used for estimating selectivities of inequality operators
    1463             :  * involving network types.
    1464             :  *
    1465             :  * On failure (e.g., unsupported typid), set *failure to true;
    1466             :  * otherwise, that variable is not changed.
    1467             :  */
    1468             : double
    1469       10880 : convert_network_to_scalar(Datum value, Oid typid, bool *failure)
    1470             : {
    1471       10880 :     switch (typid)
    1472             :     {
    1473       10880 :         case INETOID:
    1474             :         case CIDROID:
    1475             :             {
    1476       10880 :                 inet       *ip = DatumGetInetPP(value);
    1477             :                 int         len;
    1478             :                 double      res;
    1479             :                 int         i;
    1480             : 
    1481             :                 /*
    1482             :                  * Note that we don't use the full address for IPv6.
    1483             :                  */
    1484       10880 :                 if (ip_family(ip) == PGSQL_AF_INET)
    1485       10880 :                     len = 4;
    1486             :                 else
    1487           0 :                     len = 5;
    1488             : 
    1489       10880 :                 res = ip_family(ip);
    1490       54400 :                 for (i = 0; i < len; i++)
    1491             :                 {
    1492       43520 :                     res *= 256;
    1493       43520 :                     res += ip_addr(ip)[i];
    1494             :                 }
    1495       10880 :                 return res;
    1496             :             }
    1497           0 :         case MACADDROID:
    1498             :             {
    1499           0 :                 macaddr    *mac = DatumGetMacaddrP(value);
    1500             :                 double      res;
    1501             : 
    1502           0 :                 res = (mac->a << 16) | (mac->b << 8) | (mac->c);
    1503           0 :                 res *= 256 * 256 * 256;
    1504           0 :                 res += (mac->d << 16) | (mac->e << 8) | (mac->f);
    1505           0 :                 return res;
    1506             :             }
    1507           0 :         case MACADDR8OID:
    1508             :             {
    1509           0 :                 macaddr8   *mac = DatumGetMacaddr8P(value);
    1510             :                 double      res;
    1511             : 
    1512           0 :                 res = (mac->a << 24) | (mac->b << 16) | (mac->c << 8) | (mac->d);
    1513           0 :                 res *= ((double) 256) * 256 * 256 * 256;
    1514           0 :                 res += (mac->e << 24) | (mac->f << 16) | (mac->g << 8) | (mac->h);
    1515           0 :                 return res;
    1516             :             }
    1517             :     }
    1518             : 
    1519           0 :     *failure = true;
    1520           0 :     return 0;
    1521             : }
    1522             : 
    1523             : /*
    1524             :  * int
    1525             :  * bitncmp(l, r, n)
    1526             :  *      compare bit masks l and r, for n bits.
    1527             :  * return:
    1528             :  *      <0, >0, or 0 in the libc tradition.
    1529             :  * note:
    1530             :  *      network byte order assumed.  this means 192.5.5.240/28 has
    1531             :  *      0x11110000 in its fourth octet.
    1532             :  * author:
    1533             :  *      Paul Vixie (ISC), June 1996
    1534             :  */
    1535             : int
    1536      193594 : bitncmp(const unsigned char *l, const unsigned char *r, int n)
    1537             : {
    1538             :     unsigned int lb,
    1539             :                 rb;
    1540             :     int         x,
    1541             :                 b;
    1542             : 
    1543      193594 :     b = n / 8;
    1544      193594 :     x = memcmp(l, r, b);
    1545      193594 :     if (x || (n % 8) == 0)
    1546      193326 :         return x;
    1547             : 
    1548         268 :     lb = l[b];
    1549         268 :     rb = r[b];
    1550         528 :     for (b = n % 8; b > 0; b--)
    1551             :     {
    1552         376 :         if (IS_HIGHBIT_SET(lb) != IS_HIGHBIT_SET(rb))
    1553             :         {
    1554         116 :             if (IS_HIGHBIT_SET(lb))
    1555          60 :                 return 1;
    1556          56 :             return -1;
    1557             :         }
    1558         260 :         lb <<= 1;
    1559         260 :         rb <<= 1;
    1560             :     }
    1561         152 :     return 0;
    1562             : }
    1563             : 
    1564             : /*
    1565             :  * bitncommon: compare bit masks l and r, for up to n bits.
    1566             :  *
    1567             :  * Returns the number of leading bits that match (0 to n).
    1568             :  */
    1569             : int
    1570        3536 : bitncommon(const unsigned char *l, const unsigned char *r, int n)
    1571             : {
    1572             :     int         byte,
    1573             :                 nbits;
    1574             : 
    1575             :     /* number of bits to examine in last byte */
    1576        3536 :     nbits = n % 8;
    1577             : 
    1578             :     /* check whole bytes */
    1579        5362 :     for (byte = 0; byte < n / 8; byte++)
    1580             :     {
    1581        2090 :         if (l[byte] != r[byte])
    1582             :         {
    1583             :             /* at least one bit in the last byte is not common */
    1584         264 :             nbits = 7;
    1585         264 :             break;
    1586             :         }
    1587             :     }
    1588             : 
    1589             :     /* check bits in last partial byte */
    1590        3536 :     if (nbits != 0)
    1591             :     {
    1592             :         /* calculate diff of first non-matching bytes */
    1593        2780 :         unsigned int diff = l[byte] ^ r[byte];
    1594             : 
    1595             :         /* compare the bits from the most to the least */
    1596        3980 :         while ((diff >> (8 - nbits)) != 0)
    1597        1200 :             nbits--;
    1598             :     }
    1599             : 
    1600        3536 :     return (8 * byte) + nbits;
    1601             : }
    1602             : 
    1603             : 
    1604             : /*
    1605             :  * Verify a CIDR address is OK (doesn't have bits set past the masklen)
    1606             :  */
    1607             : static bool
    1608        2408 : addressOK(unsigned char *a, int bits, int family)
    1609             : {
    1610             :     int         byte;
    1611             :     int         nbits;
    1612             :     int         maxbits;
    1613             :     int         maxbytes;
    1614             :     unsigned char mask;
    1615             : 
    1616        2408 :     if (family == PGSQL_AF_INET)
    1617             :     {
    1618        1934 :         maxbits = 32;
    1619        1934 :         maxbytes = 4;
    1620             :     }
    1621             :     else
    1622             :     {
    1623         474 :         maxbits = 128;
    1624         474 :         maxbytes = 16;
    1625             :     }
    1626             :     Assert(bits <= maxbits);
    1627             : 
    1628        2408 :     if (bits == maxbits)
    1629         808 :         return true;
    1630             : 
    1631        1600 :     byte = bits / 8;
    1632             : 
    1633        1600 :     nbits = bits % 8;
    1634        1600 :     mask = 0xff;
    1635        1600 :     if (bits != 0)
    1636        1552 :         mask >>= nbits;
    1637             : 
    1638        4794 :     while (byte < maxbytes)
    1639             :     {
    1640        3224 :         if ((a[byte] & mask) != 0)
    1641          30 :             return false;
    1642        3194 :         mask = 0xff;
    1643        3194 :         byte++;
    1644             :     }
    1645             : 
    1646        1570 :     return true;
    1647             : }
    1648             : 
    1649             : 
    1650             : /*
    1651             :  * These functions are used by planner to generate indexscan limits
    1652             :  * for clauses a << b and a <<= b
    1653             :  */
    1654             : 
    1655             : /* return the minimal value for an IP on a given network */
    1656             : Datum
    1657          48 : network_scan_first(Datum in)
    1658             : {
    1659          48 :     return DirectFunctionCall1(network_network, in);
    1660             : }
    1661             : 
    1662             : /*
    1663             :  * return "last" IP on a given network. It's the broadcast address,
    1664             :  * however, masklen has to be set to its max bits, since
    1665             :  * 192.168.0.255/24 is considered less than 192.168.0.255/32
    1666             :  *
    1667             :  * inet_set_masklen() hacked to max out the masklength to 128 for IPv6
    1668             :  * and 32 for IPv4 when given '-1' as argument.
    1669             :  */
    1670             : Datum
    1671          48 : network_scan_last(Datum in)
    1672             : {
    1673          48 :     return DirectFunctionCall2(inet_set_masklen,
    1674             :                                DirectFunctionCall1(network_broadcast, in),
    1675             :                                Int32GetDatum(-1));
    1676             : }
    1677             : 
    1678             : 
    1679             : /*
    1680             :  * IP address that the client is connecting from (NULL if Unix socket)
    1681             :  */
    1682             : Datum
    1683           0 : inet_client_addr(PG_FUNCTION_ARGS)
    1684             : {
    1685           0 :     Port       *port = MyProcPort;
    1686             :     char        remote_host[NI_MAXHOST];
    1687             :     int         ret;
    1688             : 
    1689           0 :     if (port == NULL)
    1690           0 :         PG_RETURN_NULL();
    1691             : 
    1692           0 :     switch (port->raddr.addr.ss_family)
    1693             :     {
    1694           0 :         case AF_INET:
    1695             :         case AF_INET6:
    1696           0 :             break;
    1697           0 :         default:
    1698           0 :             PG_RETURN_NULL();
    1699             :     }
    1700             : 
    1701           0 :     remote_host[0] = '\0';
    1702             : 
    1703           0 :     ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
    1704             :                              remote_host, sizeof(remote_host),
    1705             :                              NULL, 0,
    1706             :                              NI_NUMERICHOST | NI_NUMERICSERV);
    1707           0 :     if (ret != 0)
    1708           0 :         PG_RETURN_NULL();
    1709             : 
    1710           0 :     clean_ipv6_addr(port->raddr.addr.ss_family, remote_host);
    1711             : 
    1712           0 :     PG_RETURN_INET_P(network_in(remote_host, false, NULL));
    1713             : }
    1714             : 
    1715             : 
    1716             : /*
    1717             :  * port that the client is connecting from (NULL if Unix socket)
    1718             :  */
    1719             : Datum
    1720           0 : inet_client_port(PG_FUNCTION_ARGS)
    1721             : {
    1722           0 :     Port       *port = MyProcPort;
    1723             :     char        remote_port[NI_MAXSERV];
    1724             :     int         ret;
    1725             : 
    1726           0 :     if (port == NULL)
    1727           0 :         PG_RETURN_NULL();
    1728             : 
    1729           0 :     switch (port->raddr.addr.ss_family)
    1730             :     {
    1731           0 :         case AF_INET:
    1732             :         case AF_INET6:
    1733           0 :             break;
    1734           0 :         default:
    1735           0 :             PG_RETURN_NULL();
    1736             :     }
    1737             : 
    1738           0 :     remote_port[0] = '\0';
    1739             : 
    1740           0 :     ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
    1741             :                              NULL, 0,
    1742             :                              remote_port, sizeof(remote_port),
    1743             :                              NI_NUMERICHOST | NI_NUMERICSERV);
    1744           0 :     if (ret != 0)
    1745           0 :         PG_RETURN_NULL();
    1746             : 
    1747           0 :     PG_RETURN_DATUM(DirectFunctionCall1(int4in, CStringGetDatum(remote_port)));
    1748             : }
    1749             : 
    1750             : 
    1751             : /*
    1752             :  * IP address that the server accepted the connection on (NULL if Unix socket)
    1753             :  */
    1754             : Datum
    1755           0 : inet_server_addr(PG_FUNCTION_ARGS)
    1756             : {
    1757           0 :     Port       *port = MyProcPort;
    1758             :     char        local_host[NI_MAXHOST];
    1759             :     int         ret;
    1760             : 
    1761           0 :     if (port == NULL)
    1762           0 :         PG_RETURN_NULL();
    1763             : 
    1764           0 :     switch (port->laddr.addr.ss_family)
    1765             :     {
    1766           0 :         case AF_INET:
    1767             :         case AF_INET6:
    1768           0 :             break;
    1769           0 :         default:
    1770           0 :             PG_RETURN_NULL();
    1771             :     }
    1772             : 
    1773           0 :     local_host[0] = '\0';
    1774             : 
    1775           0 :     ret = pg_getnameinfo_all(&port->laddr.addr, port->laddr.salen,
    1776             :                              local_host, sizeof(local_host),
    1777             :                              NULL, 0,
    1778             :                              NI_NUMERICHOST | NI_NUMERICSERV);
    1779           0 :     if (ret != 0)
    1780           0 :         PG_RETURN_NULL();
    1781             : 
    1782           0 :     clean_ipv6_addr(port->laddr.addr.ss_family, local_host);
    1783             : 
    1784           0 :     PG_RETURN_INET_P(network_in(local_host, false, NULL));
    1785             : }
    1786             : 
    1787             : 
    1788             : /*
    1789             :  * port that the server accepted the connection on (NULL if Unix socket)
    1790             :  */
    1791             : Datum
    1792           0 : inet_server_port(PG_FUNCTION_ARGS)
    1793             : {
    1794           0 :     Port       *port = MyProcPort;
    1795             :     char        local_port[NI_MAXSERV];
    1796             :     int         ret;
    1797             : 
    1798           0 :     if (port == NULL)
    1799           0 :         PG_RETURN_NULL();
    1800             : 
    1801           0 :     switch (port->laddr.addr.ss_family)
    1802             :     {
    1803           0 :         case AF_INET:
    1804             :         case AF_INET6:
    1805           0 :             break;
    1806           0 :         default:
    1807           0 :             PG_RETURN_NULL();
    1808             :     }
    1809             : 
    1810           0 :     local_port[0] = '\0';
    1811             : 
    1812           0 :     ret = pg_getnameinfo_all(&port->laddr.addr, port->laddr.salen,
    1813             :                              NULL, 0,
    1814             :                              local_port, sizeof(local_port),
    1815             :                              NI_NUMERICHOST | NI_NUMERICSERV);
    1816           0 :     if (ret != 0)
    1817           0 :         PG_RETURN_NULL();
    1818             : 
    1819           0 :     PG_RETURN_DATUM(DirectFunctionCall1(int4in, CStringGetDatum(local_port)));
    1820             : }
    1821             : 
    1822             : 
    1823             : Datum
    1824         102 : inetnot(PG_FUNCTION_ARGS)
    1825             : {
    1826         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1827             :     inet       *dst;
    1828             : 
    1829         102 :     dst = (inet *) palloc0(sizeof(inet));
    1830             : 
    1831             :     {
    1832         102 :         int         nb = ip_addrsize(ip);
    1833         102 :         unsigned char *pip = ip_addr(ip);
    1834         102 :         unsigned char *pdst = ip_addr(dst);
    1835             : 
    1836         726 :         while (--nb >= 0)
    1837         624 :             pdst[nb] = ~pip[nb];
    1838             :     }
    1839         102 :     ip_bits(dst) = ip_bits(ip);
    1840             : 
    1841         102 :     ip_family(dst) = ip_family(ip);
    1842         102 :     SET_INET_VARSIZE(dst);
    1843             : 
    1844         102 :     PG_RETURN_INET_P(dst);
    1845             : }
    1846             : 
    1847             : 
    1848             : Datum
    1849         102 : inetand(PG_FUNCTION_ARGS)
    1850             : {
    1851         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1852         102 :     inet       *ip2 = PG_GETARG_INET_PP(1);
    1853             :     inet       *dst;
    1854             : 
    1855         102 :     dst = (inet *) palloc0(sizeof(inet));
    1856             : 
    1857         102 :     if (ip_family(ip) != ip_family(ip2))
    1858           0 :         ereport(ERROR,
    1859             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1860             :                  errmsg("cannot AND inet values of different sizes")));
    1861             :     else
    1862             :     {
    1863         102 :         int         nb = ip_addrsize(ip);
    1864         102 :         unsigned char *pip = ip_addr(ip);
    1865         102 :         unsigned char *pip2 = ip_addr(ip2);
    1866         102 :         unsigned char *pdst = ip_addr(dst);
    1867             : 
    1868         726 :         while (--nb >= 0)
    1869         624 :             pdst[nb] = pip[nb] & pip2[nb];
    1870             :     }
    1871         102 :     ip_bits(dst) = Max(ip_bits(ip), ip_bits(ip2));
    1872             : 
    1873         102 :     ip_family(dst) = ip_family(ip);
    1874         102 :     SET_INET_VARSIZE(dst);
    1875             : 
    1876         102 :     PG_RETURN_INET_P(dst);
    1877             : }
    1878             : 
    1879             : 
    1880             : Datum
    1881         102 : inetor(PG_FUNCTION_ARGS)
    1882             : {
    1883         102 :     inet       *ip = PG_GETARG_INET_PP(0);
    1884         102 :     inet       *ip2 = PG_GETARG_INET_PP(1);
    1885             :     inet       *dst;
    1886             : 
    1887         102 :     dst = (inet *) palloc0(sizeof(inet));
    1888             : 
    1889         102 :     if (ip_family(ip) != ip_family(ip2))
    1890           0 :         ereport(ERROR,
    1891             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1892             :                  errmsg("cannot OR inet values of different sizes")));
    1893             :     else
    1894             :     {
    1895         102 :         int         nb = ip_addrsize(ip);
    1896         102 :         unsigned char *pip = ip_addr(ip);
    1897         102 :         unsigned char *pip2 = ip_addr(ip2);
    1898         102 :         unsigned char *pdst = ip_addr(dst);
    1899             : 
    1900         726 :         while (--nb >= 0)
    1901         624 :             pdst[nb] = pip[nb] | pip2[nb];
    1902             :     }
    1903         102 :     ip_bits(dst) = Max(ip_bits(ip), ip_bits(ip2));
    1904             : 
    1905         102 :     ip_family(dst) = ip_family(ip);
    1906         102 :     SET_INET_VARSIZE(dst);
    1907             : 
    1908         102 :     PG_RETURN_INET_P(dst);
    1909             : }
    1910             : 
    1911             : 
    1912             : static inet *
    1913        5142 : internal_inetpl(inet *ip, int64 addend)
    1914             : {
    1915             :     inet       *dst;
    1916             : 
    1917        5142 :     dst = (inet *) palloc0(sizeof(inet));
    1918             : 
    1919             :     {
    1920        5142 :         int         nb = ip_addrsize(ip);
    1921        5142 :         unsigned char *pip = ip_addr(ip);
    1922        5142 :         unsigned char *pdst = ip_addr(dst);
    1923        5142 :         int         carry = 0;
    1924             : 
    1925       37374 :         while (--nb >= 0)
    1926             :         {
    1927       32232 :             carry = pip[nb] + (int) (addend & 0xFF) + carry;
    1928       32232 :             pdst[nb] = (unsigned char) (carry & 0xFF);
    1929       32232 :             carry >>= 8;
    1930             : 
    1931             :             /*
    1932             :              * We have to be careful about right-shifting addend because
    1933             :              * right-shift isn't portable for negative values, while simply
    1934             :              * dividing by 256 doesn't work (the standard rounding is in the
    1935             :              * wrong direction, besides which there may be machines out there
    1936             :              * that round the wrong way).  So, explicitly clear the low-order
    1937             :              * byte to remove any doubt about the correct result of the
    1938             :              * division, and then divide rather than shift.
    1939             :              */
    1940       32232 :             addend &= ~((int64) 0xFF);
    1941       32232 :             addend /= 0x100;
    1942             :         }
    1943             : 
    1944             :         /*
    1945             :          * At this point we should have addend and carry both zero if original
    1946             :          * addend was >= 0, or addend -1 and carry 1 if original addend was <
    1947             :          * 0.  Anything else means overflow.
    1948             :          */
    1949        5142 :         if (!((addend == 0 && carry == 0) ||
    1950         126 :               (addend == -1 && carry == 1)))
    1951          12 :             ereport(ERROR,
    1952             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1953             :                      errmsg("result is out of range")));
    1954             :     }
    1955             : 
    1956        5130 :     ip_bits(dst) = ip_bits(ip);
    1957        5130 :     ip_family(dst) = ip_family(ip);
    1958        5130 :     SET_INET_VARSIZE(dst);
    1959             : 
    1960        5130 :     return dst;
    1961             : }
    1962             : 
    1963             : 
    1964             : Datum
    1965        5010 : inetpl(PG_FUNCTION_ARGS)
    1966             : {
    1967        5010 :     inet       *ip = PG_GETARG_INET_PP(0);
    1968        5010 :     int64       addend = PG_GETARG_INT64(1);
    1969             : 
    1970        5010 :     PG_RETURN_INET_P(internal_inetpl(ip, addend));
    1971             : }
    1972             : 
    1973             : 
    1974             : Datum
    1975         132 : inetmi_int8(PG_FUNCTION_ARGS)
    1976             : {
    1977         132 :     inet       *ip = PG_GETARG_INET_PP(0);
    1978         132 :     int64       addend = PG_GETARG_INT64(1);
    1979             : 
    1980         132 :     PG_RETURN_INET_P(internal_inetpl(ip, -addend));
    1981             : }
    1982             : 
    1983             : 
    1984             : Datum
    1985         144 : inetmi(PG_FUNCTION_ARGS)
    1986             : {
    1987         144 :     inet       *ip = PG_GETARG_INET_PP(0);
    1988         144 :     inet       *ip2 = PG_GETARG_INET_PP(1);
    1989         144 :     int64       res = 0;
    1990             : 
    1991         144 :     if (ip_family(ip) != ip_family(ip2))
    1992           0 :         ereport(ERROR,
    1993             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1994             :                  errmsg("cannot subtract inet values of different sizes")));
    1995             :     else
    1996             :     {
    1997             :         /*
    1998             :          * We form the difference using the traditional complement, increment,
    1999             :          * and add rule, with the increment part being handled by starting the
    2000             :          * carry off at 1.  If you don't think integer arithmetic is done in
    2001             :          * two's complement, too bad.
    2002             :          */
    2003         144 :         int         nb = ip_addrsize(ip);
    2004         144 :         int         byte = 0;
    2005         144 :         unsigned char *pip = ip_addr(ip);
    2006         144 :         unsigned char *pip2 = ip_addr(ip2);
    2007         144 :         int         carry = 1;
    2008             : 
    2009        1272 :         while (--nb >= 0)
    2010             :         {
    2011             :             int         lobyte;
    2012             : 
    2013        1140 :             carry = pip[nb] + (~pip2[nb] & 0xFF) + carry;
    2014        1140 :             lobyte = carry & 0xFF;
    2015        1140 :             if (byte < sizeof(int64))
    2016             :             {
    2017         768 :                 res |= ((int64) lobyte) << (byte * 8);
    2018             :             }
    2019             :             else
    2020             :             {
    2021             :                 /*
    2022             :                  * Input wider than int64: check for overflow.  All bytes to
    2023             :                  * the left of what will fit should be 0 or 0xFF, depending on
    2024             :                  * sign of the now-complete result.
    2025             :                  */
    2026         372 :                 if ((res < 0) ? (lobyte != 0xFF) : (lobyte != 0))
    2027          12 :                     ereport(ERROR,
    2028             :                             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    2029             :                              errmsg("result is out of range")));
    2030             :             }
    2031        1128 :             carry >>= 8;
    2032        1128 :             byte++;
    2033             :         }
    2034             : 
    2035             :         /*
    2036             :          * If input is narrower than int64, overflow is not possible, but we
    2037             :          * have to do proper sign extension.
    2038             :          */
    2039         132 :         if (carry == 0 && byte < sizeof(int64))
    2040          12 :             res |= ((uint64) (int64) -1) << (byte * 8);
    2041             :     }
    2042             : 
    2043         132 :     PG_RETURN_INT64(res);
    2044             : }
    2045             : 
    2046             : 
    2047             : /*
    2048             :  * clean_ipv6_addr --- remove any '%zone' part from an IPv6 address string
    2049             :  *
    2050             :  * XXX This should go away someday!
    2051             :  *
    2052             :  * This is a kluge needed because we don't yet support zones in stored inet
    2053             :  * values.  Since the result of getnameinfo() might include a zone spec,
    2054             :  * call this to remove it anywhere we want to feed getnameinfo's output to
    2055             :  * network_in.  Beats failing entirely.
    2056             :  *
    2057             :  * An alternative approach would be to let network_in ignore %-parts for
    2058             :  * itself, but that would mean we'd silently drop zone specs in user input,
    2059             :  * which seems not such a good idea.
    2060             :  */
    2061             : void
    2062         138 : clean_ipv6_addr(int addr_family, char *addr)
    2063             : {
    2064         138 :     if (addr_family == AF_INET6)
    2065             :     {
    2066          24 :         char       *pct = strchr(addr, '%');
    2067             : 
    2068          24 :         if (pct)
    2069           0 :             *pct = '\0';
    2070             :     }
    2071         138 : }

Generated by: LCOV version 1.14