summaryrefslogtreecommitdiff
path: root/server.cpp
blob: 5e67b5faf004ed9c0ff56325273e292967e0432a (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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Standard C++
#include <atomic>
#include <cerrno>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>

// FastCGI
#include <fcgiapp.h>

using namespace std;

namespace {
struct Configuration {
	int    value;
	string listen_address;
};

struct RequestError : runtime_error {
	RequestError(int status, const string& meldung)
	    : runtime_error(meldung)
	    , status(status)
	{
	}

	int status;
};

atomic_bool quit{ false };
atomic_bool reload{ false };

void
signal_handler(int signal)
{
	if ( signal == SIGINT || signal == SIGTERM ) {
		quit = true;
	}
	else if ( signal == SIGHUP ) {
		reload = true;
	}
}

void
init_signal_handler()
{
	struct sigaction sa;
	memset(&sa, 0, sizeof sa);
	sa.sa_handler = signal_handler;
	sa.sa_flags   = 0;
	sigemptyset(&sa.sa_mask);

	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);
	sigaction(SIGHUP, &sa, NULL);

	signal(SIGPIPE, SIG_IGN);
}

bool
load_configuration(Configuration& configuration)
{
	cerr << "Load configuration ...\n";
	configuration.value          = 1;
	configuration.listen_address = "127.0.0.1:5000";
	return true;
}

void
escape_html(string_view str, ostream& out)
{
	for ( auto chr: str ) {
		switch ( chr ) {
		case '<':
			out << "&lt;";
			break;
		case '>':
			out << "&gt;";
			break;
		case '&':
			out << "&amp;";
			break;
		case '\"':
			out << "&quot;";
			break;
		default:
			out << chr;
		}
	}
}

void
handle_request(char* env[], const Configuration&, string_view body, ostream& out)
{
	const char* methode = FCGX_GetParam("REQUEST_METHOD", env);

	out << "Content-Type: text/html; charset=utf-8\r\n\r\n";
	out << "<h1>Verbindung erfolgreich verarbeitet!</h1>";
	out << "<p>Methode: " << (methode ? methode : "?") << ", Body: " << body.size() << " Bytes</p>";

	out << "<pre>";
	for ( int i = 0; env[i] != NULL; ++i ) {
		// Request-Daten dürfen nicht ungefiltert als HTML ausgegeben werden.
		escape_html(env[i], out);
		out << '\n';
	}
	out << "</pre>";
}

void
send_error(const FCGX_Request& request, int status, const char* meldung)
{
	FCGX_FPrintF(request.out, "Status: %d\r\n", status);
	FCGX_FPrintF(request.out, "Content-Type: text/plain; charset=utf-8\r\n\r\n");
	FCGX_FPrintF(request.out, "%s\n", meldung);
}

string
read_request_body(const FCGX_Request& request)
{
	string body;
	char   buffer[8192];
	int    gelesen;

	while ( (gelesen = FCGX_GetStr(buffer, sizeof buffer, request.in)) > 0 ) {
		body.append(buffer, gelesen);
	}

	return body;
}
} // namespace

int
main()
{
	FCGX_Init();

	Configuration configuration{};
	if ( !load_configuration(configuration) ) {
		cerr << "Die Konfiguration konnte nicht geladen werden.\n";
		return EXIT_FAILURE;
	}

	auto socket = FCGX_OpenSocket(configuration.listen_address.c_str(), 20);
	if ( socket == -1 ) {
		cerr << "Fehler beim Erstellen des Listen-Sockets...\n";
		return EXIT_FAILURE;
	}

	FCGX_Request request;
	if ( FCGX_InitRequest(&request, socket, FCGI_FAIL_ACCEPT_ON_INTR) != 0 ) {
		cerr << "Fehler beim Initialisieren...\n";
		return EXIT_FAILURE;
	}

	init_signal_handler();

	cout << "Handle Requests...\n";

	while ( !quit ) {
		if ( reload.exchange(false) ) {
			Configuration new_configuration{};

			if ( load_configuration(new_configuration) ) {
				if ( new_configuration.listen_address != configuration.listen_address ) {
					cerr << "Listen-Adresse geaendert, wirksam erst nach Neustart.\n";
				}

				configuration = std::move(new_configuration);
			}
			else {
				cerr << "Neue Konfiguration nicht lesbar, die bisherige bleibt in Kraft.\n";
			}
		}

		if ( FCGX_Accept_r(&request) < 0 ) {
			if ( errno != EINTR ) {
				cerr << "Fehler beim Annehmen der Verbindung: " << strerror(errno) << '\n';
				break;
			}
			continue;
		}

		try {
			const string body = read_request_body(request);

			ostringstream response;
			handle_request(request.envp, configuration, body, response);

			const string_view text = response.view();
			FCGX_PutStr(text.data(), static_cast<int>(text.size()), request.out);
		}
		catch ( const RequestError& e ) {
			FCGX_FPrintF(request.err, "Anfrage abgebrochen (%d): %s\n", e.status, e.what());
			send_error(request, e.status, e.what());
		}
		catch ( const exception& e ) {
			FCGX_FPrintF(request.err, "Fehler beim Verarbeiten der Anfrage: %s\n", e.what());
			send_error(request, 500, "Die Anfrage konnte nicht verarbeitet werden.");
		}

		FCGX_Finish_r(&request);
	}

	cout << "shutdown...\n";
}