Example #1
1
static int
internal_function
getbroadcastnets (struct in_addr *addrs, int sock, char *buf)
  /* int sock:  any valid socket will do */
  /* char *buf:	why allocate more when we can use existing... */
{
  struct ifconf ifc;
  struct ifreq ifreq, *ifr;
  struct sockaddr_in *sin;
  int n, i;

  ifc.ifc_len = UDPMSGSIZE;
  ifc.ifc_buf = buf;
  if (ioctl (sock, SIOCGIFCONF, (char *) &ifc) < 0)
    {
      perror (_("broadcast: ioctl (get interface configuration)"));
      return (0);
    }
  ifr = ifc.ifc_req;
  for (i = 0, n = ifc.ifc_len / sizeof (struct ifreq); n > 0; n--, ifr++)
    {
      ifreq = *ifr;
      if (ioctl (sock, SIOCGIFFLAGS, (char *) &ifreq) < 0)
	{
	  perror (_("broadcast: ioctl (get interface flags)"));
	  continue;
	}
      if ((ifreq.ifr_flags & IFF_BROADCAST) &&
	  (ifreq.ifr_flags & IFF_UP) &&
	  ifr->ifr_addr.sa_family == AF_INET)
	{
	  sin = (struct sockaddr_in *) &ifr->ifr_addr;
#ifdef SIOCGIFBRDADDR		/* 4.3BSD */
	  if (ioctl (sock, SIOCGIFBRDADDR, (char *) &ifreq) < 0)
	    {
	      addrs[i++] = inet_makeaddr (inet_netof
	      /* Changed to pass struct instead of s_addr member
	         by roland@gnu.  */
					  (sin->sin_addr), INADDR_ANY);
	    }
	  else
	    {
	      addrs[i++] = ((struct sockaddr_in *)
			    &ifreq.ifr_addr)->sin_addr;
	    }
#else /* 4.2 BSD */
	  addrs[i++] = inet_makeaddr (inet_netof
				      (sin->sin_addr.s_addr), INADDR_ANY);
#endif
	}
    }
  return i;
}
Example #2
0
void addrouteforif(struct interface *ifp)
{
    struct sockaddr_in net;
    struct sockaddr *dst;
    int state;
    struct rt_entry *rt;

    if (ifp->int_flags & IFF_POINTOPOINT)
        dst = &ifp->int_dstaddr;
    else {
        memset(&net, 0, sizeof (net));
        net.sin_family = AF_INET;
        net.sin_addr = inet_makeaddr(ifp->int_subnet, INADDR_ANY);
        dst = (struct sockaddr *)&net;
    }
    rt = rtfind(dst);
    if (rt &&
            (rt->rt_state & (RTS_INTERFACE | RTS_INTERNAL)) == RTS_INTERFACE)
        return;
    if (rt)
        rtdelete(rt);
    /*
     * If interface on subnetted network,
     * install route to network as well.
     * This is meant for external viewers.
     */
    if ((ifp->int_flags & (IFF_SUBNET|IFF_POINTOPOINT)) == IFF_SUBNET) {
        struct in_addr subnet;

        subnet = net.sin_addr;
        net.sin_addr = inet_makeaddr(ifp->int_net, INADDR_ANY);
        rt = rtfind(dst);
        if (rt == 0)
            rtadd(dst, &ifp->int_addr, ifp->int_metric,
                  ((ifp->int_flags & (IFF_INTERFACE|IFF_REMOTE)) |
                   RTS_PASSIVE | RTS_INTERNAL | RTS_SUBNET));
        else if ((rt->rt_state & (RTS_INTERNAL|RTS_SUBNET)) ==
                 (RTS_INTERNAL|RTS_SUBNET) &&
                 ifp->int_metric < rt->rt_metric)
            rtchange(rt, &rt->rt_router, ifp->int_metric);
        net.sin_addr = subnet;
    }
    if (ifp->int_transitions++ > 0)
        syslog(LOG_ERR, "re-installing interface %s", ifp->int_name);
    state = ifp->int_flags &
            (IFF_INTERFACE | IFF_PASSIVE | IFF_REMOTE | IFF_SUBNET);
    if (ifp->int_flags & IFF_POINTOPOINT &&
            (ntohl(((struct sockaddr_in *)&ifp->int_dstaddr)->sin_addr.s_addr) &
             ifp->int_netmask) != ifp->int_net)
        state &= ~RTS_SUBNET;
    if (ifp->int_flags & IFF_LOOPBACK)
        state |= RTS_EXTERNAL;
    rtadd(dst, &ifp->int_addr, ifp->int_metric, state);
    if (ifp->int_flags & IFF_POINTOPOINT && foundloopback)
        add_ptopt_localrt(ifp);
}
Example #3
0
int
res_build_finish(res_state res, uint32_t timeout, uint16_t port)
{
	if (res == NULL) return -1;
	
	if (res->nscount == 0)
	{
#ifdef USELOOPBACK
		res->nsaddr_list[0].sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
		res->nsaddr_list[0].sin_addr.s_addr = INADDR_ANY;
#endif
		
		res->nsaddr_list[0].sin_family = AF_INET;
		res->nsaddr_list[0].sin_port = htons(port);
#ifdef HAVE_SA_LEN
		res->nsaddr_list[0].sin_len = sizeof(struct sockaddr_in);
#endif
		
		res->nscount = 1;

		/*
		 * Force loopback queries to use TCP
		 * so we don't take a timeout if named isn't running.
		 */
		res->options |= RES_USEVC;
	}
	
	if (timeout == 0) res->retrans = RES_MAXRETRANS;
	else res->retrans = timeout;

	res->options |= RES_INIT;
	return 0;
}
Example #4
0
void add_ptopt_localrt(struct interface *ifp)
{
    struct rt_entry *rt;
    struct sockaddr *dst;
    struct sockaddr_in net;
    int state;

    state = RTS_INTERFACE | RTS_PASSIVE;

    /* look for route to logical network */
    memset(&net, 0, sizeof (net));
    net.sin_family = AF_INET;
    net.sin_addr = inet_makeaddr(ifp->int_net, INADDR_ANY);
    dst = (struct sockaddr *)&net;
    rt = rtfind(dst);
    if (rt && rt->rt_state & RTS_INTERNAL)
        state |= RTS_SUBNET;

    dst = &ifp->int_addr;
    if ((rt = rtfind(dst))!=NULL) {
        if (rt && rt->rt_state & RTS_INTERFACE)
            return;
        rtdelete(rt);
    }
    rtadd(dst, &loopaddr, 1, state);
}
Example #5
0
int getnetorhostname(char *type, char *name, struct sockaddr_in *sin)
{
#ifndef EMBED

    if (strcmp(type, "net") == 0) {
        struct netent *np = getnetbyname(name);
        int n;

        if (np == 0)
            n = inet_network(name);
        else {
            if (np->n_addrtype != AF_INET)
                return (0);
            n = np->n_net;
            /*
             * getnetbyname returns right-adjusted value.
             */
            if (n < 128)
                n <<= IN_CLASSA_NSHIFT;
            else if (n < 65536)
                n <<= IN_CLASSB_NSHIFT;
            else
                n <<= IN_CLASSC_NSHIFT;
        }
        sin->sin_family = AF_INET;
        sin->sin_addr = inet_makeaddr(n, INADDR_ANY);
        return (1);
    }
    if (strcmp(type, "host") == 0)
        return (gethostnameornumber(name, sin));
#endif
    return (0);
}
Example #6
0
_PUBLIC_ struct in_addr sys_inet_makeaddr(int net, int host)
{
	struct in_addr in;
	struct in_addr in2;
	in = inet_makeaddr(net, host);
	in2.s_addr = in.s_addr;
	return in2;
}
Example #7
0
int
main(int argc,char **argv) {
    int x;
    struct sockaddr_in adr_inet;/* AF_INET */
    const char *addr[] = {
        "44.135.86.12",
        "127.0.0.1",
        "172.16.23.95",
        "192.168.9.1"
    };
    unsigned long net, hst;

    for ( x=0; x<4; ++x ) {
        /*
         * Create a socket address:
         */
        memset(&adr_inet,0,sizeof adr_inet);
        adr_inet.sin_family = AF_INET;
        adr_inet.sin_port = htons(9000);
        if ( !inet_aton(addr[x],
                  &adr_inet.sin_addr) )
            puts("bad address.");

        /*
         * Split address into Host & Net ID
         */
        hst = inet_lnaof(adr_inet.sin_addr);
        net = inet_netof(adr_inet.sin_addr);

        printf("%14s : net=0x%08lX host=0x%08lX\n",
            inet_ntoa(adr_inet.sin_addr),net,hst);

        /*
         * Zero the address to prove later that
         * we can reconstruct this value :
         */
        memset(&adr_inet,0,sizeof adr_inet);
        adr_inet.sin_family = AF_INET;
        adr_inet.sin_port = htons(9000);

        adr_inet.sin_addr =
            inet_makeaddr(net,hst);

        /*
         * Now display the reconstructed
         * address :
         */
        printf("%14s : %s\n\n",
            "inet_makeaddr",
            inet_ntoa(adr_inet.sin_addr));
    }

    return 0;
}
Example #8
0
void ReadNetworksFile (const char *fname)
{
  static int been_here = 0;

  if (!fname || !*fname)
     return;

  if (been_here)  /* loading multiple network files */
  {
    free (networkFname);
    fclose (networkFile);
    networkFile = NULL;
  }
  been_here = 1;

  networkFname = strdup (fname);
  if (!networkFname)
     return;

  setnetent (1);
  if (!networkFile)
     return;

  while (1)
  {
    struct _netent *n, *n2 = (struct _netent*) getnetent();

    if (!n2 || (n = malloc(sizeof(*n))) == NULL)
       break;

    *n = *n2;
    n->next  = network0;
    network0 = n;
  }
  rewind (networkFile);
  atexit (endnetent);

#if 0  /* test */
  {
    struct _netent *n;

    printf ("%s entries:\n", fname);
    for (n = network0; n; n = n->next)
    {
      int i;
      printf ("net = %-15.15s name = %-10.10s  alias:",
              inet_ntoa(inet_makeaddr(n->n_net,0)), n->n_name);
      for (i = 0; n->n_aliases && n->n_aliases[i]; i++)
            printf (" %s", n->n_aliases[i]);
      puts ("");
    }
  }
#endif
}
Example #9
0
static void
networksprint(const struct netent *ne)
{
	char		buf[INET6_ADDRSTRLEN];
	struct in_addr	ianet;

	ianet = inet_makeaddr(ne->n_net, 0);
	if (inet_ntop(ne->n_addrtype, &ianet, buf, sizeof(buf)) == NULL)
		strlcpy(buf, "# unknown", sizeof(buf));
	printfmtstrings(ne->n_aliases, "  ", " ", "%-16s  %s", ne->n_name, buf);
}
void fill_mapping_data_for_ipv6_addr(struct polymorphic_addr *real_ipv6_pa, struct mapping_data *data)
{
	unsigned int my_index = mapping_index++; // this is considered atomic (in a multi-threaded program)
	struct in_addr ipv4_addr;
	int length;
	static __thread struct ipv4_pool_info pool;
	static __thread int pool_initialized = 0;

	if (pool_initialized == 0)
	{
		original_inet_aton(stringified(IPV4_POOL_START), &ipv4_addr);
		pool.start = inet_lnaof(ipv4_addr);
		original_inet_aton(stringified(IPV4_POOL_END), &ipv4_addr);
		pool.end = inet_lnaof(ipv4_addr);
		pool_initialized = 1;
	}
	
	// detect overflows...
	if (my_index > pool.end - pool.start)
	{
		printf("IPV6 CARE: IPV4 POOL OVERFLOW! YOU SHOULD DESACTIVATE IPV6 CARE.\n");
		printf("IPV6 CARE: THIS PROCESS MAY SHOW UNEXPECTED BEHAVIORS IN NAME RESOLUTIONS FROM NOW ON!\n");
		// maybe we are running a critical application, so we should not stop.
		// let's get a correct value, even if it's already used...
		my_index %= pool.end - pool.start + 1;
	}

	// pa[real_ipv6_addr]
	memcpy(&data->pa[real_ipv6_addr], real_ipv6_pa, sizeof(*real_ipv6_pa));

	// pa[mapped_ipv4_addr]
	ipv4_addr = inet_makeaddr(INADDR_ANY, pool.start + my_index);
	copy_ipv4_addr_to_pa(&ipv4_addr, &data->pa[mapped_ipv4_addr]);

	// ip_text_forms[mapped_ipv4]
	original_inet_ntop(AF_INET, &ipv4_addr, data->ip_text_forms[mapped_ipv4], INET_ADDRSTRLEN);

	// ip_text_forms[full_ipv6]
	original_inet_ntop(AF_INET6, &real_ipv6_pa->addr.ipv6_addr, data->ip_text_forms[full_ipv6], INET6_ADDRSTRLEN);

	// ip_text_forms[abbreviated_ipv6]
	if (strlen(data->ip_text_forms[full_ipv6]) > INET_ADDRSTRLEN -1)
	{
		data->ip_text_forms[abbreviated_ipv6][0] = '.';
		data->ip_text_forms[abbreviated_ipv6][1] = '.';
		length = strlen(data->ip_text_forms[full_ipv6]);
		strcpy(&data->ip_text_forms[abbreviated_ipv6][2], &data->ip_text_forms[full_ipv6][length - INET_ADDRSTRLEN +3]);
	}
	else
	{
		strcpy(data->ip_text_forms[abbreviated_ipv6], data->ip_text_forms[full_ipv6]);
	}
}
Example #11
0
int main()
{	char buffer[32];
	int ret = 0;
	int host = 0;
	int network = 0;
	unsigned int address = 0;
	struct in_addr in;
	in.s_addr = 0;

	/*输入一个以.分隔的字符串形式的ip地址*/
	printf("please input your ip address:");
		fgets(buffer, 31, stdin);
	buffer[31] = '\0';
	
	/*示例使用inet_aton()函数*/
	if((ret = inet_aton(buffer, &in) == 0))
		printf("inet_aton:\t invalid address\n");
	else
		printf("inet_aton:\t0x%x\n", in.s_addr);

	/*示例使用inet_addr()函数*/
	if((address = inet_addr(buffer)) == INADDR_NONE)
		printf("inet_addr:\t invalid address\n");
	else
		printf("inet_addr:\t 0x%x\n", address);

	/*示例使用inet_network()函数*/
	if((address = inet_network(buffer)) == -1)
		printf("inet_work:\t invalid address\n");
	else
		printf("inet_work:\t 0x%x\n", address);

	/*示例使用inet_ntoa()函数*/
	if(inet_ntoa(in) == NULL)
		printf("inet_ntoa:\t invalid address\n");
	else
		printf("inet_ntoa:\t%s\n", inet_ntoa(in));

	/*示例使用inet_lnaof()与inet_netof()函数*/
	host = inet_lnaof(in);
	network = inet_netof(in);
	printf("inet_lnaof:\t 0x%x\n", host);
	printf("inet_netof:\t 0x%x\n", network);
	
	in = inet_makeaddr(network, host);
	printf("inet_makeaddr: 0x%x\n", in.s_addr);

	return 0;
	
}
Example #12
0
static void
in_getaddr(const char *s, int which)
{
#define	MIN(a,b)	((a)<(b)?(a):(b))
	struct sockaddr_in *sin = sintab[which];
	struct hostent *hp;
	struct netent *np;

	sin->sin_len = sizeof(*sin);
	if (which != MASK)
		sin->sin_family = AF_INET;

	if (which == ADDR) {
		char *p = NULL;

		if((p = strrchr(s, '/')) != NULL) {
			const char *errstr;
			/* address is `name/masklen' */
			int masklen;
			struct sockaddr_in *min = sintab[MASK];
			*p = '\0';
			if (!isdigit(*(p + 1)))
				errstr = "invalid";
			else
				masklen = (int)strtonum(p + 1, 0, 32, &errstr);
			if (errstr != NULL) {
				*p = '/';
				errx(1, "%s: bad value (width %s)", s, errstr);
			}
			min->sin_len = sizeof(*min);
			min->sin_addr.s_addr = htonl(~((1LL << (32 - masklen)) - 1) & 
				              0xffffffff);
		}
	}

	if (inet_aton(s, &sin->sin_addr))
		return;
	if ((hp = gethostbyname(s)) != 0)
		bcopy(hp->h_addr, (char *)&sin->sin_addr, 
		    MIN((size_t)hp->h_length, sizeof(sin->sin_addr)));
	else if ((np = getnetbyname(s)) != 0)
		sin->sin_addr = inet_makeaddr(np->n_net, INADDR_ANY);
	else
		errx(1, "%s: bad value", s);
#undef MIN
}
Example #13
0
static void
in_getaddr(const char *s, int which)
{
#ifndef MIN
#define	MIN(a,b)	((a)<(b)?(a):(b))
#endif /* MIN */
    struct sockaddr_in *sin = sintab[which];
    struct hostent *hp;
    struct netent *np;

    sin->sin_len = sizeof(*sin);
    if (which != MASK)
        sin->sin_family = AF_INET;

    if (which == ADDR) {
        char *p = NULL;

        if((p = strrchr(s, '/')) != NULL) {
            /* address is `name/masklen' */
            int masklen;
            int ret;
            struct sockaddr_in *min = sintab[MASK];
            *p = '\0';
            ret = sscanf(p+1, "%u", &masklen);
            if(ret != 1 || (masklen < 0 || masklen > 32)) {
                *p = '/';
                errx(1, "%s: bad value", s);
            }
            min->sin_len = sizeof(*min);
            min->sin_addr.s_addr = htonl(~((1LL << (32 - masklen)) - 1) &
                                         0xffffffff);
        }
    }

    if (inet_aton(s, &sin->sin_addr))
        return;
    if ((hp = gethostbyname(s)) != 0)
        bcopy(hp->h_addr, (char *)&sin->sin_addr,
              MIN(hp->h_length, sizeof(sin->sin_addr)));
    else if ((np = getnetbyname(s)) != 0)
        sin->sin_addr = inet_makeaddr(np->n_net, INADDR_ANY);
    else
        errx(1, "%s: bad value", s);
#undef MIN
}
Example #14
0
File: pmap_rmt.c Project: PADL/krb5
static int
getbroadcastnets(
	struct in_addr *addrs,
	int sock,  /* any valid socket will do */
	char *buf  /* why allocxate more when we can use existing... */
	)
{
	struct ifconf ifc;
        struct ifreq ifreq, *ifr;
        int n, i;

        ifc.ifc_len = GIFCONF_BUFSIZE;
        ifc.ifc_buf = buf;
	memset (buf, 0, GIFCONF_BUFSIZE);
        if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
                perror("broadcast: ioctl (get interface configuration)");
                return (0);
        }
        ifr = ifc.ifc_req;
        for (i = 0, n = ifc.ifc_len/sizeof (struct ifreq); n > 0; n--, ifr++) {
                ifreq = *ifr;
                if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifreq) < 0) {
                        perror("broadcast: ioctl (get interface flags)");
                        continue;
                }
                if ((ifreq.ifr_flags & IFF_BROADCAST) &&
		    (ifreq.ifr_flags & IFF_UP) &&
		    ifr->ifr_addr.sa_family == AF_INET) {
#ifdef SIOCGIFBRDADDR   /* 4.3BSD */
			if (ioctl(sock, SIOCGIFBRDADDR, (char *)&ifreq) < 0) {
				addrs[i++].s_addr = INADDR_ANY;
			} else {
				addrs[i++] = sa2sin(&ifreq.ifr_addr)->sin_addr;
			}
#else /* 4.2 BSD */
			struct sockaddr_in *sockin;
			sockin = sa2sin(&ifr->ifr_addr);
			addrs[i++] = inet_makeaddr(inet_netof
			  (sockin->sin_addr.s_addr), INADDR_ANY);
#endif
		}
	}
	return (i);
}
Example #15
0
void
in_getaddr(char *s, int which)
{
	struct sockaddr_in *sin = sintab[which];
	struct hostent *hp;
	struct netent *np;

	sin->sin_len = sizeof(*sin);
	sin->sin_family = AF_INET;

	if (inet_aton(s, &sin->sin_addr))
		;
	else if ((hp = gethostbyname(s)) != NULL)
		bcopy(hp->h_addr, (char *)&sin->sin_addr, hp->h_length);
	else if ((np = getnetbyname(s)) != NULL)
		sin->sin_addr = inet_makeaddr(np->n_net, INADDR_ANY);
	else
		errx(1, "%s: bad value", s);
}
Example #16
0
static int nettoa(int anet, char *buf, char *buf2, int buflen)
{
	int		addr;
	char		*p;
	struct in_addr	in;

	if (buf == NULL || buf2 == NULL)
		return ((int)1);

	in = inet_makeaddr(anet, INADDR_ANY);
	addr = in.s_addr;
	if (inet_ntop(AF_INET, (const void *)&in, buf2, INET_ADDRSTRLEN)
			== NULL)
		return ((int)1);
	if (strlcpy(buf, buf2, buflen) >= buflen)
		return ((int)1);
	if ((IN_CLASSA_HOST & htonl(addr)) == 0) {
		p = strchr(buf, '.');
		if (p == NULL)
			return ((int)1);
		*p = 0;
	} else if ((IN_CLASSB_HOST & htonl(addr)) == 0) {
		p = strchr(buf, '.');
		if (p == NULL)
			return ((int)1);
		p = strchr(p + 1, '.');
		if (p == NULL)
			return ((int)1);
		*p = 0;
	} else if ((IN_CLASSC_HOST & htonl(addr)) == 0) {
		p = strrchr(buf, '.');
		if (p == NULL)
			return ((int)1);
		*p = 0;
	}

	return ((int)0);
}
Example #17
0
/*% This function has to be reachable by res_data.c but not publically. */
int
__res_vinit(res_state statp, int preinit) {
	register FILE *fp;
	register char *cp, **pp;
	register int n;
	char path[PATH_MAX];
	char buf[BUFSIZ];
	int nserv = 0;    /*%< number of nameserver records read from file */
	int haveenv = 0;
	int havesearch = 0;
#ifdef RESOLVSORT
	int nsort = 0;
	char *net;
#endif
	int dots;
	union res_sockaddr_union u[2];
	int maxns = MAXNS;

	RES_SET_H_ERRNO(statp, 0);
	if (statp->_u._ext.ext != NULL)
		res_ndestroy(statp);

	if (!preinit) {
		statp->retrans = RES_TIMEOUT;
		statp->retry = RES_DFLRETRY;
		statp->options = RES_DEFAULT;
		res_rndinit(statp);
		statp->id = res_nrandomid(statp);
	}

	memset(u, 0, sizeof(u));
#ifdef USELOOPBACK
	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
#endif
	u[nserv].sin.sin_family = AF_INET;
	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
#ifdef HAVE_SA_LEN
	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
#endif
	nserv++;
#ifdef HAS_INET6_STRUCTS
#ifdef USELOOPBACK
	u[nserv].sin6.sin6_addr = in6addr_loopback;
#else
	u[nserv].sin6.sin6_addr = in6addr_any;
#endif
	u[nserv].sin6.sin6_family = AF_INET6;
	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
#ifdef HAVE_SA_LEN
	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif
	nserv++;
#endif
	statp->nscount = 0;
	statp->ndots = 1;
	statp->pfcode = 0;
	statp->_vcsock = -1;
	statp->_flags = 0;
	statp->qhook = NULL;
	statp->rhook = NULL;
	statp->_u._ext.nscount = 0;
	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
	if (statp->_u._ext.ext != NULL) {
	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
	} else {
		/*
		 * Historically res_init() rarely, if at all, failed.
		 * Examples and applications exist which do not check
		 * our return code.  Furthermore several applications
		 * simply call us to get the systems domainname.  So
		 * rather then immediately fail here we store the
		 * failure, which is returned later, in h_errno.  And
		 * prevent the collection of 'nameserver' information
		 * by setting maxns to 0.  Thus applications that fail
		 * to check our return code wont be able to make
		 * queries anyhow.
		 */
		RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
		maxns = 0;
	}
#ifdef RESOLVSORT
	statp->nsort = 0;
#endif
	res_setservers(statp, u, nserv);

#ifdef	SOLARIS2
	/*
	 * The old libresolv derived the defaultdomain from NIS/NIS+.
	 * We want to keep this behaviour
	 */
	{
		char buf[sizeof(statp->defdname)], *cp;
		int ret;

		if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
			(unsigned int)ret <= sizeof(buf)) {
			if (buf[0] == '+')
				buf[0] = '.';
			cp = strchr(buf, '.');
			cp = (cp == NULL) ? buf : (cp + 1);
			strncpy(statp->defdname, cp,
				sizeof(statp->defdname) - 1);
			statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		}
	}
