-
Notifications
You must be signed in to change notification settings - Fork 125
/
Server.pm
422 lines (310 loc) · 9.71 KB
/
Server.pm
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package FusionInventory::Agent::HTTP::Server;
use strict;
use warnings;
use threads;
use threads::shared;
use English qw(-no_match_vars);
use HTTP::Daemon;
use Net::IP;
use Text::Template;
use File::Basename;
use Socket qw( NI_NUMERICHOST NIx_NOSERV );
use Socket::GetAddrInfo qw( getaddrinfo getnameinfo );
use FusionInventory::Agent::Tools::Network;
use FusionInventory::Agent::Logger;
my $log_prefix = "[http server] ";
sub new {
my ($class, %params) = @_;
my $self = {
logger => $params{logger} ||
FusionInventory::Agent::Logger->new(),
agent => $params{agent},
scheduler => $params{scheduler},
htmldir => $params{htmldir},
ip => $params{ip},
port => $params{port} || 62354,
trust => $params{trust}
};
bless $self, $class;
$self->{stop} = 0;
my $stop = \$self->{stop};
threads::shared::share($stop);
$self->{listener} = threads->create('_listen', $self);
return $self;
}
sub _handle {
my ($self, $client, $request, $clientIp) = @_;
my $logger = $self->{logger};
if (!$request) {
$client->close();
return;
}
my $path = $request->uri()->path();
$logger->debug($log_prefix . "request $path from client $clientIp");
# non-GET requests
my $method = $request->method();
if ($method ne 'GET') {
$logger->debug($log_prefix . "error, invalid request type: $method");
$client->send_error(400);
$client->close;
undef($client);
return;
}
# GET requests
SWITCH: {
# root request
if ($path eq '/') {
$self->_handle_root($client, $request, $clientIp);
last SWITCH;
}
# deploy request
if ($path =~ m{^/deploy/getFile/./../([\w\d/-]+)$}) {
$self->_handle_deploy($client, $request, $clientIp, $1);
last SWITCH;
}
# now request
if ($path =~ m{^/now(?:/(\S*))?$}) {
$self->_handle_now($client, $request, $clientIp, $1);
last SWITCH;
}
# status request
if ($path eq '/status') {
$self->_handle_status($client, $request, $clientIp);
last SWITCH;
}
# static content request
if ($path =~ m{^/(logo.png|site.css|favicon.ico)$}) {
my $file = $1;
$client->send_file_response("$self->{htmldir}/$file");
last SWITCH;
}
$logger->debug("error, unknown path: $path");
$client->send_error(400);
}
$client->close();
}
sub _handle_root {
my ($self, $client, $request, $clientIp) = @_;
my $logger = $self->{logger};
my $template = Text::Template->new(
TYPE => 'FILE', SOURCE => "$self->{htmldir}/index.tpl"
);
if (!$template) {
$logger->error($log_prefix . "Template access failed: $Text::Template::ERROR");
;
my $response = HTTP::Response->new(
500,
'KO',
HTTP::Headers->new('Content-Type' => 'text/html'),
"No template"
);
$client->send_response($response);
return;
}
my $hash = {
version => $FusionInventory::Agent::VERSION,
trust => $self->_is_trusted($clientIp),
status => $self->{agent}->getStatus(),
targets => [
map { $_->getStatus() } $self->{scheduler}->getTargets()
]
};
my $response = HTTP::Response->new(
200,
'OK',
HTTP::Headers->new('Content-Type' => 'text/html'),
$template->fill_in(HASH => $hash)
);
$client->send_response($response);
}
sub _handle_deploy {
my ($self, $client, $request, $clientIp, $sha512) = @_;
my $logger = $self->{logger};
return unless $sha512 =~ /^(.)(.)(.{6})/;
my $subFilePath = $1.'/'.$2.'/'.$3;
File::Glob->require();
Digest::SHA->require();
my $path;
LOOP: foreach my $target ($self->{scheduler}->getTargets()) {
foreach (File::Glob::glob($target->{storage}->getDirectory()."/deploy/fileparts/shared/*")) {
next unless -f $_.'/'.$subFilePath;
my $sha = Digest::SHA->new('512');
$sha->addfile($_.'/'.$subFilePath, 'b');
next unless $sha->hexdigest eq $sha512;
$path = $_.'/'.$subFilePath;
last LOOP;
}
}
if ($path) {
$logger->debug($log_prefix . "file $sha512 found");
$client->send_file_response($path);
$logger->debug($log_prefix . "file $path sent");
} else {
$client->send_error(404);
}
}
sub _handle_now {
my ($self, $client, $request, $clientIp, $token) = @_;
my $logger = $self->{logger};
my ($code, $message, $trace);
if (
$self->_is_trusted($clientIp) ||
$self->_is_authenticated($token)
) {
foreach my $target ($self->{scheduler}->getTargets()) {
$target->setNextRunDate(1);
}
$self->{agent}->resetToken();
$code = 200;
$message = "OK";
$trace = "valid request, forcing execution right now";
} else {
$code = 403;
$message = "Access denied";
$trace = "invalid request (bad token or bad address)";
}
my $template = Text::Template->new(
TYPE => 'FILE', SOURCE => "$self->{htmldir}/now.tpl"
);
my $hash = {
message => $message
};
my $response = HTTP::Response->new(
$code,
'OK',
HTTP::Headers->new('Content-Type' => 'text/html'),
$template->fill_in(HASH => $hash)
);
$client->send_response($response);
$logger->debug($log_prefix . $trace);
}
sub _handle_status {
my ($self, $client, $request, $clientIp) = @_;
my $status = $self->{agent}->getStatus();
my $response = HTTP::Response->new(
200,
'OK',
HTTP::Headers->new('Content-Type' => 'text/plain'),
"status: ".$status
);
$client->send_response($response);
}
sub _is_trusted {
my ($self, $address) = @_;
return 0 unless $self->{trust};
my $sourceAddr = Net::IP->new($address);
if (!$sourceAddr) {
$self->{logger}->error("Cannot parse “$address”");
return 0;
}
foreach my $trustedAddr (@{$self->{trust}}) {
my @trustedAddrToTest;
# Is it an numerical IPv4 host or network?
if ($trustedAddr =~ /^$ip_address_pattern(|\/\d+)/) {
push @trustedAddrToTest, Net::IP->new($trustedAddr);
# It's a host name, he retrieve the IPv4 addresses of the
# host.
} else {
my ( $err, @res ) = getaddrinfo( $trustedAddr, "", { socktype => SOCK_RAW } );
print("Cannot getaddrinfo $trustedAddr - $err") if $err;
while( my $ai = shift @res ) {
my ( $err, $nameinfo ) = getnameinfo( $ai->{addr}, NI_NUMERICHOST, NIx_NOSERV );
$self->{logger}->error("Cannot getnameinfo - $err") if $err;
push @trustedAddrToTest, Net::IP->new($nameinfo);
}
}
# And we compare
foreach (@trustedAddrToTest) {
my $result = $sourceAddr->overlaps($_);
return 1 if $result == $IP_A_IN_B_OVERLAP;
return 1 if $result == $IP_IDENTICAL;
}
}
return 0;
}
sub _is_authenticated {
my ($self, $token) = @_;
return 0 unless $token;
return $token eq $self->{agent}->getToken();
}
sub _listen {
my ($self) = @_;
my $logger = $self->{logger};
my $daemon = HTTP::Daemon->new(
LocalAddr => $self->{ip},
LocalPort => $self->{port},
Reuse => 1,
Timeout => 5
);
if (!$daemon) {
$logger->error($log_prefix . "failed to start the HTTPD service");
return;
}
my $url = $self->{ip} ?
"http://$self->{ip}:$self->{port}" :
"http://localhost:$self->{port}" ;
$logger->info($log_prefix . "HTTPD service started at $url");
while (1) {
my ($client, $socket) = $daemon->accept();
last if $self->{stop};
next unless $socket;
my (undef, $iaddr) = sockaddr_in($socket);
my $clientIp = inet_ntoa($iaddr);
my $request = $client->get_request();
$self->_handle($client, $request, $clientIp);
}
}
sub terminate {
my ($self) = @_;
lock $self->{stop};
$self->{stop} = 1;
}
sub DESTROY {
my ($self) = @_;
return unless $self->{listener};
if ($self->{listener}->is_joinable()) {
$self->{listener}->join();
} elsif (!$self->{listener}->is_detached()) {
$self->{listener}->detach();
}
}
1;
__END__
=head1 NAME
FusionInventory::Agent::HTTP:Server - An embedded HTTP server
=head1 DESCRIPTION
This is the server used by the agent to listen on the network for messages sent
by OCS or GLPI servers.
It is an HTTP server listening on port 62354 (by default). The following
requests are accepted:
=over
=item /status
=item /deploy
=item /now
=back
Authentication is based on a token created by the agent, and sent to the
server at initial connection. Connection from addresses matching the trust
parameter are trusted without token.
=head1 METHODS
=head2 new(%params)
The constructor. The following parameters are allowed, as keys of the %params
hash:
=over
=item I<logger>
the logger object to use
=item I<scheduler>
the scheduler object to use
=item I<agent>
the agent object
=item I<htmldir>
the directory where HTML templates and static files are stored
=item I<ip>
the network address to listen to (default: all)
=item I<port>
the network port to listen to
=item I<trust>
an IP address or an IP address range from which to trust incoming requests
without authentication token (default: none)
=back
=head2 terminate
Ensure the listening thread terminates.