/*
 * nasd_generic_hostlocal.c
 *
 * Determine whether a hostname refers to the local machine.
 *
 * Author: Nat Lanza
 */
/*
 * Copyright (c) of Carnegie Mellon University, 2000.
 *
 * Permission to reproduce, use, and prepare derivative works of
 * this software for internal use is granted provided the copyright
 * and "No Warranty" statements are included with all reproductions
 * and derivative works. This software may also be redistributed
 * without charge provided that the copyright and "No Warranty"
 * statements are included in all redistributions.
 *
 * NO WARRANTY. THIS SOFTWARE IS FURNISHED ON AN "AS IS" BASIS.
 * CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER
 * EXPRESSED OR IMPLIED AS TO THE MATTER INCLUDING, BUT NOT LIMITED
 * TO: WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY
 * OF RESULTS OR RESULTS OBTAINED FROM USE OF THIS SOFTWARE. CARNEGIE
 * MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT
 * TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
 */

#include <nasd/nasd_options.h>
#include <nasd/nasd_common.h>
#include <nasd/nasd_sys.h>
#include <nasd/nasd_general.h>
#include <nasd/nasd_threadstuff.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>

nasd_status_t nasd_hostlocal(char *remote_name) {
  int i, sock;
  nasd_status_t rc = NASD_FAIL;
  char buf[1024];
  struct ifconf ifc;
  struct sockaddr_in *sockaddr = NULL;
  struct hostent he;

  ifc.ifc_len = sizeof(buf);
  ifc.ifc_ifcu.ifcu_buf = buf;

  rc = nasd_gethostbyname_r(remote_name, &he);
  if (rc == -1) { return NASD_FAIL; }

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock == -1) { return NASD_FAIL; }

  rc = ioctl(sock, SIOCGIFCONF, &ifc);
  close(sock);

  if (rc == -1) { return NASD_FAIL; }

  for (i = 0; i < (ifc.ifc_len / sizeof(struct ifreq)); i++) {
    sockaddr = (struct sockaddr_in *) &ifc.ifc_ifcu.ifcu_req[i].ifr_addr;
    if (!memcmp(he.h_addr_list[0], &sockaddr->sin_addr.s_addr, 4)) {
      return NASD_SUCCESS;
    }
  }

  return NASD_FAIL;
}