#endif	/* SOLARIS2 */

	/* Allow user to override the local domain definition */
	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		haveenv++;

		/*
		 * Set search list to be blank-separated strings
		 * from rest of env value.  Permits users of LOCALDOMAIN
		 * to still have a search list, and anyone to set the
		 * one that they want to use as an individual (even more
		 * important now that the rfc1535 stuff restricts searches)
		 */
		cp = statp->defdname;
		pp = statp->dnsrch;
		*pp++ = cp;
		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
			if (*cp == '\n')	/*%< silly backwards compat */
				break;
			else if (*cp == ' ' || *cp == '\t') {
				*cp = 0;
				n = 1;
			} else if (n) {
				*pp++ = cp;
				n = 0;
				havesearch = 1;
			}
		}
		/* null terminate last domain if there are excess */
		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
			cp++;
		*cp = '\0';
		*pp++ = 0;
	}

#define	MATCH(line, name) \
	(!strncmp(line, name, sizeof(name) - 1) && \
	(line[sizeof(name) - 1] == ' ' || \
	 line[sizeof(name) - 1] == '\t'))

	if (find_directory(B_COMMON_SETTINGS_DIRECTORY, -1, false, path,
			sizeof(path)) == B_OK)
		strlcat(path, "/network/resolv.conf", sizeof(path));

	nserv = 0;
	if ((fp = fopen(path, "r")) != NULL) {
	    /* read the config file */
	    while (fgets(buf, sizeof(buf), fp) != NULL) {
		/* skip comments */
		if (*buf == ';' || *buf == '#')
			continue;
		/* read default domain name */
		if (MATCH(buf, "domain")) {
		    if (haveenv)	/*%< skip if have from environ */
			    continue;
		    cp = buf + sizeof("domain") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
			    *cp = '\0';
		    havesearch = 0;
		    continue;
		}
		/* set search list */
		if (MATCH(buf, "search")) {
		    if (haveenv)	/*%< skip if have from environ */
			    continue;
		    cp = buf + sizeof("search") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
			    *cp = '\0';
		    /*
		     * Set search list to be blank-separated strings
		     * on rest of line.
		     */
		    cp = statp->defdname;
		    pp = statp->dnsrch;
		    *pp++ = cp;
		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
			    if (*cp == ' ' || *cp == '\t') {
				    *cp = 0;
				    n = 1;
			    } else if (n) {
				    *pp++ = cp;
				    n = 0;
			    }
		    }
		    /* null terminate last domain if there are excess */
		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
			    cp++;
		    *cp = '\0';
		    *pp++ = 0;
		    havesearch = 1;
		    continue;
		}
		/* read nameservers to query */
		if (MATCH(buf, "nameserver") && nserv < maxns) {
		    struct addrinfo hints, *ai;
		    char sbuf[NI_MAXSERV];
		    const size_t minsiz =
		        sizeof(statp->_u._ext.ext->nsaddrs[0]);

		    cp = buf + sizeof("nameserver") - 1;
		    while (*cp == ' ' || *cp == '\t')
			cp++;
		    cp[strcspn(cp, ";# \t\n")] = '\0';
		    if ((*cp != '\0') && (*cp != '\n')) {
			memset(&hints, 0, sizeof(hints));
			hints.ai_family = PF_UNSPEC;
			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
			hints.ai_flags = AI_NUMERICHOST;
			sprintf(sbuf, "%u", NAMESERVER_PORT);
			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
			    ai->ai_addrlen <= minsiz) {
			    if (statp->_u._ext.ext != NULL) {
				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
				    ai->ai_addr, ai->ai_addrlen);
			    }
			    if (ai->ai_addrlen <=
			        sizeof(statp->nsaddr_list[nserv])) {
				memcpy(&statp->nsaddr_list[nserv],
				    ai->ai_addr, ai->ai_addrlen);
			    } else
				statp->nsaddr_list[nserv].sin_family = 0;
			    freeaddrinfo(ai);
			    nserv++;
			}
		    }
		    continue;
		}
