summaryrefslogtreecommitdiffhomepage
path: root/plop.c
blob: eb2712576b90aae03ebe4dc38a756a3567d998b0 (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
#include <netdb.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

/// Tries to create, bind and start listening on INET server socket.
/// \param node Hostname
/// \param service Port
/// \return File descriptor of the socket or -1 in case of an error
/// \see getaddrinfo(3)
// TODO: Handle UNIX sockets
int make_server(const char * node, const char * service)
{
	struct addrinfo hints = {
		.ai_family = AF_UNSPEC,
		.ai_socktype = SOCK_STREAM,
		.ai_flags = AI_PASSIVE,
	};

	struct addrinfo * result;
	struct addrinfo * it;

	if (0 != getaddrinfo(node, service, &hints, &result))
	{
		return -1; // TODO: Handle errors properly
	}

	int server;

	for (it = result; it != NULL; it = it->ai_next)
	{
		server = socket(it->ai_family, it->ai_socktype, it->ai_protocol);

		if (-1 == server)
			continue;

		if (0 == bind(server, it->ai_addr,it->ai_addrlen))
			break;

		close(server);
	}

	if (it == NULL)
	{
		server = -1; // TODO: Handle errors properly
	}

	freeaddrinfo(result);

	if (-1 == server || -1 == listen(server, 5))
	{
		return -1; // TODO: Handle errors properly
	}

	return server;
}

/// Standard entry point for the program.
/// \param argc Argument count
/// \param argv Argument array
/// \return Error code
int main(int argc, char ** argv)
{
	if (2 != argc)
	{
		return 4;
	}

	int server = make_server(NULL, argv[1]);

	int client;
	static const char * response =
		"HTTP/1.1 200 OK\r\n"
		"Content-Type: text/plain; charset=utf-8\r\n"
		"\r\n"
		"plop\n";

	for (;;)
	{
		if (-1 != (client = accept(server, NULL, NULL)))
		{
			if (-1 == send(client, response, strlen(response), 0))
			{
				// TODO: Handle errors properly
			}

			// Ignore the close-related error mess.
			close(client);
		}
	}
}