This file is indexed.

/usr/share/perl5/App/Parcimonie/Daemon.pm is in parcimonie 0.10.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
=head1 NAME

App::Parcimonie::Daemon - parcimonie daemon class

=head1 SYNOPSIS

Have a look to bin/parcimonie for a full-blown real life usage example.

=cut

package App::Parcimonie::Daemon;
use Moo;
use MooX::late;

use 5.10.1;
use App::Parcimonie;
use Carp;
use Encode;
use English qw{-no_match_vars};
use List::Util qw{any};
use Time::Duration::Parse qw(parse_duration);
use Try::Tiny;
use Type::Utils qw{declare as where coerce from};
use Types::Path::Tiny qw{Dir};
use Types::Standard qw{Str Num};
use namespace::clean;

with 'App::Parcimonie::Role::HasEncoding';
use MooX::Options;


=head1 TYPES

=cut

my $DurationInSeconds = declare as Num, where { $_ > 0 };
coerce $DurationInSeconds, from Str, sub { parse_duration($_) };

=head1 ATTRIBUTES

=cut

option 'verbose'  => (
    documentation => q{Use this option to get more output.},
    isa => 'Bool', is => 'ro', default => 0
);

option 'with_dbus'  => (
    documentation => q{Send activity updates on the org.parcimonie.daemon D-Bus service},
    isa => 'Bool', is => 'ro', default => 0
);

option 'gnupg_homedir' => (
    documentation => q{GnuPG homedir.},
    isa           => Dir,
    is            => 'ro',
    format        => 's',
    coerce        => Dir->coercion,
);

option 'gnupg_extra_args' => (
    documentation => q{Extra argument passed to GnuPG. Use this option once per needed argument.},
    cmd_flag      => 'gnupg-extra-arg',
    isa           => 'ArrayRef[Str]',
    is            => 'ro',
    default       => sub { [] },
    format        => 's@',
);

has 'gnupg_builtin_args' => (
    isa           => 'ArrayRef[Str]',
    is            => 'ro',
    default       => sub { [
        '--import-options' => 'merge-only',
    ] },
);

has 'gnupg_options' => (
    isa           => 'HashRef',
    is            => 'ro',
    lazy_build    => 1,
);

option 'average_lapse_time' => (
    documentation => q{Average lapse time between two key fetches. Can be expressed in any way understood by Time::Duration::Parse.},
    isa           => $DurationInSeconds,
    is            => 'ro',
    predicate     => 'has_average_lapse_time',
    format        => 's',
    coerce        => $DurationInSeconds->coercion,
);

option 'minimum_lapse_time' => (
    documentation => q{Minimum lapse time between two key fetches. Can be expressed in any way understood by Time::Duration::Parse. Defaults to 600 seconds.},
    isa           => $DurationInSeconds,
    is            => 'ro',
    default       => sub { 600 },
    predicate     => 'has_minimum_lapse_time',
    format        => 's',
    coerce        => $DurationInSeconds->coercion,
);

has 'iterate_id' => (
    isa           => 'Int',
    is            => 'rw',
);

has 'dbus_object' => (
    isa           => 'Object',
    is            => 'ro',
    lazy_build    => 1,
);

option 'gnupg_already_torified' => (
    documentation => q{gpg is already torified somehow (e.g. gpg.conf or firewall)},
    isa       => 'Bool',
    is        => 'ro',
    required  => 0,
    default   => sub { 0; },
);