#ifdef RESOLVSORT
		if (MATCH(buf, "sortlist")) {
		    struct in_addr a;

		    cp = buf + sizeof("sortlist") - 1;
		    while (nsort < MAXRESOLVSORT) {
			while (*cp == ' ' || *cp == '\t')
			    cp++;
			if (*cp == '\0' || *cp == '\n' || *cp == ';')
			    break;
			net = cp;
			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
			       isascii(*cp) && !isspace((unsigned char)*cp))
				cp++;
			n = *cp;
			*cp = 0;
			if (inet_aton(net, &a)) {
			    statp->sort_list[nsort].addr = a;
			    if (ISSORTMASK(n)) {
				*cp++ = n;
				net = cp;
				while (*cp && *cp != ';' &&
					isascii(*cp) &&
					!isspace((unsigned char)*cp))
				    cp++;
				n = *cp;
				*cp = 0;
				if (inet_aton(net, &a)) {
				    statp->sort_list[nsort].mask = a.s_addr;
				} else {
				    statp->sort_list[nsort].mask = 
					net_mask(statp->sort_list[nsort].addr);
				}
			    } else {
				statp->sort_list[nsort].mask = 
				    net_mask(statp->sort_list[nsort].addr);
			    }
			    nsort++;
			}
			*cp = n;
		    }
		    continue;
		}
#endif
		if (MATCH(buf, "options")) {
		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
		    continue;
		}
	    }
	    if (nserv > 0) 
		statp->nscount = nserv;
#ifdef RESOLVSORT
	    statp->nsort = nsort;
#endif
	    (void) fclose(fp);
	}
/*
 * Last chance to get a nameserver.  This should not normally
 * be necessary
 */
#ifdef NO_RESOLV_CONF
	if(nserv == 0)
		nserv = get_nameservers(statp);
#endif

	if (statp->defdname[0] == 0 &&
	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
	    (cp = strchr(buf, '.')) != NULL)
		strcpy(statp->defdname, cp + 1);

	/* find components of local domain that might be searched */
	if (havesearch == 0) {
		pp = statp->dnsrch;
		*pp++ = statp->defdname;
		*pp = NULL;

		dots = 0;
		for (cp = statp->defdname; *cp; cp++)
			dots += (*cp == '.');

		cp = statp->defdname;
		while (pp < statp->dnsrch + MAXDFLSRCH) {
			if (dots < LOCALDOMAINPARTS)
				break;
			cp = strchr(cp, '.') + 1;    /*%< we know there is one */
			*pp++ = cp;
			dots--;
		}
		*pp = NULL;
#ifdef DEBUG
		if (statp->options & RES_DEBUG) {
			printf(";; res_init()... default dnsrch list:\n");
			for (pp = statp->dnsrch; *pp; pp++)
				printf(";;\t%s\n", *pp);
			printf(";;\t..END..\n");
		}
#endif
	}

	if ((cp = getenv("RES_OPTIONS")) != NULL)
		res_setoptions(statp, cp, "env");
	statp->options |= RES_INIT;
	return (statp->res_h_errno);
}
Example #18
0
struct in_addr wresolve_ip (const char * arg)
{

    struct in_addr resolved; 
    struct in_addr addr;
    unsigned long  netip    = 0;
    const char * ifname     = arg;
    int sock                = -1;
    int i=0;
    unsigned      numreqs=0;
    struct ifconf ifc;
    struct ifreq *ifr;
    resolved = inet_makeaddr(0,0);   
    addr = inet_makeaddr(0,0);   
    

    if (!arg || (strlen(arg)==0))
    {
        resolved.s_addr = INADDR_ANY;
        return resolved;
    }
    /* 1. try interpreting as network or host IP address */
    {
        netip   = inet_network (arg);
        if (netip != (unsigned long)(-1))
        {
            addr = inet_makeaddr(netip, 0);
        }
    }
    /* 2. try interpreting as network name */
    if (! addr.s_addr)
    {
        struct netent * net = getnetbyname (arg);
        if ((net != NULL) && (net->n_addrtype == AF_INET))
        {
            addr = inet_makeaddr (net->n_net, 0);
        }
    }
    /* 3. try interpreting as host name */
    if (! addr.s_addr)
    {
        struct hostent * host = gethostbyname (arg);
        if ((host != NULL) && (host->h_addrtype == AF_INET))
        {
            addr = *(struct in_addr *)(host->h_addr_list[0]);
        }
    }
    
    /* 4. try interpreting as a NIC interface name */
    numreqs = 30;
    sock = socket(AF_INET, SOCK_DGRAM, 0);

    ifc.ifc_buf = NULL;
    for (;;)
    {
        ifc.ifc_len = sizeof(struct ifreq) * numreqs;
        ifc.ifc_buf = (char *)malloc(ifc.ifc_len);
        if (ioctl(sock, SIOCGIFCONF, &ifc) < 0)
        {
            perror ("SIOCGIFCONF");
            resolved.s_addr = (unsigned long) -1;
            return resolved;
        }
        if (ifc.ifc_len == (sizeof(struct ifreq) * numreqs))
        {
            numreqs *= 2;
            continue;
        }
        break;
    }

    ifr = ifc.ifc_req;
    for (i = 0; i < ifc.ifc_len; i += sizeof(struct ifreq))
    {
        struct sockaddr_in    hostaddr; 
        struct sockaddr_in    netmask;  
        struct in_addr network  = inet_makeaddr(0,0);

        hostaddr.sin_addr = inet_makeaddr(0,0);
        netmask.sin_addr  = inet_makeaddr(0,0);
        
        if (ioctl(sock, SIOCGIFADDR, ifr) < 0)
        {
            perror ("SIOCGIFADDR");
            resolved.s_addr = (unsigned long)-1;
            return resolved;
        }
        memcpy (&hostaddr, &(ifr->ifr_addr), sizeof(struct sockaddr_in));

        if (ioctl(sock, SIOCGIFNETMASK, ifr) < 0)
        {
            perror ("SIOCGIFNETMASK");
            resolved.s_addr = (unsigned long)-1;
            return resolved;
        }
        memcpy (&netmask, &(ifr->ifr_addr), sizeof (struct sockaddr_in));
        network.s_addr = hostaddr.sin_addr.s_addr & netmask.sin_addr.s_addr;
        if (addr.s_addr)
        {
            if (addr.s_addr == hostaddr.sin_addr.s_addr)
            {
                resolved = hostaddr.sin_addr;
                break;
            }
            else if (addr.s_addr == network.s_addr)
            {
                resolved = hostaddr.sin_addr;
                break;
            }
        }

        if (strcmp(ifr->ifr_name, ifname) == 0)
        {
            resolved = hostaddr.sin_addr;
            break;
        }
        ifr++;
    }

    if (!resolved.s_addr)
    {
        resolved.s_addr = (unsigned long)-1;
    } 
    return (resolved);
}
Example #19
0
/* This function has to be reachable by res_data.c but not publically. */
int
minires_vinit(res_state statp, int preinit) {
	register FILE *fp;
	char *cp;
	register char **pp;
	register int n;
	char buf[BUFSIZ];
	int nserv = 0;    /* number of nameserver records read from file */
	int haveenv = 0;
	int havesearch = 0;
#ifdef RESOLVSORT
	int nsort = 0;
	char *net;
#endif
#ifndef RFC1535
	int dots;
#endif

	if (!preinit) {
		statp->retrans = RES_TIMEOUT;
		statp->retry = RES_DFLRETRY;
		statp->options = RES_DEFAULT;
		statp->id = res_randomid();
#if defined (TRACING)
		statp->id = trace_mr_res_randomid (statp -> id);
#endif
	}

#ifdef USELOOPBACK
	statp->nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
	statp->nsaddr.sin_addr.s_addr = INADDR_ANY;
#endif
	statp->nsaddr.sin_family = AF_INET;
	statp->nsaddr.sin_port = htons(NAMESERVER_PORT);
	statp->nscount = 1;
	statp->ndots = 1;
	statp->pfcode = 0;
	statp->_sock = -1;
	statp->_flags = 0;
	statp->qhook = NULL;
	statp->rhook = NULL;

	/* Allow user to override the local domain definition */
	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		haveenv++;

		/*
		 * Set search list to be blank-separated strings
		 * from rest of env value.  Permits users of LOCALDOMAIN
		 * to still have a search list, and anyone to set the
		 * one that they want to use as an individual (even more
		 * important now that the rfc1535 stuff restricts searches)
		 */
		cp = statp->defdname;
		pp = statp->dnsrch;
		*pp++ = cp;
		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
			if (*cp == '\n')	/* silly backwards compat */
				break;
			else if (*cp == ' ' || *cp == '\t') {
				*cp = 0;
				n = 1;
			} else if (n) {
				*pp++ = cp;
				n = 0;
				havesearch = 1;
			}
		}
		/* null terminate last domain if there are excess */
		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
			cp++;
		*cp = '\0';
		*pp++ = 0;
	}

#define	MATCH(line, name) \
	(!strncmp(line, name, sizeof(name) - 1) && \
	(line[sizeof(name) - 1] == ' ' || \
	 line[sizeof(name) - 1] == '\t'))

	if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
	    /* read the config file */
	    while (fgets(buf, sizeof(buf), fp) != NULL) {
		/* skip comments */
		if (*buf == ';' || *buf == '#')
			continue;
		/* read default domain name */
		if (MATCH(buf, "domain")) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("domain") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
			    *cp = '\0';
		    havesearch = 0;
		    continue;
		}
		/* set search list */
		if (MATCH(buf, "search")) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("search") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
			    *cp = '\0';
		    /*
		     * Set search list to be blank-separated strings
		     * on rest of line.
		     */
		    cp = statp->defdname;
		    pp = statp->dnsrch;
		    *pp++ = cp;
		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
			    if (*cp == ' ' || *cp == '\t') {
				    *cp = 0;
				    n = 1;
			    } else if (n) {
				    *pp++ = cp;
				    n = 0;
			    }
		    }
		    /* null terminate last domain if there are excess */
		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
			    cp++;
		    *cp = '\0';
		    *pp++ = 0;
		    havesearch = 1;
		    continue;
		}
		/* read nameservers to query */
		if (MATCH(buf, "nameserver") && nserv < MAXNS) {
		    struct in_addr a;

		    cp = buf + sizeof("nameserver") - 1;
		    while (*cp == ' ' || *cp == '\t')
			cp++;
		    if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
			statp->nsaddr_list[nserv].sin_addr = a;
			statp->nsaddr_list[nserv].sin_family = AF_INET;
			statp->nsaddr_list[nserv].sin_port =
				htons(NAMESERVER_PORT);
			nserv++;
		    }
		    continue;
		}
#ifdef RESOLVSORT
		if (MATCH(buf, "sortlist")) {
		    struct in_addr a;

		    cp = buf + sizeof("sortlist") - 1;
		    while (nsort < MAXRESOLVSORT) {
			while (*cp == ' ' || *cp == '\t')
			    cp++;
			if (*cp == '\0' || *cp == '\n' || *cp == ';')
			    break;
			net = cp;
			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
			       isascii((int)*cp) && !isspace((int)*cp))
				cp++;
			n = *cp;
			*cp = 0;
			if (inet_aton(net, &a)) {
			    statp->sort_list[nsort].addr = a;
			    if (ISSORTMASK(n)) {
				*cp++ = n;
				net = cp;
				while (*cp && *cp != ';' &&
					isascii((int)*cp) && !isspace((int)*cp))
				    cp++;
				n = *cp;
				*cp = 0;
				if (inet_aton(net, &a)) {
				    statp->sort_list[nsort].mask = a.s_addr;
				} else {
				    statp->sort_list[nsort].mask = 
					net_mask(statp->sort_list[nsort].addr);
				}
			    } else {
				statp->sort_list[nsort].mask = 
				    net_mask(statp->sort_list[nsort].addr);
			    }
			    nsort++;
			}
			*cp = n;
		    }
		    continue;
		}
