ipBucket static method

String ipBucket(
  1. String ip
)

The count key of ip with CoreFlags.rateLimitIpv6Prefix:

  • an IPv6 address gives its /64 prefix, eg. 2001:db8:1:2::/64. One home or one server gets a whole /64, so a client can not get a new count by changing the last 64 bits.
  • an IPv4-mapped IPv6 address (::ffff:1.2.3.4) gives the IPv4 address (1.2.3.4).
  • an IPv4 address, or a value that is not an ip, stays as it is.
RateLimit(key: (DoxRequest req) => RateLimit.ipBucket(req.ip()));

Implementation

static String ipBucket(String ip) {
  if (!ip.contains(':')) return ip;
  int zone = ip.indexOf('%');
  List<int> bytes;
  try {
    bytes = Uri.parseIPv6Address(zone < 0 ? ip : ip.substring(0, zone));
  } on FormatException {
    return ip;
  }
  bool mapped = bytes[10] == 0xff && bytes[11] == 0xff;
  for (int i = 0; mapped && i < 10; i++) {
    mapped = bytes[i] == 0;
  }
  if (mapped) return bytes.sublist(12).join('.');
  StringBuffer out = StringBuffer();
  for (int i = 0; i < 8; i += 2) {
    out
      ..write(((bytes[i] << 8) | bytes[i + 1]).toRadixString(16))
      ..write(':');
  }
  out.write(':/64');
  return out.toString();
}