summaryrefslogtreecommitdiff
path: root/sys/src/ape/lib/bsd/gethostbyname.c
blob: ee788e5275473c24fa3b224d36400cf6cb9f6417 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* posix */
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

/* bsd extensions */
#include <sys/uio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include "priv.h"

int h_errno;

enum
{
	Nname= 6,
};

/*
 *  for inet addresses only
 */
struct hostent*
gethostbyname(char *name)
{
	int i, t, fd, m;
	char *p, *k, *bp;
	int nn, na;
	struct in_addr in;
	static struct hostent h;
	static char buf[1024];
	static char *nptr[Nname+1];
	static char *aptr[Nname+1];
	static char addr[Nname][4];

	h.h_name = 0;
	t = _sock_ipattr(name);

	/* connect to server */
	fd = open("/net/cs", O_RDWR);
	if(fd < 0){
		h_errno = NO_RECOVERY;
		return 0;
	}

	/* construct the query, always expect an ip# back */
	switch(t){
	case Tsys:
		snprintf(buf, sizeof buf, "!sys=%s ip=*", name);
		break;
	case Tdom:
		snprintf(buf, sizeof buf, "!dom=%s ip=*", name);
		break;
	case Tip:
		snprintf(buf, sizeof buf, "!ip=%s", name);
		break;
	}

	/* query the server */
	if(write(fd, buf, strlen(buf)) < 0){
		h_errno = TRY_AGAIN;
		close(fd);
		return 0;
	}
	lseek(fd, 0, 0);
	for(i = 0; i < sizeof(buf)-1; i += m){
		m = read(fd, buf+i, sizeof(buf) - 1 - i);
		if(m <= 0)
			break;
		buf[i+m++] = ' ';
	}
	close(fd);
	buf[i] = 0;

	/* parse the reply */
	nn = na = 0;
	for(bp = buf;;){
		k = bp;
		p = strchr(k, '=');
		if(p == 0)
			break;
		*p++ = 0;
		for(bp = p; *bp && *bp != ' '; bp++)
			;
		if(*bp)
			*bp++ = 0;
		if(strcmp(k, "dom") == 0){
			if(h.h_name == 0)
				h.h_name = p;
			if(nn < Nname)
				nptr[nn++] = p;
		} else if(strcmp(k, "sys") == 0){
			if(nn < Nname)
				nptr[nn++] = p;
		} else if(strcmp(k, "ip") == 0){
			if(inet_aton(p, &in) == 0)
				continue;
			if(na < Nname){
				memmove(addr[na], (unsigned char*)&in.s_addr, 4);
				aptr[na] = addr[na];
				na++;
			}
		}
	}
	if(nn+na == 0){
		h_errno = HOST_NOT_FOUND;
		return 0;
	}

	nptr[nn] = 0;
	aptr[na] = 0;
	h.h_aliases = nptr;
	h.h_addr_list = aptr;
	h.h_length = 4;
	h.h_addrtype = AF_INET;
	if(h.h_name == 0)
		h.h_name = nptr[0];
	if(h.h_name == 0)
		h.h_name = aptr[0];

	return &h;
}