#endif
		if (MATCH(buf, "options")) {
		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
		    continue;
		}
	    }
	    if (nserv > 1) 
		statp->nscount = nserv;
#ifdef RESOLVSORT
	    statp->nsort = nsort;
#endif
	    (void) fclose(fp);
	}
	if (statp->defdname[0] == 0 &&
	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
	    (cp = strchr(buf, '.')) != NULL)
		strcpy(statp->defdname, cp + 1);

	/* find components of local domain that might be searched */
	if (havesearch == 0) {
		pp = statp->dnsrch;
		*pp++ = statp->defdname;
		*pp = NULL;

#ifndef RFC1535
		dots = 0;
		for (cp = statp->defdname; *cp; cp++)
			dots += (*cp == '.');

		cp = statp->defdname;
		while (pp < statp->dnsrch + MAXDFLSRCH) {
			if (dots < LOCALDOMAINPARTS)
				break;
			cp = strchr(cp, '.') + 1;    /* we know there is one */
			*pp++ = cp;
			dots--;
		}
		*pp = NULL;
		if (statp->options & RES_DEBUG) {
			printf(";; res_init()... default dnsrch list:\n");
			for (pp = statp->dnsrch; *pp; pp++)
				printf(";;\t%s\n", *pp);
			printf(";;\t..END..\n");
		}
#endif /* !RFC1535 */
	}

	if ((cp = getenv("RES_OPTIONS")) != NULL)
		res_setoptions(statp, cp, "env");
	statp->options |= RES_INIT;
	return (0);
}
Example #20
0
/*
 * Set up default settings.  If the configuration file exist, the values
 * there will have precedence.  Otherwise, the server address is set to
 * INADDR_ANY and the default domain name comes from the gethostname().
 *
 * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
 * rather than INADDR_ANY ("0.0.0.0") as the default name server address
 * since it was noted that INADDR_ANY actually meant ``the first interface
 * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
 * it had to be "up" in order for you to reach your own name server.  It
 * was later decided that since the recommended practice is to always 
 * install local static routes through 127.0.0.1 for all your network
 * interfaces, that we could solve this problem without a code change.
 *
 * The configuration file should always be used, since it is the only way
 * to specify a default domain.  If you are running a server on your local
 * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
 * in the configuration file.
 *
 * Return 0 if completes successfully, -1 on error
 */
int
res_init()
{
	register FILE *fp;
	register char *cp, **pp;
	register int n;
	char buf[MAXDNAME];
	int nserv = 0;    /* number of nameserver records read from file */
	int haveenv = 0;
	int havesearch = 0;
#ifdef RESOLVSORT
	int nsort = 0;
	char *net;
#endif
#ifndef RFC1535
	int dots;
#endif

	/*
	 * These three fields used to be statically initialized.  This made
	 * it hard to use this code in a shared library.  It is necessary,
	 * now that we're doing dynamic initialization here, that we preserve
	 * the old semantics: if an application modifies one of these three
	 * fields of _res before res_init() is called, res_init() will not
	 * alter them.  Of course, if an application is setting them to
	 * _zero_ before calling res_init(), hoping to override what used
	 * to be the static default, we can't detect it and unexpected results
	 * will follow.  Zero for any of these fields would make no sense,
	 * so one can safely assume that the applications were already getting
	 * unexpected results.
	 *
	 * _res.options is tricky since some apps were known to diddle the bits
	 * before res_init() was first called. We can't replicate that semantic
	 * with dynamic initialization (they may have turned bits off that are
	 * set in RES_DEFAULT).  Our solution is to declare such applications
	 * "broken".  They could fool us by setting RES_INIT but none do (yet).
	 */
	if (!_res.retrans)
		_res.retrans = RES_TIMEOUT;
	if (!_res.retry)
		_res.retry = 4;
	if (!(_res.options & RES_INIT))
		_res.options = RES_DEFAULT;

	/*
	 * This one used to initialize implicitly to zero, so unless the app
	 * has set it to something in particular, we can randomize it now.
	 */
	if (!_res.id)
		_res.id = res_randomid();

#ifdef USELOOPBACK
	_res.nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
	_res.nsaddr.sin_addr.s_addr = INADDR_ANY;
#endif
	_res.nsaddr.sin_family = AF_INET;
	_res.nsaddr.sin_port = htons(NAMESERVER_PORT);
	_res.nscount = 1;
	_res.ndots = 1;
	_res.pfcode = 0;

	/* Allow user to override the local domain definition */
	if (issetugid() == 0 && (cp = getenv("LOCALDOMAIN")) != NULL) {
		(void)strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
		_res.defdname[sizeof(_res.defdname) - 1] = '\0';
		haveenv++;

		/*
		 * Set search list to be blank-separated strings
		 * from rest of env value.  Permits users of LOCALDOMAIN
		 * to still have a search list, and anyone to set the
		 * one that they want to use as an individual (even more
		 * important now that the rfc1535 stuff restricts searches)
		 */
		cp = _res.defdname;
		pp = _res.dnsrch;
		*pp++ = cp;
		for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
			if (*cp == '\n')	/* silly backwards compat */
				break;
			else if (*cp == ' ' || *cp == '\t') {
				*cp = 0;
				n = 1;
			} else if (n) {
				*pp++ = cp;
				n = 0;
				havesearch = 1;
			}
		}
		/* null terminate last domain if there are excess */
		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
			cp++;
		*cp = '\0';
		*pp++ = 0;
	}

#define	MATCH(line, name) \
	(!strncmp(line, name, sizeof(name) - 1) && \
	(line[sizeof(name) - 1] == ' ' || \
	 line[sizeof(name) - 1] == '\t'))

	if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
	    /* read the config file */
	    while (fgets(buf, sizeof(buf), fp) != NULL) {
		/* skip comments */
		if (*buf == ';' || *buf == '#')
			continue;
		/* read default domain name */
		if (MATCH(buf, "domain")) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("domain") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
		    _res.defdname[sizeof(_res.defdname) - 1] = '\0';
		    if ((cp = strpbrk(_res.defdname, " \t\n")) != NULL)
			    *cp = '\0';
		    havesearch = 0;
		    continue;
		}
		/* set search list */
		if (MATCH(buf, "search")) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("search") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
		    _res.defdname[sizeof(_res.defdname) - 1] = '\0';
		    if ((cp = strchr(_res.defdname, '\n')) != NULL)
			    *cp = '\0';
		    /*
		     * Set search list to be blank-separated strings
		     * on rest of line.
		     */
		    cp = _res.defdname;
		    pp = _res.dnsrch;
		    *pp++ = cp;
		    for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
			    if (*cp == ' ' || *cp == '\t') {
				    *cp = 0;
				    n = 1;
			    } else if (n) {
				    *pp++ = cp;
				    n = 0;
			    }
		    }
		    /* null terminate last domain if there are excess */
		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
			    cp++;
		    *cp = '\0';
		    *pp++ = 0;
		    havesearch = 1;
		    continue;
		}
		/* read nameservers to query */
		if (MATCH(buf, "nameserver") && nserv < MAXNS) {
		    struct in_addr a;

		    cp = buf + sizeof("nameserver") - 1;
		    while (*cp == ' ' || *cp == '\t')
			cp++;
		    if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
			_res.nsaddr_list[nserv].sin_addr = a;
			_res.nsaddr_list[nserv].sin_family = AF_INET;
			_res.nsaddr_list[nserv].sin_port =
				htons(NAMESERVER_PORT);
			nserv++;
		    }
		    continue;
		}
#ifdef RESOLVSORT
		if (MATCH(buf, "sortlist")) {
		    struct in_addr a;

		    cp = buf + sizeof("sortlist") - 1;
		    while (nsort < MAXRESOLVSORT) {
			while (*cp == ' ' || *cp == '\t')
			    cp++;
			if (*cp == '\0' || *cp == '\n' || *cp == ';')
			    break;
			net = cp;
			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
			       isascii(*cp) && !isspace(*cp))
				cp++;
			n = *cp;
			*cp = 0;
			if (inet_aton(net, &a)) {
			    _res.sort_list[nsort].addr = a;
			    if (ISSORTMASK(n)) {
				*cp++ = n;
				net = cp;
				while (*cp && *cp != ';' &&
					isascii(*cp) && !isspace(*cp))
				    cp++;
				n = *cp;
				*cp = 0;
				if (inet_aton(net, &a)) {
				    _res.sort_list[nsort].mask = a.s_addr;
				} else {
				    _res.sort_list[nsort].mask = 
					net_mask(_res.sort_list[nsort].addr);
				}
			    } else {
				_res.sort_list[nsort].mask = 
				    net_mask(_res.sort_list[nsort].addr);
			    }
			    nsort++;
			}
			*cp = n;
		    }
		    continue;
		}
#endif
		if (MATCH(buf, "options")) {
		    res_setoptions(buf + sizeof("options") - 1, "conf");
		    continue;
		}
	    }
	    if (nserv > 1) 
		_res.nscount = nserv;
#ifdef RESOLVSORT
	    _res.nsort = nsort;