option 'gnupg2' => (
    documentation => q{Use GnuPG 2.1+ (default: autodetect gpg's version).},
    isa      => 'Bool',
    is       => 'ro',
    required => 0,
    default  => sub { gpg_is_v21(); },
);

has 'memory_usage' => (
    isa       => 'Memory::Usage',
    is        => 'ro',
    required  => 0,
);


=head1 METHODS

=cut

=head2 BUILD

Post-constructor.

=cut
sub BUILD {
    my $self = shift;

    $self->record_memory_usage("[BUILD]: entering");

    $self->keyserver_defined_on_command_line
        or checkGpgHasDefinedKeyserver(
            $self->gnupg_options,
            {
                gnupg2 => $self->gnupg2,
            });

    if ($self->with_dbus) {
        $self->record_memory_usage("[BUILD]: starting to load D-Bus dependencies");
        require App::Parcimonie::DBus::Object;
        require Net::DBus;
        require Net::DBus::Reactor;
        require Net::DBus::Service;
        require Net::DBus::Test::MockObject;
        $self->record_memory_usage("[BUILD]: finished loading D-Bus dependencies");
    }

    $self->record_memory_usage("[BUILD]: leaving");
}

sub _build_dbus_object {
    my $self = shift;

    croak "D-Bus is disabled." unless $self->with_dbus;

    my ($bus, $service);
    if ($ENV{HARNESS_ACTIVE}) {
        $bus = Net::DBus->test;
        $service = $bus->export_service("org.parcimonie.daemon");
        Net::DBus::Test::MockObject->new($service, "/org/parcimonie/daemon/object");
    }
    else {
        $bus = Net::DBus->session;
        $service = $bus->export_service("org.parcimonie.daemon");
        App::Parcimonie::DBus::Object->new($service);
    }
}

=head2 run

Run the daemon infinite loop.

=cut
sub run {
    my $self = shift;
    my $opt  = shift;
    my $args = shift;

    $self->record_memory_usage("[run]: entering");

    if ($self->with_dbus) {
        $self->run_with_dbus();
    }
    else {
        use JSON::PP;
        $self->run_without_dbus();
    }
}

sub run_without_dbus {
    my $self = shift;

    while (1) {
        my $next_sleep_time = $self->iterate;
        say encode_json({
            state   => 'Sleeping',
            details => {
                duration => $next_sleep_time,
            },
        });
        sleep($next_sleep_time);
    }
}

sub run_with_dbus {
    my $self = shift;

    $self->record_memory_usage("[run_with_dbus]: entering");

    my $reactor = Net::DBus::Reactor->main();

    my $initial_sleep_time = 1 * 1000;

    $self->iterate_id(
        $reactor->add_timeout(
            $initial_sleep_time,
            Net::DBus::Callback->new(method => sub {
                my $next_sleep_time = $self->iterate;
                # at definition time, the ->add_timeout return value is not known yet;
                # it's stored in the iterate_id attribute
                # => use it only once it's been computed.
                if (defined $self->iterate_id) {
                    $self->debug(sprintf(
                        "Will now sleep %i seconds.",
                        $next_sleep_time
                    ));
                    $self->notify({
                        signal => 'Sleeping',
                        duration => $next_sleep_time,
                    });
                    $reactor->toggle_timeout(
                        $self->iterate_id,
                        1,
                        $next_sleep_time * 1000
                    );
                }
            })
          )
    );

    $reactor->run();
};

sub debug {
    my $self = shift;
    my $msg  = shift;
    say STDERR $self->encoding->encode($msg) if $self->verbose;
}

sub fatal {
    my $self      = shift;
    my $msg       = shift;
    my $exit_code = shift;
    say STDERR $self->encoding->encode($msg);
    exit($exit_code);
}

sub _build_gnupg_options {
    my $self = shift;
    my %opts = (
        extra_args => [],
    );
    $opts{homedir} = $self->gnupg_homedir if defined $self->gnupg_homedir;
    push @{$opts{extra_args}}, @{$self->gnupg_builtin_args}
        if defined $self->gnupg_builtin_args;
    push @{$opts{extra_args}}, @{$self->gnupg_extra_args}
        if defined $self->gnupg_extra_args;
    return \%opts;
}

=head2 keyserver_defined_on_command_line

Return true iff a keyserver was passed on the command-line via --gnupg-extra-arg.

=cut
sub keyserver_defined_on_command_line {
    my $self      = shift;
    any {
        $_ =~ m{
                   \A                # starts with
                   [-] [-] keyserver # literal --keyserver, followed by
                   [ =]              # a space or an equal sign
                   [^\n]+            # followed by anything but a newline
           }xms
    } @{$self->gnupg_extra_args};
}

sub notify {
    my $self = shift;
    my $args = shift;

    if ($self->with_dbus) {
        my $signal = $args->{signal};
        my @args_name;
        if ($signal eq 'FetchBegin') {
            @args_name = qw{keyid};
        }
        elsif ($signal eq 'FetchEnd') {
            @args_name = qw{keyid success gpg_error};
        }
        elsif ($signal eq 'Sleeping') {
            @args_name = qw{duration};
        }
        else {
            croak "Unsupported signal: $signal";
        }

        my @args;
        push @args, $args->{$_} for (@args_name);
        $self->dbus_object->emit_signal($signal, @args);
    }
    else {
        say encode_json {
            state   => $args->{signal},
            details => $args,
        };
    }
}

sub tryRecvKey {
    my $self  = shift;
    my $keyid = shift;
    my $gpg_output;
    my $gpg_error;

    $self->debug(sprintf("tryRecvKey: trying to fetch %s", $keyid));
    $self->notify({ signal => 'FetchBegin', keyid => $keyid });

    try {
        $gpg_output = gpgRecvKeys(
            [ $keyid ],
            $self->gnupg_options,
            already_torified => $self->gnupg_already_torified,
            gnupg2           => $self->gnupg2,
        );
    } catch {
        $gpg_error = $_;
    };

    $gpg_output ||= '';
    my $success = 0;
    if (defined $gpg_error) {
        warn $self->encoding->encode($gpg_error);
    }
    else {
        $self->debug($gpg_output);
        $success = 1;
        $gpg_error = '';
    }

    $self->notify({
        signal    => 'FetchEnd',
        keyid     => $keyid,
        success   => $success,
        gpg_error => $gpg_error,
    });
}

sub next_sleep_time {
    my $self            = shift;
    my $num_public_keys = shift;
    my $average_lapse_time =
        $self->has_average_lapse_time ?
            $self->average_lapse_time
            : averageLapseTime($num_public_keys);

    my $fallback_lapse_time = $self->minimum_lapse_time
                            + rand($self->minimum_lapse_time);

    $self->debug(sprintf('Using %s seconds as average sleep time, '.
                         'and %s seconds as fallback sleep time.',
                         $average_lapse_time, $fallback_lapse_time
    ));

    my $next_sleep_time = rand(2 * $average_lapse_time);
    if ($next_sleep_time < $self->minimum_lapse_time) {
        $next_sleep_time = $fallback_lapse_time;
    }
    return $next_sleep_time;
}

=head2 iterate

Arg: long PGP key id (Str).
Returns next sleep time (seconds).

=cut
sub iterate {
    my $self = shift;
    my $default_sleep_time = 600;

    $self->record_memory_usage("[iterate]: entering");

    my @public_keys = gpgPublicKeys(
        $self->gnupg_options,
        already_torified => $self->gnupg_already_torified,
        gnupg2           => $self->gnupg2,
    );
    unless (@public_keys) {
        warn "No public key was found.";
        return $default_sleep_time ;
    }
    my $next_sleep_time = $self->next_sleep_time(scalar(@public_keys));
    my ( $keyid ) = pickRandomItems(1, @public_keys);
    # allow the GC to free some memory
    undef(@public_keys);

    $self->record_memory_usage("[iterate]: before fetching key $keyid");
    $self->tryRecvKey($keyid);
    $self->record_memory_usage("[iterate]: after fetching key $keyid");

    return $next_sleep_time;
}

=head2 record_memory_usage

Args: a message (Str) indicating when we're run.
Records memory usage in the memory_usage attribute,
iff. the REPORT_MEMORY_USAGE environment variable is set to a true value.

=cut
sub record_memory_usage {
    my $self = shift;
    my $message = shift;

    return unless exists $ENV{REPORT_MEMORY_USAGE}
        && defined $ENV{REPORT_MEMORY_USAGE}
        && $ENV{REPORT_MEMORY_USAGE};

    $self->memory_usage->record($message);
}

no Moo;
1; # End of App::Parcimonie::Daemon