/* Standalone check of the localhost predicate in git-localhost-timeout.
 * No sockets are opened and no network configuration is changed.
 */
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int is_localhost(const struct addrinfo *cur, int corrected) {
  const struct in6_addr ip6_localhost = IN6ADDR_LOOPBACK_INIT;

  return (cur->ai_family == AF_INET
          && (ntohl(((struct sockaddr_in *)cur->ai_addr)->sin_addr.s_addr) & IN_CLASSA_NET)
             == (INADDR_LOOPBACK & IN_CLASSA_NET))
         || (cur->ai_family == AF_INET6
             && !memcmp(corrected ? (const void *)&((struct sockaddr_in6 *)cur->ai_addr)->sin6_addr
                                  : (const void *)cur->ai_addr,
                        &ip6_localhost, sizeof(ip6_localhost)));
}

int main(void) {
  static const struct {
    const char *host;
    int original_expected;
    int corrected_expected;
  } cases[] = {
    {"::1", 0, 1},
    {"2001:db8::1", 0, 0},
    {"127.0.0.1", 1, 1},
    {"127.0.0.2", 1, 1},
    {"192.0.2.1", 0, 0},
  };
  const struct addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV};
  int failed = 0;

  for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
    struct addrinfo *address = NULL;
    int error = getaddrinfo(cases[i].host, "4101", &hints, &address);
    if (error) {
      fprintf(stderr, "%s: %s\n", cases[i].host, gai_strerror(error));
      return EXIT_FAILURE;
    }
    int original = is_localhost(address, 0);
    int corrected = is_localhost(address, 1);
    printf("%-12s original=%d corrected=%d\n", cases[i].host, original, corrected);
    failed |= original != cases[i].original_expected || corrected != cases[i].corrected_expected;
    freeaddrinfo(address);
  }
  return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