#endif
	    (void) fclose(fp);
	}
	if (_res.defdname[0] == 0 &&
	    gethostname(buf, sizeof(_res.defdname) - 1) == 0 &&
	    (cp = strchr(buf, '.')) != NULL)
		strcpy(_res.defdname, cp + 1);

	/* find components of local domain that might be searched */
	if (havesearch == 0) {
		pp = _res.dnsrch;
		*pp++ = _res.defdname;
		*pp = NULL;

#ifndef RFC1535
		dots = 0;
		for (cp = _res.defdname; *cp; cp++)
			dots += (*cp == '.');

		cp = _res.defdname;
		while (pp < _res.dnsrch + MAXDFLSRCH) {
			if (dots < LOCALDOMAINPARTS)
				break;
			cp = strchr(cp, '.') + 1;    /* we know there is one */
			*pp++ = cp;
			dots--;
		}
		*pp = NULL;
#ifdef DEBUG
		if (_res.options & RES_DEBUG) {
			printf(";; res_init()... default dnsrch list:\n");
			for (pp = _res.dnsrch; *pp; pp++)
				printf(";;\t%s\n", *pp);
			printf(";;\t..END..\n");
		}
#endif
#endif /* !RFC1535 */
	}

	if (issetugid())
		_res.options |= RES_NOALIASES;
	else if ((cp = getenv("RES_OPTIONS")) != NULL)
		res_setoptions(cp, "env");
	_res.options |= RES_INIT;
	return (0);
}
Example #21
0
File: dhcp.c Project: Bamby4a/lms
void reload(GLOBAL *g, struct dhcp_module *dhcp)
{
	FILE *fh;
	QueryHandle *res, *res1;
	int i, j, m, k=2, gc=0, nc=0, nh=0, n=2;
	char lastif[MAXIFN] = "";
	struct hostcache
	{
		char *name;
		char *mac;
		unsigned long ipaddr;
	} *hosts = NULL;

	struct net *nets = (struct net *) malloc(sizeof(struct net));
	char *netnames = strdup(dhcp->networks);	
	char *netname = strdup(netnames);
    
	struct group *ugps = (struct group *) malloc(sizeof(struct group));
	char *groupnames = strdup(dhcp->customergroups);	
	char *groupname = strdup(groupnames);

	while( n>1 )
	{
    		n = sscanf(netnames, "%s %[._a-zA-Z0-9- ]", netname, netnames);

		if( strlen(netname) )
		{
		        res = g->db_pquery(g->conn, "SELECT name, address, INET_ATON(mask) AS mask  FROM networks WHERE UPPER(name)=UPPER('?')",netname);
			if( g->db_nrows(res) ) 
			{
				nets = (struct net *) realloc(nets, (sizeof(struct net) * (nc+1)));
				nets[nc].name = strdup(g->db_get_data(res,0,"name"));
				nets[nc].address = inet_addr(g->db_get_data(res,0,"address"));
				nc++;
			}
	    		g->db_free(&res);
		}
	}
	free(netname); free(netnames);

	while( k>1 )
	{
		k = sscanf(groupnames, "%s %[._a-zA-Z0-9- ]", groupname, groupnames);

		if( strlen(groupname) )
		{
			res = g->db_pquery(g->conn, "SELECT name, id FROM customergroups WHERE UPPER(name)=UPPER('?')",groupname);
			if( g->db_nrows(res) )
			{
		    		ugps = (struct group *) realloc(ugps, (sizeof(struct group) * (gc+1)));
				ugps[gc].name = strdup(g->db_get_data(res,0,"name"));
				ugps[gc].id = atoi(g->db_get_data(res,0,"id"));
				gc++;
			}
	    		g->db_free(&res);
		}		
	}
	free(groupname); free(groupnames);

	fh = fopen(dhcp->file, "w");
	if(fh)
	{
		res = g->db_query(g->conn, "SELECT name, mac, ipaddr, ipaddr_pub, ownerid FROM vnodes ORDER BY ipaddr");

		for(i=0; i<g->db_nrows(res); i++)
		{
			int ownerid = atoi(g->db_get_data(res,i,"ownerid"));
			char *name = g->db_get_data(res,i,"name");
			char *mac = g->db_get_data(res,i,"mac");
			char *ipaddr = g->db_get_data(res,i,"ipaddr");
			char *ipaddr_pub = g->db_get_data(res,i,"ipaddr_pub");
		
			if(name && mac && ipaddr)
			{
				// groups test
				if(gc)
				{
					if( ownerid==0 ) continue;
					m = gc;
					
					res1 = g->db_pquery(g->conn, "SELECT customergroupid FROM customerassignments WHERE customerid=?", g->db_get_data(res,i,"ownerid"));
					for(k=0; k<g->db_nrows(res1); k++)
					{
						int groupid = atoi(g->db_get_data(res1, k, "customergroupid"));
						for(m=0; m<gc; m++) 
							if(ugps[m].id==groupid) 
								break;
						if(m!=gc) break;
					}
					g->db_free(&res1);
					if( m==gc )
						continue;
				}
				
				hosts = (struct hostcache*) realloc(hosts, sizeof(struct hostcache) * (nh + 1));
				hosts[nh].name = strdup(name);
				hosts[nh].mac = strdup(mac);
				hosts[nh].ipaddr = inet_addr(ipaddr);
				nh++;
				
				if(atoi(ipaddr_pub))
				{
					hosts = (struct hostcache*) realloc(hosts, sizeof(struct hostcache) * (nh + 1));
					hosts[nh].name = g->str_concat(name, "_pub");
					hosts[nh].mac = strdup(mac);
					hosts[nh].ipaddr = inet_addr(ipaddr_pub);
					nh++;
				}
			}
		}
		g->db_free(&res);
	
		fprintf(fh, "%s\n", dhcp->prefix);
		
		res = g->db_query(g->conn, "SELECT inet_ntoa(address) AS address, mask, gateway, dns, dns2, domain, wins, dhcpstart, dhcpend, interface FROM networks ORDER BY interface");

		for(i=0; i<g->db_nrows(res); i++)
		{
			char *s, *d, *d2, *e, *b;
			unsigned long netmask, network, broadcast;
			char iface[MAXIFN] = "";
			
			e = g->db_get_data(res,i,"address");
			d = g->db_get_data(res,i,"mask");
			
			network = inet_addr(e);
			netmask = inet_addr(d);
			
			// networks test
			if(nc)
			{
				for( j=0; j<nc; j++ )
					if( nets[j].address==network )
						break;
				if( j==nc )
					continue;
			}
			
			// shared (interface) network ?
			sscanf(g->db_get_data(res,i,"interface"), "%[a-zA-Z0-9.]", iface);
			
			if( strlen(lastif) && strlen(iface) && strcmp(iface, lastif)!=0 )
			{
				fprintf(fh, "}\n");
			}
			
			if( strlen(iface) && strcmp(iface, lastif)!=0 )
			{
				fprintf(fh, "\nshared-network LMS-%s {\n", iface);
				strcpy(lastif, iface);
			}

			// broadcast address
			broadcast = network | (~netmask);
			b = inet_ntoa(inet_makeaddr(htonl(broadcast), 0));
			
			// start subnet record				
			s = strdup(dhcp->subnetstart);
			g->str_replace(&s, "%m", d);
			g->str_replace(&s, "%a", e);
			g->str_replace(&s, "%b", b);
			fprintf(fh, "%s\n", s);
			free(s); 

			if( (d = g->db_get_data(res,i,"dhcpstart")) && ((e = g->db_get_data(res,i,"dhcpend"))) )
			{
				if( strlen(d) && strlen(e) ) {
					s = strdup(dhcp->rangeline);
					g->str_replace(&s, "%s", d);
					g->str_replace(&s, "%e", e);
					fprintf(fh, "%s\n", s);
					free(s);
				}
			}
			
			if( (d = g->db_get_data(res,i,"gateway")) )
			{
				if( strlen(d) ) {
					s = strdup(dhcp->gateline);
					g->str_replace(&s, "%i", d);
					fprintf(fh, "%s\n", s);
					free(s);
				}
			}

			if( (d = g->db_get_data(res,i,"dns")) )
			{
				if( (d2 = g->db_get_data(res,i,"dns2")) )
				{
					if( strlen(d) && strlen(d2) ) {
						e = (char*) malloc(strlen(d)+strlen(d2)+2);
						sprintf(e,"%s,%s",d,d2);
						s = strdup(dhcp->dnsline);
						g->str_replace(&s, "%i", e);
						fprintf(fh, "%s\n", s);
						free(s); free(e);
					} else if (strlen(d)) {
						s = strdup(dhcp->dnsline);
						g->str_replace(&s, "%i", d);
						fprintf(fh, "%s\n", s);
						free(s);
					}
				}
			}

			if( (d = g->db_get_data(res,i,"domain")) )
			{
				if( strlen(d) ) {
					s = strdup(dhcp->domainline);
					g->str_replace(&s, "%n", d);
					fprintf(fh, "%s\n", s);
					free(s);
				}
			}

			if( (d = g->db_get_data(res,i,"wins")) )
			{
				if( strlen(d) ) {
					s = strdup(dhcp->winsline);
					g->str_replace(&s, "%i", d);
					fprintf(fh, "%s\n", s);
					free(s);
				}
			}
			
			for(j=0; j<nh; j++) 
			{
				char *mac;
				if( (hosts[j].ipaddr & netmask) == network ) {
					for(mac = strtok(hosts[j].mac, ","), m = 0; mac != NULL; mac = strtok(NULL, ","), m++)
					{
						static char name_suffix[12];
						char *name;
						name_suffix[0] = 0;
						if (m > 0)
							sprintf(name_suffix, "-%d", m);
						name = g->str_concat(hosts[j].name, name_suffix);
						s = strdup(dhcp->host);
						g->str_replace(&s, "%i", inet_ntoa(inet_makeaddr(htonl(hosts[j].ipaddr), 0)));
						g->str_replace(&s, "%n", name);
						g->str_replace(&s, "%m", mac);
						fprintf(fh, "%s\n", s);
						free(s);
						free(name);
					}
				}
			}
			
			fprintf(fh, "%s\n", dhcp->subnetend);
		}
		
		if( strlen(lastif) )
			fprintf(fh, "}\n");
		
		fprintf(fh, "%s", dhcp->append);
		
		g->db_free(&res);
		fclose(fh);
		
		system(dhcp->command);
		
		// cleanup
		for(i=0; i<nh; i++) {
			free(hosts[i].name);
			free(hosts[i].mac);
		}
		free(hosts);
#ifdef DEBUG1
		syslog(LOG_INFO,"DEBUG: [%s/dhcp] reloaded", dhcp->base.instance);
#endif
	}
	else
		syslog(LOG_ERR, "[%s/dhcp] Unable to write a temporary file '%s'", dhcp->base.instance, dhcp->file);

	//more cleanup
	for(i=0;i<nc;i++)
		free(nets[i].name);
	free(nets);
	
	for(i=0;i<gc;i++)
		free(ugps[i].name);
	free(ugps);
	
	free(dhcp->networks);
	free(dhcp->customergroups);
	free(dhcp->prefix);
	free(dhcp->append);
	free(dhcp->subnetstart);
	free(dhcp->subnetend);
	free(dhcp->gateline);
	free(dhcp->dnsline);
	free(dhcp->domainline);
	free(dhcp->winsline);
	free(dhcp->rangeline);
	free(dhcp->host);
	free(dhcp->file);
	free(dhcp->command);
}
Example #22
0
/* This function has to be reachable by res_data.c but not publicly. */
int
__res_vinit(res_state statp, int preinit) {
	register FILE *fp;
	register char *cp, **pp;
	register int n;
	char buf[BUFSIZ];
	int nserv = 0;    /* number of nameserver records read from file */
	int haveenv = 0;
	int havesearch = 0;
	int nsort = 0;
	char *net;
	int dots;
	union res_sockaddr_union u[2];
#if defined(ANDROID_CHANGES) && ANDROID_CHANGES
        pid_t mypid = getpid();
        int use_proc_props = 0;
        int found_prop;
	char dnsProperty[PROP_VALUE_MAX];
#endif

        if ((statp->options & RES_INIT) != 0U)
                res_ndestroy(statp);

	if (!preinit) {
		statp->retrans = RES_TIMEOUT;
		statp->retry = RES_DFLRETRY;
		statp->options = RES_DEFAULT;
		statp->id = res_randomid();
	}

	memset(u, 0, sizeof(u));
#ifdef USELOOPBACK
	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
#endif
	u[nserv].sin.sin_family = AF_INET;
	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
#ifdef HAVE_SA_LEN
	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
#endif
	nserv++;
#ifdef HAS_INET6_STRUCTS
#ifdef USELOOPBACK
	u[nserv].sin6.sin6_addr = in6addr_loopback;
#else
	u[nserv].sin6.sin6_addr = in6addr_any;
#endif
	u[nserv].sin6.sin6_family = AF_INET6;
	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
#ifdef HAVE_SA_LEN
	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif
	nserv++;
#endif
	statp->nscount = 0;
	statp->ndots = 1;
	statp->pfcode = 0;
	statp->_vcsock = -1;
	statp->_flags = 0;
	statp->qhook = NULL;
	statp->rhook = NULL;
	statp->_u._ext.nscount = 0;
	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
	if (statp->_u._ext.ext != NULL) {
	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
	}
	statp->nsort = 0;
	res_setservers(statp, u, nserv);

#if 0 /* IGNORE THE ENVIRONMENT */
	/* Allow user to override the local domain definition */
	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		haveenv++;

		/*
		 * Set search list to be blank-separated strings
		 * from rest of env value.  Permits users of LOCALDOMAIN
		 * to still have a search list, and anyone to set the
		 * one that they want to use as an individual (even more
		 * important now that the rfc1535 stuff restricts searches)
		 */
		cp = statp->defdname;
		pp = statp->dnsrch;
		*pp++ = cp;
		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
			if (*cp == '\n')	/* silly backwards compat */
				break;
			else if (*cp == ' ' || *cp == '\t') {
				*cp = 0;
				n = 1;
			} else if (n) {
				*pp++ = cp;
				n = 0;
				havesearch = 1;
			}
		}
		/* null terminate last domain if there are excess */
		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
			cp++;
		*cp = '\0';
		*pp++ = 0;
	}
	if (nserv > 0)
		statp->nscount = nserv;
#endif
#if defined(ANDROID_CHANGES) && defined(PROPERTY_SYSTEM_SUPPORT) /* READ FROM SYSTEM PROPERTIES */
	dns_last_change_counter = _get_dns_change_count();

	nserv = 0;
	for(n = 1; n <= MAX_DNS_PROPERTIES && nserv < MAXNS; n++) {
		char propname[PROP_NAME_MAX];
		char propvalue[PROP_VALUE_MAX];

		struct addrinfo hints, *ai;
		char sbuf[NI_MAXSERV];
		const size_t minsiz = sizeof(statp->_u._ext.ext->nsaddrs[0]);

		/*
		 * Check first for process-specific properties, and if those don't
		 * exist, try the generic properties.
		 */
		found_prop = 0;
		if (n == 1 || use_proc_props) {
			snprintf(propname, sizeof(propname), "%s%d.%d", DNS_PROP_NAME_PREFIX, n, mypid);
			if(__system_property_get(propname, propvalue) < 1) {
				if (use_proc_props) {
					break;
				}
			} else {
				found_prop = 1;
				use_proc_props = 1;
			}
		}
		if (!found_prop) {
			snprintf(propname, sizeof(propname), "%s%d", DNS_PROP_NAME_PREFIX, n);
			if(__system_property_get(propname, propvalue) < 1) {
				break;
			}
		}

		cp = propvalue;

		while (*cp == ' ' || *cp == '\t')
			cp++;
		cp[strcspn(cp, ";# \t\n")] = '\0';
		if ((*cp != '\0') && (*cp != '\n')) {
			memset(&hints, 0, sizeof(hints));
			hints.ai_family = PF_UNSPEC;
			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
			hints.ai_flags = AI_NUMERICHOST;
			sprintf(sbuf, "%u", NAMESERVER_PORT);
			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
			    (size_t)ai->ai_addrlen <= minsiz) {
				if (statp->_u._ext.ext != NULL) {
					memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
					       ai->ai_addr, ai->ai_addrlen);
				}
				if ((size_t)ai->ai_addrlen <=
				    sizeof(statp->nsaddr_list[nserv])) {
					memcpy(&statp->nsaddr_list[nserv],
					       ai->ai_addr, ai->ai_addrlen);
				} else {
					statp->nsaddr_list[nserv].sin_family = 0;
				}
				freeaddrinfo(ai);
				nserv++;
			}
		}
	}

	/* Add the domain search list */
	havesearch = load_domain_search_list(statp);
