xref: /haiku/src/add-ons/kernel/network/dns_resolver/server/main.cpp (revision 21769ef60394a854df725a2ad2ca995c4daa2042)
1 /*
2  * Copyright 2012 Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Paweł Dziepak, pdziepak@quarnos.org
7  */
8 
9 
10 #include <stdlib.h>
11 
12 #include <sys/socket.h>
13 #include <netdb.h>
14 
15 #include <port.h>
16 #include <SupportDefs.h>
17 
18 #include "Definitions.h"
19 
20 
21 status_t
22 resolve_dns(const char* host, uint32* addr)
23 {
24 	addrinfo* ai;
25 	addrinfo* current;
26 	status_t result = getaddrinfo(host, NULL, NULL, &ai);
27 	if (result != B_OK)
28 		return result;
29 
30 	current = ai;
31 
32 	while (current != NULL) {
33 		if (current->ai_family == AF_INET) {
34 			sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(current->ai_addr);
35 			*addr = sin->sin_addr.s_addr;
36 			freeaddrinfo(ai);
37 			return B_OK;
38 		}
39 
40 		current = current->ai_next;
41 	}
42 
43 	freeaddrinfo(ai);
44 	return B_NAME_NOT_FOUND;
45 }
46 
47 
48 status_t
49 main_loop(port_id portReq, port_id portRpl)
50 {
51 	do {
52 		ssize_t size = port_buffer_size(portReq);
53 		if (size < B_OK)
54 			return 0;
55 
56 		void* buffer = malloc(size);
57 		if (buffer == NULL)
58 			return B_NO_MEMORY;
59 
60 		int32 code;
61 		status_t result = read_port(portReq, &code, buffer, size);
62 		if (size < B_OK) {
63 			free(buffer);
64 			return 0;
65 		}
66 
67 		if (code != MsgResolveRequest) {
68 			free(buffer);
69 			continue;
70 		}
71 
72 		uint32 addr;
73 		result = resolve_dns(reinterpret_cast<char*>(buffer), &addr);
74 		free(buffer);
75 
76 		if (result == B_OK)
77 			result = write_port(portRpl, MsgResolveReply, &addr, sizeof(addr));
78 		else {
79 			result = write_port(portRpl, MsgResolveError, &result,
80 				sizeof(result));
81 		}
82 
83 		if (result == B_BAD_PORT_ID)
84 			return 0;
85 
86 	} while (true);
87 }
88 
89 
90 int
91 main(int argc, char** argv)
92 {
93 	port_id portReq = find_port(kPortNameReq);
94 	if (portReq == B_NAME_NOT_FOUND) {
95 		fprintf(stderr, "%s\n", strerror(portReq));
96 		return portReq;
97 	}
98 
99 	port_id portRpl = find_port(kPortNameRpl);
100 	if (portRpl == B_NAME_NOT_FOUND) {
101 		fprintf(stderr, "%s\n", strerror(portRpl));
102 		return portRpl;
103 	}
104 
105 	return main_loop(portReq, portRpl);
106 }
107 
108