-
Notifications
You must be signed in to change notification settings - Fork 125
/
Server.pm
687 lines (548 loc) · 19.5 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
package FusionInventory::Agent::HTTP::Server;
use strict;
use warnings;
use UNIVERSAL::require;
use English qw(-no_match_vars);
use File::Basename;
use HTTP::Daemon;
use IO::Handle;
use Net::IP;
use Text::Template;
use File::Glob;
use URI;
use Socket qw(IN6ADDR_ANY inet_ntop);
use FusionInventory::Agent::Version;
use FusionInventory::Agent::Logger;
use FusionInventory::Agent::Tools;
use FusionInventory::Agent::Tools::Network;
my $log_prefix = "[http server] ";
sub new {
my ($class, %params) = @_;
my $self = {
logger => $params{logger} ||
FusionInventory::Agent::Logger->new(),
agent => $params{agent},
htmldir => $params{htmldir},
ip => $params{ip},
port => $params{port} || 62354,
listeners => {},
};
bless $self, $class;
$self->setTrustedAddresses(%params);
# Load any Server sub-module as plugin
my @plugins = ();
my ($sub_modules_path) = $INC{module2file(__PACKAGE__)} =~ /(.*)\.pm/;
foreach my $file (File::Glob::bsd_glob("$sub_modules_path/*.pm")) {
if ($OSNAME eq 'MSWin32') {
$file =~ s{\\}{/}g;
$sub_modules_path =~ s{\\}{/}g;
}
my ($name) = $file =~ m{$sub_modules_path/(\S+)\.pm$};
next unless $name;
# Don't load Plugin base class
next if $name eq "Plugin";
$self->{logger}->debug($log_prefix . "Trying to load $name Server plugin");
my $module = __PACKAGE__ . "::" . $name;
$module->require();
if ($EVAL_ERROR) {
$self->{logger}->debug($log_prefix . "Failed to load $name Server plugin: $EVAL_ERROR");
next;
}
my $plugin = $module->new(server => $self)
or next;
$plugin->init();
if ($plugin->disabled()) {
$self->{logger}->debug($log_prefix . "HTTPD $name Server plugin loaded but disabled");
} else {
$self->{logger}->info($log_prefix . "HTTPD $name Server plugin loaded");
}
push @plugins, $plugin;
}
# Sort and store loaded plugins
@plugins = sort { $b->priority() <=> $a->priority() } @plugins
if @plugins > 1;
$self->{_plugins} = \@plugins;
return $self;
}
sub setTrustedAddresses {
my ($self, %params) = @_;
# compute addresses allowed for push requests
foreach my $target ($self->{agent}->getTargets()) {
next unless $target->isType('server');
my $url = $target->getUrl();
my $host = URI->new($url)->host();
my @addresses = compile($host, $self->{logger});
$self->{trust}->{$url} = \@addresses;
}
if ($params{trust}) {
foreach my $string (@{$params{trust}}) {
my @addresses = compile($string);
$self->{trust}->{$string} = \@addresses if @addresses;
}
}
}
sub _handle {
my ($self, $client, $request, $clientIp) = @_;
my $logger = $self->{logger};
if (!$request) {
$client->close();
return;
}
my $path = $request->uri()->path();
my $method = $request->method();
$logger->debug($log_prefix . "$method request $path from client $clientIp");
my $keepalive = 0;
my $status = 400;
my $error_400 = $log_prefix . "invalid request type: $method";
SWITCH: {
# root request
if ($path eq '/') {
last SWITCH if $method ne 'GET';
$status = $self->_handle_root($client, $request, $clientIp);
last SWITCH;
}
# deploy request
if ($path =~ m{^/deploy/getFile/./../([\w\d/-]+)$}) {
last SWITCH if $method ne 'GET';
$status = $self->_handle_deploy($client, $request, $clientIp, $1);
last SWITCH;
}
# plugins request
foreach my $plugin (@{$self->{_plugins}}) {
next if $plugin->disabled();
if ($plugin->urlMatch($path)) {
undef $error_400;
last SWITCH unless $plugin->supported_method($method);
$status = $plugin->handle($client, $request, $clientIp);
$keepalive = $plugin->keepalive();
last SWITCH if $status;
}
}
# now request
if ($path =~ m{^/now(?:/(\S*))?$}) {
last SWITCH if $method ne 'GET';
$status = $self->_handle_now($client, $request, $clientIp, $1);
last SWITCH;
}
# status request
if ($path eq '/status') {
last SWITCH if $method ne 'GET';
$status = $self->_handle_status($client, $request, $clientIp);
last SWITCH;
}
# static content request
if ($path =~ m{^/(logo.png|site.css|favicon.ico)$}) {
my $file = $1;
last SWITCH if $method ne 'GET';
$client->send_file_response("$self->{htmldir}/$file");
$status = 200;
last SWITCH;
}
$error_400 = $log_prefix . "unknown path: $path";
}
if ($status == 400) {
$logger->error($error_400) if $error_400;
$client->send_error(400)
}
$logger->debug($log_prefix . "response status $status");
if ($keepalive) {
# Looking for another request
$self->_handle($client, $client->get_request(), $clientIp);
} else {
$client->close();
}
}
sub _handle_plugins {
my ($self, $client, $request, $clientIp, $plugins) = @_;
my $logger = $self->{logger};
if (!$request) {
$client->close();
return;
}
my $path = $request->uri()->path();
my $method = $request->method();
my $keepalive = 0;
$logger->debug($log_prefix . "$method request $path from client $clientIp via plugin");
my $status = 400;
my $match = 0;
foreach my $plugin (@{$plugins}) {
next if $plugin->disabled();
if ($plugin->urlMatch($path)) {
$match = 1;
last unless ($plugin->supported_method($method));
$status = $plugin->handle($client, $request, $clientIp);
$keepalive = $plugin->keepalive();
last if $status;
}
}
if ($status == 400) {
$logger->error($log_prefix . "unknown path: $path") unless $match;
$client->send_error(400);
$status = 400;
}
$logger->debug($log_prefix . "response status $status");
if ($keepalive) {
# Looking for another request
$self->_handle_plugins($client, $client->get_request(), $clientIp, $plugins);
} else {
$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 500;
}
my @server_targets =
map { { name => $_->getUrl(), date => $_->getFormatedNextRunDate() } }
grep { $_->isType('server') }
$self->{agent}->getTargets();
my @local_targets =
map { { name => $_->getPath(), date => $_->getFormatedNextRunDate() } }
grep { $_->isType('local') }
$self->{agent}->getTargets();
my @httpd_plugins = map { @{$_->{plugins}} } values(%{$self->{listeners}});
push @httpd_plugins, @{$self->{_plugins}};
my @listening_plugins =
map { { port => $_->config('port'), name => $_->name() } }
grep { ! $_->disabled() }
@httpd_plugins;
my $hash = {
version => $FusionInventory::Agent::Version::VERSION,
trust => $self->_isTrusted($clientIp),
status => $self->{agent}->getStatus(),
httpd_plugins => \@listening_plugins,
server_targets => \@server_targets,
local_targets => \@local_targets
};
my $response = HTTP::Response->new(
200,
'OK',
HTTP::Headers->new('Content-Type' => 'text/html'),
$template->fill_in(HASH => $hash)
);
$client->send_response($response);
return 200;
}
sub _handle_deploy {
my ($self, $client, $request, $clientIp, $sha512) = @_;
return unless $sha512 =~ /^(.)(.)(.{6})/;
my $subFilePath = $1.'/'.$2.'/'.$3;
my $logger = $self->{logger};
Digest::SHA->require();
if ($EVAL_ERROR) {
$logger->error("Failed to load Digest::SHA: $EVAL_ERROR");
# Return 501 (Not Implemented) to client with reason
$client->send_error(501, 'Digest::SHA perl library is missing');
return 501;
}
my $path;
my $count = 0;
LOOP: foreach my $target ($self->{agent}->getTargets()) {
foreach (File::Glob::bsd_glob($target->{storage}->getDirectory() . "/deploy/fileparts/shared/*")) {
next unless -f $_.'/'.$subFilePath;
$count ++;
my $sha = Digest::SHA->new('512');
$sha->addfile($_.'/'.$subFilePath, 'b');
next unless $sha->hexdigest eq $sha512;
$path = $_.'/'.$subFilePath;
last LOOP;
}
}
if ($path) {
$client->send_file_response($path);
return 200;
} else {
if ($count) {
$client->send_error(404);
} else {
# Report this agent as nothing to share
$client->send_error(404, 'Nothing found');
}
return 404;
}
}
sub _handle_now {
my ($self, $client, $request, $clientIp) = @_;
my $logger = $self->{logger};
my ($code, $message, $trace);
BLOCK: {
foreach my $target ($self->{agent}->getTargets()) {
next unless $target->isType('server');
my $url = $target->getUrl();
my $addresses = $self->{trust}->{$url};
next unless isPartOf($clientIp, $addresses, $logger);
$target->setNextRunDateFromNow();
$code = 200;
$message = "OK";
$trace = "rescheduling next contact for target $url right now";
last BLOCK;
}
if ($self->_isTrusted($clientIp)) {
foreach my $target ($self->{agent}->getTargets()) {
$target->setNextRunDateFromNow();
}
$code = 200;
$message = "OK";
$trace = "rescheduling next contact for all targets right now";
last BLOCK;
}
$code = 403;
$message = "Access denied";
$trace = "invalid request (untrusted 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);
return $code;
}
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);
return 200;
}
sub _isTrusted {
my ($self, $address) = @_;
foreach my $trusted_addresses (values %{$self->{trust}}) {
return 1
if isPartOf(
$address,
$trusted_addresses,
$self->{logger}
);
}
return 0;
}
sub init {
my ($self) = @_;
my $logger = $self->{logger};
$self->{listener} = HTTP::Daemon->new(
LocalAddr => $self->{ip},
LocalPort => $self->{port},
ReuseAddr => 1,
Timeout => 1,
Blocking => 0
);
if (!$self->{listener}) {
$logger->error($log_prefix . "failed to start the HTTPD service");
return;
}
$logger->info(
$log_prefix . "HTTPD service started on port $self->{port}"
);
# Load any plugin configuration and fix plugins list handled on main port
my %plugins = map { $_->name() => $_ } @{$self->{_plugins}};
foreach my $plugin (@{$self->{_plugins}}) {
next if $plugin->disabled();
# We handle SSL Plugin differently
if ($plugin->name() eq 'SSL') {
my $ports = $plugin->config('ports');
foreach my $port (@{$ports}) {
# Handle SSL case on default port
if (!$port || $port == $self->{port}) {
$self->{_ssl} = $plugin;
$logger->info($log_prefix . "HTTPD SSL Server plugin enabled on default port");
next;
}
if (!$self->{listeners}->{$port}) {
my $listener = HTTP::Daemon->new(
LocalAddr => $self->{ip},
LocalPort => $port,
ReuseAddr => 1,
Timeout => 1,
Blocking => 0
);
unless ($listener) {
$logger->error($log_prefix . "failed to start the HTTPD service on port $port for SSL plugin");
next;
}
$self->{listeners}->{$port} = {
ssl => $plugin,
listener => $listener,
plugins => [],
};
} else {
$self->{listeners}->{$port}->{ssl} = $plugin;
}
$logger->info($log_prefix . "HTTPD SSL Server plugin enabled on port $port");
}
delete $plugins{$plugin->name()};
next;
}
# Add a port listener if a plugin uses a dedicated port
my $port = $plugin->port();
if ($port && $port != $self->{port}) {
if ($self->{listeners}->{$port}) {
push @{$self->{listeners}->{$port}->{plugins}}, $plugin;
$logger->info($log_prefix . "HTTPD ".$plugin->name()." Server plugin also used on port $port");
} else {
my $listener = HTTP::Daemon->new(
LocalAddr => $self->{ip},
LocalPort => $port,
ReuseAddr => 1,
Timeout => 1,
Blocking => 0
);
if (!$listener) {
$logger->error($log_prefix . "failed to start the HTTPD service on port $port for ".$plugin->name()." plugin");
$plugin->disable();
} else {
$self->{listeners}->{$port} = {
listener => $listener,
plugins => [ $plugin ],
};
$logger->info($log_prefix . "HTTPD ".$plugin->name()." Server plugin also started on port $port");
}
}
delete $plugins{$plugin->name()};
} elsif ($port) {
$logger->info($log_prefix . "HTTPD ".$plugin->name()." Server plugin also used on main port $self->{port}");
}
}
$self->{_plugins} = [ values(%plugins) ];
return 1;
}
sub needToRestart {
my ($self, %params) = @_;
# If no httpd daemon was started, we need to really start it
return 1 unless $self->{listener};
# Restart httpd daemon if ip or port changed
return 1 if ($params{ip} && (!$self->{ip} || $params{ip} ne $self->{ip}));
return 1 if ($params{port} && (!$self->{port} || $params{port} ne $self->{port}));
# Reload any plugin configuration and check if port or status has changed
foreach my $plugin (@{$self->{_plugins}}) {
my $port = $plugin->port();
my $disabled = $plugin->disabled();
$plugin->init();
return 1 if $port != $plugin->port();
return 1 if $disabled != $plugin->disabled();
}
# Logger may have changed, but then resetting logger ref is sufficient
$self->{logger} = $params{logger};
$self->{logger}->debug2(
$log_prefix . "HTTPD service still listening on port $self->{port}"
);
# Be sure to reset computed trusted addresses
delete $self->{trust};
$self->setTrustedAddresses(%params);
return 0;
}
sub stop {
my ($self) = @_;
return unless $self->{listener};
foreach my $port (keys(%{$self->{listeners}})) {
$self->{listeners}->{$port}->{listener}->shutdown(2);
delete $self->{listeners}->{$port};
}
$self->{listener}->shutdown(2);
$self->{logger}->debug($log_prefix . "HTTPD service stopped");
delete $self->{_plugins};
delete $self->{listener};
}
sub handleRequests {
my ($self) = @_;
return unless $self->{listener}; # init() call failed
# First try to handle plugin requests on dedicated ports
foreach my $port (keys(%{$self->{listeners}})) {
my ($client, $socket) = $self->{listeners}->{$port}->{listener}->accept();
next unless $socket;
# Upgrade to SSL if required
my $ssl = $self->{listeners}->{$port}->{ssl};
if ($ssl && !$ssl->upgrade_SSL($client)) {
$self->{logger}->debug($log_prefix . "HTTPD can't start SSL session");
next;
}
my $family = sockaddr_family($socket);
my $iaddr = $family == AF_INET ? unpack_sockaddr_in($socket) :
$family == AF_INET6 ? unpack_sockaddr_in6($socket) :
INADDR_ANY;
my $clientIp = inet_ntop($family, $iaddr);
my $request = $client->get_request();
$self->_handle_plugins($client, $request, $clientIp, $self->{listeners}->{$port}->{plugins});
}
my ($client, $socket) = $self->{listener}->accept();
return unless $socket;
# Upgrade to SSL if required
if ($self->{_ssl} && !$self->{_ssl}->upgrade_SSL($client)) {
$self->{logger}->debug($log_prefix . "HTTPD can't start SSL session");
return;
}
my $family = sockaddr_family($socket);
my $iaddr = $family == AF_INET ? unpack_sockaddr_in($socket) :
$family == AF_INET6 ? unpack_sockaddr_in6($socket) :
INADDR_ANY;
my $clientIp = inet_ntop($family, $iaddr);
my $request = $client->get_request();
$self->_handle($client, $request, $clientIp);
return 1;
}
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 connection source address: trusted requests are
accepted, other are rejected.
=head1 CLASS 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<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
(default: none)
=back
=head1 INSTANCE METHODS
=head2 $server->init()
Start the server internal listener.
=head2 $server->handleRequests()
Check if there any incoming request, and honours it if needed.