#else /* !ANDROID_CHANGES - IGNORE resolv.conf in Android */
#define	MATCH(line, name) \
	(!strncmp(line, name, sizeof(name) - 1) && \
	(line[sizeof(name) - 1] == ' ' || \
	 line[sizeof(name) - 1] == '\t'))

	nserv = 0;
	if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
	    /* read the config file */
	    while (fgets(buf, sizeof(buf), fp) != NULL) {
		/* skip comments */
		if (*buf == ';' || *buf == '#')
			continue;
		/* read default domain name */
		if (MATCH(buf, "domain")) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("domain") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
			    *cp = '\0';
		    havesearch = 0;
		    continue;
		}
		/* set search list */
		if (MATCH(buf, "search")) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("search") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
			    *cp = '\0';
		    /*
		     * Set search list to be blank-separated strings
		     * on rest of line.
		     */
		    cp = statp->defdname;
		    pp = statp->dnsrch;
		    *pp++ = cp;
		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
			    if (*cp == ' ' || *cp == '\t') {
				    *cp = 0;
				    n = 1;
			    } else if (n) {
				    *pp++ = cp;
				    n = 0;
			    }
		    }
		    /* null terminate last domain if there are excess */
		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
			    cp++;
		    *cp = '\0';
		    *pp++ = 0;
		    havesearch = 1;
		    continue;
		}
		/* read nameservers to query */
		if (MATCH(buf, "nameserver") && nserv < MAXNS) {
		    struct addrinfo hints, *ai;
		    char sbuf[NI_MAXSERV];
		    const size_t minsiz =
		        sizeof(statp->_u._ext.ext->nsaddrs[0]);

		    cp = buf + sizeof("nameserver") - 1;
		    while (*cp == ' ' || *cp == '\t')
			cp++;
		    cp[strcspn(cp, ";# \t\n")] = '\0';
		    if ((*cp != '\0') && (*cp != '\n')) {
			memset(&hints, 0, sizeof(hints));
			hints.ai_family = PF_UNSPEC;
			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
			hints.ai_flags = AI_NUMERICHOST;
			sprintf(sbuf, "%u", NAMESERVER_PORT);
			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
			    ai->ai_addrlen <= minsiz) {
			    if (statp->_u._ext.ext != NULL) {
				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
				    ai->ai_addr, ai->ai_addrlen);
			    }
			    if (ai->ai_addrlen <=
			        sizeof(statp->nsaddr_list[nserv])) {
				memcpy(&statp->nsaddr_list[nserv],
				    ai->ai_addr, ai->ai_addrlen);
			    } else
				statp->nsaddr_list[nserv].sin_family = 0;
			    freeaddrinfo(ai);
			    nserv++;
			}
		    }
		    continue;
		}
		if (MATCH(buf, "sortlist")) {
		    struct in_addr a;

		    cp = buf + sizeof("sortlist") - 1;
		    while (nsort < MAXRESOLVSORT) {
			while (*cp == ' ' || *cp == '\t')
			    cp++;
			if (*cp == '\0' || *cp == '\n' || *cp == ';')
			    break;
			net = cp;
			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
			       isascii(*cp) && !isspace((unsigned char)*cp))
				cp++;
			n = *cp;
			*cp = 0;
			if (inet_aton(net, &a)) {
			    statp->sort_list[nsort].addr = a;
			    if (ISSORTMASK(n)) {
				*cp++ = n;
				net = cp;
				while (*cp && *cp != ';' &&
					isascii(*cp) &&
					!isspace((unsigned char)*cp))
				    cp++;
				n = *cp;
				*cp = 0;
				if (inet_aton(net, &a)) {
				    statp->sort_list[nsort].mask = a.s_addr;
				} else {
				    statp->sort_list[nsort].mask =
					net_mask(statp->sort_list[nsort].addr);
				}
			    } else {
				statp->sort_list[nsort].mask =
				    net_mask(statp->sort_list[nsort].addr);
			    }
			    nsort++;
			}
			*cp = n;
		    }
		    continue;
		}
		if (MATCH(buf, "options")) {
		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
		    continue;
		}
	    }
	    if (nserv > 0)
		statp->nscount = nserv;
	    statp->nsort = nsort;
	    (void) fclose(fp);
	}
#endif /* !ANDROID_CHANGES */
/*
 * Last chance to get a nameserver.  This should not normally
 * be necessary
 */
#ifdef NO_RESOLV_CONF
	if(nserv == 0)
		nserv = get_nameservers(statp);
#endif

	if (statp->defdname[0] == 0 &&
	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
	    (cp = strchr(buf, '.')) != NULL)
		strcpy(statp->defdname, cp + 1);

	/* find components of local domain that might be searched */
	if (havesearch == 0) {
		pp = statp->dnsrch;
		*pp++ = statp->defdname;
		*pp = NULL;

		dots = 0;
		for (cp = statp->defdname; *cp; cp++)
			dots += (*cp == '.');

		cp = statp->defdname;
		while (pp < statp->dnsrch + MAXDFLSRCH) {
			if (dots < LOCALDOMAINPARTS)
				break;
			cp = strchr(cp, '.') + 1;    /* we know there is one */
			*pp++ = cp;
			dots--;
		}
		*pp = NULL;
#ifdef DEBUG
		if (statp->options & RES_DEBUG) {
			printf(";; res_init()... default dnsrch list:\n");
			for (pp = statp->dnsrch; *pp; pp++)
				printf(";;\t%s\n", *pp);
			printf(";;\t..END..\n");
		}
#endif
	}

	if ((cp = getenv("RES_OPTIONS")) != NULL)
		res_setoptions(statp, cp, "env");
	if (nserv > 0) {
		statp->nscount = nserv;
		statp->options |= RES_INIT;
	}
	return (0);
}
Example #23
0
int
res_vinit_from_file(res_state statp, int preinit, char *resconf_file)
{
	register FILE *fp;
	register char *cp, **pp;
	register int n;
	char buf[BUFSIZ];
	int nserv = 0;    /* number of nameserver records read from file */
	int haveenv = 0;
	int havesearch = 0;
	int isresdefault = 0;
	unsigned short port; /* HOST BYTE ORDER */
	unsigned int i, total_timeout;
#ifdef RESOLVSORT
	int nsort = 0;
	char *net;
#endif
	int dots;

	port = NS_DEFAULTPORT;
	total_timeout = 0;

	if (!preinit)
	{
		statp->retrans = RES_TIMEOUT;
		statp->retry = RES_DFLRETRY;
		statp->options = RES_DEFAULT;
		statp->id = res_randomid();
	}

	if ((statp->options & RES_INIT) != 0) res_ndestroy(statp);

	/* N.B. we allocate a new statp->_u._ext.ext below */

	/* make sure version is set */
	statp->_pad = 9;
	
	statp->nscount = 0;
	
	if ((resconf_file == NULL) || (!strcmp(resconf_file, _PATH_RESCONF)))
	{
		isresdefault = 1;
		
#ifdef USELOOPBACK
		statp->nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
		statp->nsaddr.sin_addr.s_addr = INADDR_ANY;
#endif
		statp->nsaddr.sin_family = AF_INET;
		statp->nsaddr.sin_port = htons(NS_DEFAULTPORT);
#ifdef HAVE_SA_LEN
		statp->nsaddr.sin_len = sizeof(struct sockaddr_in);
#endif
		statp->nscount = 1;

		/*
		 * Force loopback queries to use TCP
		 * so we don't take a timeout if named isn't running.
		 */
		statp->options |= RES_USEVC;
	}
	
	statp->ndots = 1;
	statp->pfcode = 0;
	statp->_vcsock = -1;
	statp->_flags = 0;
	statp->qhook = NULL;
	statp->rhook = NULL;

	statp->_u._ext.nscount = 0;
	statp->_u._ext.ext = (struct __res_state_ext *)calloc(1, sizeof(struct __res_state_ext));
	
	if (statp->_u._ext.ext != NULL)
	{
		memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
		strcpy(statp->_u._ext.ext->bsuffix, "ip6.arpa");
	}
	
#ifdef RESOLVSORT
	statp->nsort = 0;
#endif
	
	/* Allow user to override the local domain definition */
	cp = getenv("LOCALDOMAIN");
	if ((cp != NULL) && (isresdefault != 0))
	{
		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
		haveenv++;

		/*
		 * Set search list to be blank-separated strings
		 * from rest of env value.  Permits users of LOCALDOMAIN
		 * to still have a search list, and anyone to set the
		 * one that they want to use as an individual (even more
		 * important now that the rfc1535 stuff restricts searches)
		 */
		cp = statp->defdname;
		pp = statp->dnsrch;
		*pp++ = cp;
		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++)
		{
			if (*cp == '\n') break;
			else if (*cp == ' ' || *cp == '\t')
			{
				*cp = 0;
				n = 1;
			}
			else if (n != 0)
			{
				*pp++ = cp;
				n = 0;
				havesearch = 1;
			}
		}

		/* null terminate last domain if there are excess */
		while ((*cp != '\0') && (*cp != ' ') && (*cp != '\t') && (*cp != '\n')) cp++;
		*cp = '\0';
		*pp++ = 0;
	}

#define	MATCH(line, name) \
	(!strncmp(line, name, sizeof(name) - 1) && \
	(line[sizeof(name) - 1] == ' ' || \
	 line[sizeof(name) - 1] == '\t'))

	if (resconf_file == NULL) resconf_file = _PATH_RESCONF;

	if ((fp = fopen(resconf_file, "r")) != NULL)
	{
		/* look for port number */
		while (fgets(buf, sizeof(buf), fp) != NULL)
		{
			/* skip comments */
			if (*buf == ';' || *buf == '#') continue;

			/* read default domain name */
			if (MATCH(buf, "port"))
			{
				cp = buf + sizeof("port") - 1;
				while (*cp == ' ' || *cp == '\t') cp++;
				if ((*cp == '\0') || (*cp == '\n')) continue;
				port = atoi(cp);
				break;
			}
		}
		fclose(fp);
	}

	if ((fp = fopen(resconf_file, "r")) != NULL)
	{
	    /* read the config file */
	    while (fgets(buf, sizeof(buf), fp) != NULL)
		{
			/* skip comments */
			if ((*buf == ';') || (*buf == '#')) continue;
			
			/* read default domain name */
			if (MATCH(buf, "domain"))
			{
				/* skip if have from environ */
				if (haveenv) continue;

				cp = buf + sizeof("domain") - 1;
				while ((*cp == ' ') || (*cp == '\t')) cp++;
				if ((*cp == '\0') || (*cp == '\n')) continue;

				strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
				statp->defdname[sizeof(statp->defdname) - 1] = '\0';
				cp = strpbrk(statp->defdname, " \t\n");
				if (cp != NULL) *cp = '\0';
				havesearch = 0;
				continue;
			}

			/* set search list */
			if (MATCH(buf, "search"))
			{
				/* skip if have from environ */
			    if (haveenv) continue;

			    cp = buf + sizeof("search") - 1;
			    while ((*cp == ' ') || (*cp == '\t')) cp++;
			    if ((*cp == '\0') || (*cp == '\n')) continue;
				
			    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
			    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
				cp = strchr(statp->defdname, '\n');
			    if (cp != NULL) *cp = '\0';

			    /*
			     * Set search list to be blank-separated strings
			     * on rest of line.
			     */
			    cp = statp->defdname;
			    pp = statp->dnsrch;
			    *pp++ = cp;
			    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++)
				{
				    if ((*cp == ' ') || (*cp == '\t'))
					{
					    *cp = 0;
					    n = 1;
				    }
					else if (n != 0)
					{
					    *pp++ = cp;
					    n = 0;
				    }
			    }

			    /* null terminate last domain if there are excess */
			    while ((*cp != '\0') && (*cp != ' ') && (*cp != '\t')) cp++;
			    *cp = '\0';
			    *pp++ = 0;
			    havesearch = 1;
			    continue;
			}

			/* read nameservers to query */
			if (MATCH(buf, "nameserver") && (nserv < MAXNS))
			{
#ifndef __APPLE__
			    struct addrinfo hints, *ai;
#endif
				int dotcount, semicount, status;
				struct in_addr addr4;
				struct sockaddr_in sin4;
				struct in6_addr addr6;
				struct sockaddr_in6 sin6;
				unsigned short aport; /* HOST BYTE ORDER */
				char *lastdot, *checkp;
			    char sbuf[NI_MAXSERV];
#ifndef __APPLE__
			    const size_t minsiz = sizeof(statp->_u._ext.ext->nsaddrs[0]);
#endif

			    cp = buf + sizeof("nameserver") - 1;
			    while ((*cp == ' ') || (*cp == '\t')) cp++;
			    cp[strcspn(cp, ";# \t\n")] = '\0';
			    if ((*cp != '\0') && (*cp != '\n'))
				{
#ifndef __APPLE__
					memset(&hints, 0, sizeof(hints));
					hints.ai_family = PF_UNSPEC;
					hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
					hints.ai_flags = AI_NUMERICHOST;
#endif
					dotcount = 0;
					semicount = 0;
					lastdot = NULL;
					aport = port;

					for (checkp = cp; *checkp != '\0'; checkp++)
					{
						if (*checkp == ':') semicount++;
						else if (*checkp == '.')
						{
							dotcount++;
							lastdot = checkp;
						}
					}

					if ((dotcount == 4) || ((semicount > 0) && (lastdot != NULL)))
					{
						aport = atoi(lastdot + 1);
						if (aport == 0) aport = port;
						*lastdot = '\0';
					}
					
					sprintf(sbuf, "%u", aport);

#ifdef __APPLE__
					memset(&addr4, 0, sizeof(struct in_addr));
					memset(&sin4, 0, sizeof(struct sockaddr_in));

					memset(&addr6, 0, sizeof(struct in6_addr));
					memset(&sin6, 0, sizeof(struct sockaddr_in6));

					status = inet_pton(AF_INET6, cp, &addr6);
					if (status == 1)
					{
						sin6.sin6_addr = addr6;
						sin6.sin6_family = AF_INET6;
						sin6.sin6_port = htons(aport);
						sin6.sin6_len = sizeof(struct sockaddr_in6);
						if (statp->_u._ext.ext != NULL)
						{
							memcpy(&statp->_u._ext.ext->nsaddrs[nserv], &sin6, sizeof(struct sockaddr_in6));
						}
						statp->nsaddr_list[nserv].sin_family = 0;
						nserv++;
					}
					else
					{
						status = inet_pton(AF_INET, cp, &addr4);
						if (status == 1)
						{
							sin4.sin_addr = addr4;
							sin4.sin_family = AF_INET;
							sin4.sin_port = htons(port);
							sin4.sin_len = sizeof(struct sockaddr_in);
							if (statp->_u._ext.ext != NULL)
							{
								memcpy(&statp->_u._ext.ext->nsaddrs[nserv], &sin4, sizeof(struct sockaddr_in));
							}
							memcpy(&statp->nsaddr_list[nserv], &sin4, sizeof(struct sockaddr_in));
							nserv++;
						}
             	   }

					
#else
					if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 && ai->ai_addrlen <= minsiz)
					{
						if (statp->_u._ext.ext != NULL)
						{
							memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
						}

						if (ai->ai_addrlen <= sizeof(statp->nsaddr_list[nserv]))
						{
							memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
						}
						else
						{
							statp->nsaddr_list[nserv].sin_family = 0;
						}

						freeaddrinfo(ai);
						nserv++;
					}
#endif
				}

				continue;
			}

#ifdef RESOLVSORT
			if (MATCH(buf, "sortlist"))
			{
			    struct in_addr a;

			    cp = buf + sizeof("sortlist") - 1;
			    while (nsort < MAXRESOLVSORT)
				{
					while ((*cp == ' ') || (*cp == '\t')) cp++;
					if ((*cp == '\0') || (*cp == '\n') || (*cp == ';')) break;

					net = cp;
					while (*cp && !ISSORTMASK(*cp) && (*cp != ';') && isascii(*cp) && !isspace((unsigned char)*cp)) cp++;
					n = *cp;
					*cp = 0;
					if (inet_aton(net, &a))
					{
						statp->sort_list[nsort].addr = a;
						if (ISSORTMASK(n))
						{
							*cp++ = n;
							net = cp;
							while (*cp && (*cp != ';') && isascii(*cp) && !isspace((unsigned char)*cp)) cp++;
							n = *cp;
							*cp = 0;
							if (inet_aton(net, &a))
							{
								statp->sort_list[nsort].mask = a.s_addr;
							}
							else
							{
								statp->sort_list[nsort].mask = net_mask(statp->sort_list[nsort].addr);
							}
						}
						else
						{
							statp->sort_list[nsort].mask = net_mask(statp->sort_list[nsort].addr);
						}
						nsort++;
					}

					*cp = n;
				}

				continue;
			}
#endif

			if (MATCH(buf, "options"))
			{
			    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
			    continue;
			}

			if (MATCH(buf, "timeout"))
			{
				cp = buf + sizeof("timeout") - 1;
				while (*cp == ' ' || *cp == '\t') cp++;
				if ((*cp == '\0') || (*cp == '\n')) continue;
				i = atoi(cp);
				if (i > RES_MAXRETRANS) i = RES_MAXRETRANS;
				total_timeout = i;
				continue;
			}
		}

		if (nserv > 1) statp->nscount = nserv;
#ifdef RESOLVSORT
		statp->nsort = nsort;
#endif
		fclose(fp);
	}

	/*
	 * Last chance to get a nameserver.  This should not normally
	 * be necessary
	 */
#ifdef NO_RESOLV_CONF
	if(nserv == 0) nserv = get_nameservers(statp);
#endif

	if (isresdefault != 0)
	{
		if ((statp->defdname[0] == 0) && (gethostname(buf, sizeof(statp->defdname) - 1) == 0) && ((cp = strchr(buf, '.')) != NULL))
		{
			strcpy(statp->defdname, cp + 1);
		}
	}

	/* find components of local domain that might be searched */
	if (havesearch == 0)
	{
		pp = statp->dnsrch;
		*pp++ = statp->defdname;
		*pp = NULL;

		dots = 0;
		for (cp = statp->defdname; *cp; cp++)
		{
			if (*cp == '.') dots++;
		}

		/* Back up over any trailing dots and cut them out of the name */
		for (cp--; (cp >= statp->defdname) && (*cp == '.'); cp--)
		{
			*cp = '\0';
			dots--;
		}

		cp = statp->defdname;
		while (pp < statp->dnsrch + MAXDFLSRCH)
		{
			if (dots < LOCALDOMAINPARTS) break;

			/* we know there is a dot */
			cp = strchr(cp, '.') + 1;   
			*pp++ = cp;
			dots--;
		}

		*pp = NULL;
#ifdef DEBUG
		if (statp->options & RES_DEBUG)
		{
			printf(";; res_init()... default dnsrch list:\n");
			for (pp = statp->dnsrch; *pp; pp++) printf(";;\t%s\n", *pp);
			printf(";;\t..END..\n");
		}
#endif
	}

	cp = getenv("RES_OPTIONS");
	if ((cp != NULL) && (isresdefault != 0))
	{
		res_setoptions(statp, cp, "env");
	}

#ifdef __APPLE__
	/*
	 * Post processing to set the timeout value.
	 */
	if (total_timeout != 0)
	{
		/* Timeout was set with a "timeout" line in the file */
		statp->retrans = total_timeout;
	}
	else
	{
		/*
		 * Timeout is default, or was set with "options timeout:"
		 * This is a per-select timeout value.  Calculate total timeout
		 * and set statp->restrans which we (Apple) use to indicate
		 * total time allowed for a query to be resolved.
		 */
		total_timeout = statp->retrans * (statp->retry + 1) * statp->nscount;
		statp->retrans = total_timeout;
	}
#endif

	statp->options |= RES_INIT;
	return (0);
}
Example #24
0
void ReadNetworksFile (const char *fname)
{
  static BOOL been_here = FALSE;

  if (!fname || !*fname)
     return;

  if (been_here)  /* loading multiple network files */
  {
    free (networkFname);
    fclose (networkFile);
    networkFile = NULL;
  }

  networkFname = strdup (fname);
  if (!networkFname)
     return;

  setnetent (1);
  if (!networkFile)
     return;

  been_here = TRUE;

  while (1)
  {
    struct netent  *n = getnetent();
    struct _netent *n2;
    int    i;

    if (!n)
       break;

    n2 = (struct _netent*) calloc (sizeof(*n2), 1);
    if (!n2)
    {
      outs (networkFname);
      outsnl (_LANG(" too big!"));
      break;
    }

    for (i = 0; n->n_aliases[i]; i++)
        n2->n_aliases[i] = strdup (n->n_aliases[i]);
    n2->n_net      = n->n_net;
    n2->n_addrtype = n->n_addrtype;
    n2->n_name     = strdup (n->n_name);
    if (!n2->n_name)
       break;
    n2->n_next = network0;
    network0   = n2;
  }
  rewind (networkFile);
  RUNDOWN_ADD (endnetent, 251);

#if 0  /* test */
  {
    struct _netent *n;

    printf ("\n%s entries:\n", networkFname);

    for (n = network0; n; n = n->n_next)
    {
      int i;
      printf ("net %-15.15s name %-10.10s  Aliases:",
              inet_ntoa(inet_makeaddr(n->n_net,0)), n->n_name);
      for (i = 0; n->n_aliases[i]; i++)
          printf (" %s,", n->n_aliases[i]);
      puts ("");
    }
    fflush (stdout);
  }
#endif
}
Example #25
0
/*
 * Set up default settings.  If the configuration file exist, the values
 * there will have precedence.  Otherwise, the server address is set to
 * INADDR_ANY and the default domain name comes from the gethostname().
 *
 * The configuration file should only be used if you want to redefine your
 * domain or run without a server on your machine.
 *
 * Return 0 if completes successfully, -1 on error
 */
res_init()
{
	register FILE *fp;
	register char *cp, **pp;
	register int n;
	char buf[BUFSIZ];
	int nserv = 0;    /* number of nameserver records read from file */
	int haveenv = 0;
	int havesearch = 0;

#ifdef USELOOPBACK
	_res.nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
#else
	_res.nsaddr.sin_addr.s_addr = INADDR_ANY;
#endif
	_res.nsaddr.sin_family = AF_INET;
	_res.nsaddr.sin_port = htons(NAMESERVER_PORT);
	_res.nscount = 1;
	_res.pfcode = 0;

	/* Allow user to override the local domain definition */
	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
		(void)strncpy(_res.defdname, cp, sizeof(_res.defdname));
		if ((cp = strpbrk(_res.defdname, " \t\n")) != NULL)
			*cp = '\0';
		haveenv++;
	}

	if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
	    /* read the config file */
	    while (fgets(buf, sizeof(buf), fp) != NULL) {
		/* skip comments */
		if ((*buf == ';') || (*buf == '#'))
			continue;
		/* read default domain name */
		if (!strncmp(buf, "domain", sizeof("domain") - 1)) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("domain") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    (void)strncpy(_res.defdname, cp,
				  sizeof(_res.defdname) - 1);
		    if ((cp = strpbrk(_res.defdname, " \t\n")) != NULL)
			    *cp = '\0';
		    havesearch = 0;
		    continue;
		}
		/* set search list */
		if (!strncmp(buf, "search", sizeof("search") - 1)) {
		    if (haveenv)	/* skip if have from environ */
			    continue;
		    cp = buf + sizeof("search") - 1;
		    while (*cp == ' ' || *cp == '\t')
			    cp++;
		    if ((*cp == '\0') || (*cp == '\n'))
			    continue;
		    (void)strncpy(_res.defdname, cp,
				  sizeof(_res.defdname) - 1);
		    if ((cp = strchr(_res.defdname, '\n')) != NULL)
			    *cp = '\0';
		    /*
		     * Set search list to be blank-separated strings
		     * on rest of line.
		     */
		    cp = _res.defdname;
		    pp = _res.dnsrch;
		    *pp++ = cp;
		    for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
			    if (*cp == ' ' || *cp == '\t') {
				    *cp = 0;
				    n = 1;
			    } else if (n) {
				    *pp++ = cp;
				    n = 0;
			    }
		    }
		    /* null terminate last domain if there are excess */
		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
			    cp++;
		    *cp = '\0';
		    *pp++ = 0;
		    havesearch = 1;
		    continue;
		}
		/* read nameservers to query */
		if (!strncmp(buf, "nameserver", sizeof("nameserver") - 1) &&
		   nserv < MAXNS) {
		   struct in_addr a;

		    cp = buf + sizeof("nameserver") - 1;
		    while (*cp == ' ' || *cp == '\t')
			cp++;
		    if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
			_res.nsaddr_list[nserv].sin_addr = a;
			_res.nsaddr_list[nserv].sin_family = AF_INET;
			_res.nsaddr_list[nserv].sin_port =
				htons(NAMESERVER_PORT);
			nserv++;
		    }
		    continue;
		}
	    }
	    if (nserv > 1) 
		_res.nscount = nserv;
	    (void) fclose(fp);
	}
	if (_res.defdname[0] == 0) {
		if (gethostname(buf, sizeof(_res.defdname)) == 0 &&
		   (cp = strchr(buf, '.')))
			(void)strcpy(_res.defdname, cp + 1);
	}

	/* find components of local domain that might be searched */
	if (havesearch == 0) {
		pp = _res.dnsrch;
		*pp++ = _res.defdname;
		for (cp = _res.defdname, n = 0; *cp; cp++)
			if (*cp == '.')
				n++;
		cp = _res.defdname;
		for (; n >= LOCALDOMAINPARTS && pp < _res.dnsrch + MAXDFLSRCH;
		    n--) {
			cp = strchr(cp, '.');
			*pp++ = ++cp;
		}
		*pp++ = 0;
	}
	_res.options |= RES_INIT;
	return (0);
}
Example #26
0
void reload(GLOBAL *g, struct ethers_module *fm)
{
	FILE *fh;
	QueryHandle *res, *res1;
	int i, j, m, k=2, gc=0, nc=0, n=2;

	struct net *nets = (struct net *) malloc(sizeof(struct net));
	char *netnames = strdup(fm->networks);	
	char *netname = strdup(netnames);
    
	struct group *ugps = (struct group *) malloc(sizeof(struct group));
	char *groupnames = strdup(fm->customergroups);	
	char *groupname = strdup(groupnames);

	while( n>1 )
	{
    		n = sscanf(netnames, "%s %[._a-zA-Z0-9- ]", netname, netnames);

		if( strlen(netname) )
		{
		        res = g->db->pquery(g->db->conn, "SELECT name, address, INET_ATON(mask) AS mask  FROM networks WHERE UPPER(name)=UPPER('?')", netname);

			if( g->db->nrows(res) ) 
			{
				nets = (struct net *) realloc(nets, (sizeof(struct net) * (nc+1)));
				nets[nc].name = strdup(g->db->get_data(res,0,"name"));
				nets[nc].address = inet_addr(g->db->get_data(res,0,"address"));
				nets[nc].mask = inet_addr(g->db->get_data(res,0,"mask"));
				nc++;
			}
	    		g->db->free(&res);
		}				
	}
	free(netname); free(netnames);

	if( !nc )
	{
		res = g->db->query(g->db->conn, "SELECT name, address, INET_ATON(mask) AS mask FROM networks");
		for(nc=0; nc<g->db->nrows(res); nc++)
		{
			nets = (struct net*) realloc(nets, (sizeof(struct net) * (nc+1)));
			nets[nc].name = strdup(g->db->get_data(res,nc,"name"));
			nets[nc].address = inet_addr(g->db->get_data(res,nc,"address"));
			nets[nc].mask = inet_addr(g->db->get_data(res,nc,"mask"));
		}
		g->db->free(&res);
	}

	while( k>1 )
	{
		k = sscanf(groupnames, "%s %[._a-zA-Z0-9- ]", groupname, groupnames);

		if( strlen(groupname) )
		{
			res = g->db->pquery(g->db->conn, "SELECT name, id FROM customergroups WHERE UPPER(name)=UPPER('?')", groupname);

			if( g->db->nrows(res) )
			{
		    		ugps = (struct group *) realloc(ugps, (sizeof(struct group) * (gc+1)));
				ugps[gc].name = strdup(g->db->get_data(res,0,"name"));
				ugps[gc].id = atoi(g->db->get_data(res,0,"id"));
				gc++;
			}
    			g->db->free(&res);
		}		
	}		
	free(groupname); free(groupnames);

	fh = fopen(fm->file, "w");
	if(fh)
	{
		res = g->db->query(g->db->conn, "SELECT mac, ipaddr, access, ownerid FROM vmacs ORDER BY ipaddr");
	
		for(i=0; i<g->db->nrows(res); i++)
		{
			unsigned long inet = inet_addr(g->db->get_data(res,i,"ipaddr"));
			int ownerid = atoi(g->db->get_data(res,i,"ownerid"));
				
			// networks test
			for(j=0; j<nc; j++)
				if(nets[j].address == (inet & nets[j].mask)) 
					break;
			
			// groups test
			m = gc;
			if(gc && ownerid)
			{
				res1 = g->db->pquery(g->db->conn, "SELECT customergroupid FROM customerassignments WHERE customerid=?", g->db->get_data(res,i,"ownerid"));
				for(k=0; k<g->db->nrows(res1); k++)
				{
					int groupid = atoi(g->db->get_data(res1, k, "customergroupid"));
					for(m=0; m<gc; m++) 
						if(ugps[m].id==groupid) 
							break;
					if( m!=gc ) break;
				}
				g->db->free(&res1);
			}
				
			if( j!=nc && (gc==0 || m!=gc) )
			{
				if( atoi(g->db->get_data(res,i,"access")) )
					fprintf(fh, "%s\t%s\n", g->db->get_data(res,i,"mac"), inet_ntoa(inet_makeaddr(htonl(inet), 0)));
				else
					if( fm->dummy_macs )
						fprintf(fh, "00:00:00:00:00:00\t%s\n", inet_ntoa(inet_makeaddr(htonl(inet), 0)));	
			}
		}

    		g->db->free(&res);
		fclose(fh);
		system(fm->command);
#ifdef DEBUG1
		syslog(LOG_INFO, "DEBUG: [%s/ethers] reloaded", fm->base.instance);
#endif
	}
	else
		syslog(LOG_ERR, "[%s/ethers] Unable to write a temporary file '%s'", fm->base.instance, fm->file);

	for(i=0;i<nc;i++)
		free(nets[i].name);
	free(nets);
	
	for(i=0;i<gc;i++)
		free(ugps[i].name);
	free(ugps);
	
	free(fm->networks);
	free(fm->customergroups);
	free(fm->file);
	free(fm->command);
}
Example #27
0
void rip_input(struct sockaddr *sa, int size)
{
	struct sockaddr_in *from = (struct sockaddr_in *)sa;
	register struct rip *msg = (struct rip *)packet;
	register struct netinfo *n;
	const char *name;
	int lna, net, subnet;
	struct hostent *hp;
	struct netent *np;

	if (msg->rip_cmd != RIPCMD_RESPONSE)
		return;
	printf("%d bytes from ", size);
	if (nflag)
		printf("%s:\n", inet_ntoa(from->sin_addr));
	else {
		hp = gethostbyaddr((char *)&from->sin_addr,
		    sizeof (struct in_addr), AF_INET);
		name = hp == 0 ? "???" : hp->h_name;
		printf("%s(%s):\n", name, inet_ntoa(from->sin_addr));
	}
	size -= sizeof (int);
	n = msg->rip_nets;
	while (size > 0) {
	    if (size < (int)sizeof (struct netinfo))
		    break;
	    if (msg->rip_vers > 0) {
		    n->rip_dst.sa_family =
			    ntohs(n->rip_dst.sa_family);
		    n->rip_metric = ntohl(n->rip_metric);
	    }
	    switch (n->rip_dst.sa_family) {

	    case AF_INET:
		{ register struct sockaddr_in *sin;

		sin = (struct sockaddr_in *)&n->rip_dst;
		net = inet_netof(sin->sin_addr);
		subnet = inet_subnetof(sin->sin_addr);
		lna = inet_lnaof(sin->sin_addr);
		name = "???";
		if (!nflag) {
			if (sin->sin_addr.s_addr == 0)
				name = "default";
			else if (lna == INADDR_ANY) {
				np = getnetbyaddr(net, AF_INET);
				if (np)
					name = np->n_name;
				else if (net == 0)
					name = "default";
			} else if ((lna & 0xff) == 0 &&
			    (np = getnetbyaddr(subnet, AF_INET))) {
				struct in_addr subnaddr;

				subnaddr = inet_makeaddr(subnet, INADDR_ANY);
				if (memcmp(&sin->sin_addr, &subnaddr,
				    sizeof(subnaddr)) == 0)
					name = np->n_name;
				else
					goto host;
			} else {
	host:
				hp = gethostbyaddr((char *)&sin->sin_addr,
				    sizeof (struct in_addr), AF_INET);
				if (hp)
					name = hp->h_name;
			}
			printf("\t%-17s metric %2d name %s\n",
				inet_ntoa(sin->sin_addr), n->rip_metric, name);
		} else
			printf("\t%-17s metric %2d\n",
				inet_ntoa(sin->sin_addr), n->rip_metric);
		break;
		}

	    default:
		{ u_short *p = (u_short *)n->rip_dst.sa_data;

		printf("\t(af %d) %x %x %x %x %x %x %x, metric %d\n",
		    p[0], p[1], p[2], p[3], p[4], p[5], p[6],
		    n->rip_dst.sa_family,
		    n->rip_metric);
		break;
		}
			
	    }
	    size -= sizeof (struct netinfo), n++;
	}
}
extern int
main(int argc, char** argv)
{
  int retval = 0;
  int arg = 0;
  struct in_addr addr;
  struct in_addr addr2;
  char* rhost = NULL;
  int loops = -1;


  if (argc < 3) {
      printf("usage: test_cl_hostname_list <DEBUGLEVEL> hostnames\n");
      exit(1);
  }

  printf("commlib setup ...\n");
  retval = cl_com_setup_commlib(CL_NO_THREAD, (cl_log_t)atoi(argv[1]), NULL);
  printf("%s\n\n",cl_get_error_text(retval));

  printf("reslovling host addr 129.157.141.10 ...\n");
  addr = inet_makeaddr(129*256+157,141*256+10);
  printf("ip addr: %s\n",inet_ntoa(addr));  /* inet_ntoa() is not MT save */
  addr2 = inet_makeaddr(192*256+168,11*256+1);
  printf("ip addr2: %s\n",inet_ntoa(addr2));  /* inet_ntoa() is not MT save */



  while ((loops--) != 0) { 
  arg = 2;
  printf("loop\n\n\n");
     while( argv[arg] != NULL) {
        printf("resolving host \"%s\" ...\n", argv[arg]);
        retval = cl_com_cached_gethostbyname(argv[arg],&rhost,NULL,NULL,NULL);
        printf("%s\n",cl_get_error_text(retval));
   
        if (rhost != NULL) {
           printf(" -> host resolved as \"%s\"\n", rhost );
           free(rhost);
           rhost = NULL;
        }
   
        printf("cl_com_gethostbyaddr ... %s\n", inet_ntoa(addr)); /* inet_ntoa() is not MT save */

        retval = cl_com_cached_gethostbyaddr(&addr, &rhost, NULL, NULL);
        printf("%s\n",cl_get_error_text(retval));
   
        if (retval == CL_RETVAL_OK) {
           printf(" -> host name is \"%s\"\n", rhost);
        }
        free(rhost);
        rhost = NULL;
   
        printf("cl_com_gethostbyaddr ... %s\n",inet_ntoa(addr2) ); /* inet_ntoa() is not MT save */

   
        retval = cl_com_cached_gethostbyaddr(&addr2, &rhost, NULL, NULL);
        printf("%s\n",cl_get_error_text(retval));
   
        if (retval == CL_RETVAL_OK) {
           printf(" -> host name is \"%s\"\n", rhost);
        }
        free(rhost);
        rhost = NULL;
   
        printf("***********************************************************\n");
        arg++;
     }
     sleep(1); 
  }
  
  
  printf("commlib cleanup ...\n");
  retval = cl_com_cleanup_commlib();
  printf("%s\n\n",cl_get_error_text(retval));


  printf("main done\n");
  return 0;
}
Example #29
-1
void addrule(GLOBAL *g, FILE *fh, char *rule, struct host h)
{
	unsigned long inet_pub = inet_addr(h.ip_pub);
	char *s = strdup(rule);

	g->str_replace(&s, "%customer", h.customer);
	g->str_replace(&s, "%cid", h.cid);
	g->str_replace(&s, "%maskpub", inet_pub ? inet_ntoa(inet_makeaddr(htonl(h.pubnet.mask),0)) : "");
	g->str_replace(&s, "%prefixpub", inet_pub ? h.pubnet.prefix : "");
	g->str_replace(&s, "%addrpub", inet_pub ? inet_ntoa(inet_makeaddr(htonl(h.pubnet.address),0)) : "");
	g->str_replace(&s, "%domainpub", inet_pub ? h.pubnet.domain : "");
	g->str_replace(&s, "%netpub", inet_pub ? h.pubnet.name : "");
	g->str_replace(&s, "%ifpub", inet_pub ? h.pubnet.interface : "");
	g->str_replace(&s, "%gwpub", inet_pub ? h.pubnet.gateway : "");
	g->str_replace(&s, "%dns2pub", inet_pub ? h.pubnet.dns2 : "");
	g->str_replace(&s, "%dnspub", inet_pub ? h.pubnet.dns : "");
	g->str_replace(&s, "%winspub", inet_pub ? h.pubnet.wins : "");
	g->str_replace(&s, "%dhcpspub", inet_pub ? h.pubnet.dhcpstart : "");
	g->str_replace(&s, "%dhcpepub", inet_pub ? h.pubnet.dhcpend : "");
	g->str_replace(&s, "%prefix", h.net.prefix);
	g->str_replace(&s, "%mask", inet_ntoa(inet_makeaddr(htonl(h.net.mask),0)));
	g->str_replace(&s, "%addr", inet_ntoa(inet_makeaddr(htonl(h.net.address),0)));
	g->str_replace(&s, "%domain", h.net.domain);
	g->str_replace(&s, "%net", h.net.name);
	g->str_replace(&s, "%if", h.net.interface);
	g->str_replace(&s, "%gw", h.net.gateway);
	g->str_replace(&s, "%dns2", h.net.dns2);
	g->str_replace(&s, "%dns", h.net.dns);
	g->str_replace(&s, "%wins", h.net.wins);
	g->str_replace(&s, "%dhcps", h.net.dhcpstart);
	g->str_replace(&s, "%dhcpe", h.net.dhcpend);
	g->str_replace(&s, "%info", h.info);
	g->str_replace(&s, "%ipub", h.ip_pub);
	g->str_replace(&s, "%id", h.id);
	g->str_replace(&s, "%i16pub", h.i16_pub);
	g->str_replace(&s, "%i16", h.i16);
	g->str_replace(&s, "%i", h.ip);
	g->str_replace(&s, "%ms", h.macs);
	g->str_replace(&s, "%m", h.mac ? h.mac : "00:00:00:00:00:00");
	g->str_replace(&s, "%n", h.name);
	g->str_replace(&s, "%l", h.location);
	g->str_replace(&s, "%devl", h.devlocation);
	g->str_replace(&s, "%port", h.port);
	g->str_replace(&s, "%p", h.passwd);

	fprintf(fh, "%s", s);
	free(s);
}
Example #30
-1
/**
@SYMTestCaseID          SYSLIB-STDLIB-CT-1072
@SYMTestCaseDesc	    Tests for ARPA net functions
@SYMTestPriority 	    High
@SYMTestActions  	    Tests for all basic network functions 
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/
void testArpa()
	{
	char* cp;
	char* cp2;
	struct in_addr iaddr;
	unsigned long ul1, ul2;
	int err;
	int i;

	test_Next("ARPA/INET.H functions");

	iaddr.s_addr=11;
	cp="16.33.50.67";
	err=inet_aton(cp, &iaddr);
	test(err==1);
	test(iaddr.s_addr==htonl(0x10213243));
	test(iaddr.s_addr==inet_addr(cp));
	cp2=inet_ntoa(iaddr);
	test(strcmp(cp2,cp)==0);

	iaddr.s_addr=11;
	err=inet_aton("16.rubbish.67", &iaddr);
	test(err==0);

	for (i=0;i<N_ADDRESSES;i++)
		{
		iaddr=inet_makeaddr(addresses[i][0], addresses[i][1]);
		test(iaddr.s_addr==ntohl(addresses[i][2]));
		ul1=inet_netof(iaddr);
		ul2=inet_lnaof(iaddr);
		test(ul1==addresses[i][0]);
		test(ul2==addresses[i][1]);
		}
	}