File: Reload.pm

package info (click to toggle)
lemonldap-ng 2.21.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 28,024 kB
  • sloc: perl: 77,414; javascript: 25,284; xml: 6,473; makefile: 1,303; sh: 453; sql: 159; python: 53; php: 26
file content (683 lines) | stat: -rw-r--r-- 22,962 bytes parent folder | download | duplicates (2)
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
package Lemonldap::NG::Handler::Main::Reload;

our $VERSION = '2.21.0';

package Lemonldap::NG::Handler::Main;

use strict;
use Digest::SHA qw(sha256_hex);
use Lemonldap::NG::Common::Conf::Constants;    #inherits
use Lemonldap::NG::Common::Crypto;
use Lemonldap::NG::Common::Safelib;            #link protected safe Safe object
use Lemonldap::NG::Handler::Main::Jail;
use Scalar::Util qw(weaken);

use constant UNPROTECT => 1;
use constant SKIP      => 2;
use constant MAYSKIP   => 3;

our @_onReload;

sub onReload {
    my ( $class, $obj, $sub ) = @_;
    weaken($obj);
    push @_onReload, [ $obj, $sub ];
}

# CONFIGURATION UPDATE

## @rmethod protected int checkConf(boolean force)
# Check if configuration is up to date, and reload it if needed.
# If the optional boolean $force is set to true,
# * cached configuration is ignored
# * and checkConf returns false if it fails to load remote config
# @param $force boolean
# @return true if config is up to date or if reload config succeeded
sub checkConf {
    my ( $class, $force ) = @_;
    $class->logger->debug("Check configuration for $class");
    my $prm    = { local => !$force, localPrm => $class->localConfig };
    my $cfgNum = $class->confAcc->lastCfg();
    $prm->{local} = 0 if $class->cfgNum and $cfgNum != $class->cfgNum;
    my $conf = $class->confAcc->getConf($prm);
    chomp $Lemonldap::NG::Common::Conf::msg;

    unless ( ref($conf) ) {
        $class->logger->error(
"$class: Unable to load configuration: $Lemonldap::NG::Common::Conf::msg"
        );
        return $force ? 0 : $class->cfgNum ? 1 : 0;
    }

    if ($Lemonldap::NG::Common::Conf::msg) {
        if ( $Lemonldap::NG::Common::Conf::msg =~ /Error:/ ) {
            $class->logger->error($Lemonldap::NG::Common::Conf::msg);
        }
        elsif ( $Lemonldap::NG::Common::Conf::msg =~ /Warn:/ ) {
            $class->logger->warn($Lemonldap::NG::Common::Conf::msg);
        }
        else {
            $class->logger->debug($Lemonldap::NG::Common::Conf::msg);
        }
    }
    $Lemonldap::NG::Common::Conf::msg = '';

    if (   $force
        or !$class->cfgNum
        or !$class->cfgDate
        or $class->cfgNum != $conf->{cfgNum}
        or $class->cfgDate != $conf->{cfgDate} )
    {
        $class->logger->debug(
            "Get configuration $conf->{cfgNum} aged $conf->{cfgDate}");
        unless ( $class->cfgNum( $conf->{cfgNum} )
            && $class->cfgDate( $conf->{cfgDate} ) )
        {
            $class->logger->error('No configuration available');
            return 0;
        }
        $class->configReload($conf);
        foreach (@_onReload) {
            my ( $obj, $sub ) = @$_;
            if ($obj) {
                $class->logger->debug(
                    'Launching ' . ref($obj) . "->$sub(conf)" );
                unless ( $obj->$sub($conf) ) {
                    $class->logger->error( "Underlying object can't load conf ("
                          . ref($obj)
                          . "->$sub)" );
                    if ( $obj->can('error') ) {
                        $Lemonldap::NG::Common::Conf::msg = $obj->error;
                    }
                    return 0;
                }
            }
        }
    }
    $class->checkTime( $conf->{checkTime} ) if $conf->{checkTime};
    $class->checkMsg( $conf->{checkMsg} )   if $conf->{checkMsg};
    $class->lastCheck( time() );
    $class->logger->debug("$class: configuration is up to date");
    return 1;
}

# RELOAD SYSTEM

## @rmethod int reload
# Launch checkConf() with $local=0, so remote configuration is tested.
# Then build a simple HTTP response that just returns "200 OK" or
# "500 Server Error".
# @return Apache constant ($class->OK or $class->SERVER_ERROR)
sub reload {
    my $class = shift;
    $class->logger->notice("Request for configuration reload");
    return $class->checkConf(1) ? $class->DONE : $class->SERVER_ERROR;
}

*refresh = *reload;

# INTERNAL METHODS

## @imethod void configReload(hashRef conf, hashRef tsv)
# Given a Lemonldap::NG configuration $conf, computes values used to
# handle requests and store them in a thread shared object called $tsv
#
# methods called by configReload, and thread shared values computed, are:
# - jailInit():
#      - jail
# - defaultValuesInit():
#      (scalars for global options)
#      - cookieExpiration  # warning: absent from default Conf
#      - cookieName
#      - securedCookie,
#      - httpOnly
#      - whatToTrace
#      - customFunctions
#      - timeoutActivity
#      - timeoutActivityInterval
#      - useRedirectOnError
#      - useRedirectOnForbidden
#      - useRedirectAjaxOnUnauthorized
#      - useSafeJail
#      (objects)
#      - cipher  # Lemonldap::NG::Common::Crypto object
#      (hashrefs for vhost options)
#      - https
#      - port
#      - maintenance
# - portalInit():
#      - portal (functions that returns portal URL)
# - locationRulesInit():
#      - locationCount
#      - defaultCondition
#      - defaultProtection
#      - locationCondition
#      - locationProtection
#      - locationRegexp
#      - locationConditionText
# - sessionStorageInit():
#      - sessionStorageModule
#      - sessionStorageOptions
#      - sessionCacheModule
#      - sessionCacheOptions
# - headersInit():
#      - headerList
#      - forgeHeaders
# - postUrlInit():
#      - inputPostData
#      - outputPostData
# - aliasInit():
#      - vhostAlias
# - oauth2Init():
#      - oauth2Options
# - msgBrokerInit():
#      - msgBrokerWriter
#      - msgBrokerReader
#
# The *Init() methods can be run in any order,
# but jailInit must be run first because $tsv->{jail}
# is used by locationRulesInit, headersInit and postUrlInit.

# @param $conf reference to the configuration hash
# @param $tsv reference to the thread-shared parameters conf
sub configReload {
    my ( $class, $conf ) = @_;
    $class->logger->info(
        "Loading configuration $conf->{cfgNum} for process $$");

    foreach my $sub (
        qw( defaultValuesInit jailInit portalInit locationRulesInit
        sessionStorageInit headersInit postUrlInit aliasInit
        oauth2Init msgBrokerInit )
      )
    {
        $class->logger->debug("Process $$ calls $sub");
        $class->$sub($conf);
    }
    return 1;
}

## @imethod protected void jailInit(hashRef args)
# Set default values for non-customized variables
# @param $args reference to the configuration hash
sub jailInit {
    my ( $class, $conf ) = @_;

    $class->tsv->{jail} = Lemonldap::NG::Handler::Main::Jail->new( {
            useSafeJail          => $conf->{useSafeJail},
            customFunctions      => $conf->{customFunctions},
            multiValuesSeparator => $conf->{multiValuesSeparator},
        }
    );
    $class->tsv->{jail}
      ->build_jail( $class, $conf->{require}, $conf->{requireDontDie} );
}

## @imethod protected void defaultValuesInit(hashRef args)
# Set default values for non-customized variables
# @param $args reference to the configuration hash
sub defaultValuesInit {
    my ( $class, $conf ) = @_;

    $class->tsv->{$_} = $conf->{$_}
      foreach ( qw(
        cookieExpiration        cookieName         customFunctions
        securedCookie           timeout            timeoutActivity
        timeoutActivityInterval useRedirectOnError useRedirectOnForbidden
        useSafeJail  httpOnly   whatToTrace        handlerInternalCache
        handlerServiceTokenTTL  customToTrace      lwpOpts lwpSslOpts
        authChoiceAuthBasic     authChoiceParam    upgradeSession
        hashedSessionStore      eventQueueName     eventStatus
        statusQueueName useRedirectAjaxOnUnauthorized
        )
      );

    $class->tsv->{cipher} = Lemonldap::NG::Common::Crypto->new( $conf->{key} );
    $class->tsv->{keyH}   = sha256_hex( $conf->{key} );

    foreach my $opt (qw(https port maintenance)) {

        # Record default value in key '_'
        $class->tsv->{$opt} = { _ => $conf->{$opt} };

        # Override with vhost options
        if ( $conf->{vhostOptions} ) {
            my $name = 'vhost' . ucfirst($opt);
            foreach my $vhost ( sort keys %{ $conf->{vhostOptions} } ) {
                $conf->{vhostOptions}->{$vhost} ||= {};
                my $val = $conf->{vhostOptions}->{$vhost}->{$name};

                # Keep global value if $val is negative
                if ( defined $val and $val >= 0 ) {
                    $class->logger->debug(
                        "Options $opt for vhost $vhost: $val");
                    $class->tsv->{$opt}->{$vhost} = $val;
                }
            }
        }
    }
    if ( $conf->{vhostOptions} ) {
        foreach my $vhost ( sort keys %{ $conf->{vhostOptions} } ) {
            $class->tsv->{type}->{$vhost} =
              $conf->{vhostOptions}->{$vhost}->{vhostType};
            $class->tsv->{authnLevel}->{$vhost} =
              $conf->{vhostOptions}->{$vhost}->{vhostAuthnLevel};
            $class->tsv->{serviceTokenTTL}->{$vhost} =
              $conf->{vhostOptions}->{$vhost}->{vhostServiceTokenTTL};
            $class->tsv->{accessToTrace}->{$vhost} =
              $conf->{vhostOptions}->{$vhost}->{vhostAccessToTrace};
            $class->tsv->{devOpsRulesUrl}->{$vhost} =
              $conf->{vhostOptions}->{$vhost}->{vhostDevOpsRulesUrl};
        }
    }
    return 1;
}

## @imethod protected void portalInit(hashRef args)
# Verify that portal variable exists. Die unless
# @param $args reference to the configuration hash
sub portalInit {
    my ( $class, $conf ) = @_;
    unless ( $conf->{portal} ) {
        $class->logger->error("portal parameter required");
        return 0;
    }
    if ( $conf->{portal} =~ /[\$\(&\|"']/ ) {
        ( $class->tsv->{portal} ) =
          $class->conditionSub( $conf->{portal} );
    }
    else {
        $class->tsv->{portal} = sub { return $conf->{portal} };
    }
    return 1;
}

## @imethod void locationRulesInit(hashRef args)
# Compile rules.
# Rules are stored in $args->{locationRules}->{<virtualhost>} that contains
# regexp=>test expressions where :
# - regexp is used to test URIs
# - test contains an expression used to grant the user
#
# This function creates 2 hashRef containing :
# - one list of the compiled regular expressions for each virtual host
# - one list of the compiled functions (compiled with conditionSub()) for each
# virtual host
# @param $args reference to the configuration hash
sub locationRulesInit {
    my ( $class, $conf, $orules ) = @_;

    $orules ||= $conf->{locationRules};
    $class->tsv->{vhostReg} = [];
    my @lastReg;

    foreach my $vhost ( keys %$orules ) {
        my $rules = $orules->{$vhost};
        if ( $vhost =~ /[\%\*]/ ) {
            my $expr = join '[^\.]*', map {
                my $elt = $_;
                join '.*', map { quotemeta $_ } split /\*/, $elt;
            } split /\%/, $vhost;
            if ($expr) {
                push @{ $class->tsv->{vhostReg} }, [ qr/^$expr$/, $vhost ];
            }
            else {
                push @lastReg, [ qr/.+/, $vhost ];
            }
        }
        $class->tsv->{locationCount}->{$vhost}         = 0;
        $class->tsv->{locationCondition}->{$vhost}     = [];
        $class->tsv->{locationProtection}->{$vhost}    = [];
        $class->tsv->{locationRegexp}->{$vhost}        = [];
        $class->tsv->{locationConditionText}->{$vhost} = [];
        $class->tsv->{locationAuthnLevel}->{$vhost}    = [];

        foreach my $url ( sort keys %{$rules} ) {
            my ( $cond, $prot ) = $class->conditionSub( $rules->{$url} );
            unless ($cond) {
                $class->tsv->{maintenance}->{$vhost} = 1;
                $class->logger->error(
                    "Unable to build rule '$rules->{$url}': "
                      . $class->tsv->{jail}->error );
                next;
            }

            if ( $url eq 'default' ) {
                $class->tsv->{defaultCondition}->{$vhost}  = $cond;
                $class->tsv->{defaultProtection}->{$vhost} = $prot;
            }
            else {
                push @{ $class->tsv->{locationCondition}->{$vhost} },  $cond;
                push @{ $class->tsv->{locationProtection}->{$vhost} }, $prot;
                push @{ $class->tsv->{locationRegexp}->{$vhost} },     qr/$url/;
                push @{ $class->tsv->{locationAuthnLevel}->{$vhost} },
                  $url =~ /\(\?#AuthnLevel=(-?\d+)\)/
                  ? $1
                  : undef;
                push @{ $class->tsv->{locationConditionText}->{$vhost} },
                    $url =~ /^\(\?#(.*?)\)/ ? $1
                  : $url =~ /^(.*?)##(.+)$/ ? $2
                  :                           $url;
                $class->tsv->{locationCount}->{$vhost}++;
            }
        }

        # Default policy set to 'accept'
        unless ( $class->tsv->{defaultCondition}->{$vhost} ) {
            $class->tsv->{defaultCondition}->{$vhost}  = sub { 1 };
            $class->tsv->{defaultProtection}->{$vhost} = 0;
        }
    }
    @{ $class->tsv->{vhostReg} } = sort {
        my $av = $a->[1];
        my $bv = $b->[1];
        return 1  if $av =~ /^\*/ and $bv !~ /^\*/;
        return -1 if $bv =~ /^\*/ and $av !~ /^\*/;
        return 1  if $av =~ /^\%/ and $bv !~ /^\%/;
        return -1 if $bv =~ /^\%/ and $av !~ /^\%/;
        return length($bv) <=> length($av) || $av cmp $bv;
    } @{ $class->tsv->{vhostReg} } if @{ $class->tsv->{vhostReg} };
    push @{ $class->tsv->{vhostReg} }, @lastReg if @lastReg;
    return 1;
}

## @imethod protected void sessionStorageInit(hashRef args)
# Initialize the Apache::Session::* module choosed to share user's variables
# and the Cache::Cache module chosen to cache sessions
# @param $args reference to the configuration hash
sub sessionStorageInit {
    my ( $class, $conf ) = @_;

    # Global session storage
    unless ( $class->tsv->{sessionStorageModule} = $conf->{globalStorage} ) {
        $class->logger->error("globalStorage required");
        return 0;
    }
    eval "use " . $class->tsv->{sessionStorageModule};
    die($@) if ($@);
    $class->tsv->{sessionStorageOptions} = $conf->{globalStorageOptions};

    # OIDC session storage
    if ( $conf->{oidcStorage} ) {
        eval "use " . $conf->{oidcStorage};
        die($@) if ($@);
        $class->tsv->{oidcStorageModule}  = $conf->{oidcStorage};
        $class->tsv->{oidcStorageOptions} = $conf->{oidcStorageOptions};

    }
    else {
        $class->tsv->{oidcStorageModule}  = $conf->{globalStorage};
        $class->tsv->{oidcStorageOptions} = $conf->{globalStorageOptions};
    }

    # Local session storage
    if ( $conf->{localSessionStorage} ) {
        $class->tsv->{sessionCacheModule} = $conf->{localSessionStorage};
        $class->tsv->{sessionCacheOptions} =
          $conf->{localSessionStorageOptions};
        $class->tsv->{sessionCacheOptions}->{default_expires_in} ||= 600;

        if ( $conf->{status} ) {
            my $params = "";
            if ( $class->tsv->{sessionCacheModule} ) {
                $params = $class->tsv->{sessionCacheModule} . ',{' . join(
                    ',',
                    map {
                        "$_ => '"
                          . $class->tsv->{sessionCacheOptions}->{$_} . "'"
                      }
                      keys %{ $class->tsv->{sessionCacheOptions} // {} }
                ) . '}';
            }
        }
    }
    return 1;
}

## @imethod void headersInit(hashRef args)
# Create the subroutines used to insert headers into the HTTP request.
# @param $args reference to the configuration hash
sub headersInit {
    my ( $class, $conf, $headers ) = @_;
    $headers ||= $conf->{exportedHeaders};

    # Creation of the subroutine which will generate headers
    foreach my $vhost ( keys %{$headers} ) {
        unless ($vhost) {
            $class->logger->warn('Empty vhost in headers, skipping');
            next;
        }
        $headers->{$vhost} ||= {};
        my %headers = %{ $headers->{$vhost} };
        $class->tsv->{headerList}->{$vhost} = [ keys %headers ];
        my $sub = '';
        foreach ( keys %headers ) {
            $headers{$_} ||= "''";
            my $val = $class->substitute( $headers{$_} ) . " // ''";
            $sub .= "('$_' => $val),";
        }

        unless ( $class->tsv->{forgeHeaders}->{$vhost} =
            $class->buildSub($sub) )
        {
            $class->tsv->{maintenance}->{$vhost} = 1;
            $class->logger->error( "$class Unable to forge $vhost headers: "
                  . $class->tsv->{jail}->error );
        }
    }
    return 1;
}

## @imethod protected void postUrlInit()
# Prepare methods to post form attributes
sub postUrlInit {
    my ( $class, $conf ) = @_;
    return unless ( $conf->{post} );

    # Browse all vhost
    foreach my $vhost ( keys %{ $conf->{post} } ) {

        #  Browse all POST URI
        foreach my $url ( keys %{ $conf->{post}->{$vhost} || {} } ) {
            my $d = $conf->{post}->{$vhost}->{$url};
            $class->logger->debug("Compiling POST data for $url");

            # Where to POST
            $d->{target} ||= $url;
            my $sub;
            $d->{vars} ||= [];
            foreach my $input ( @{ delete $d->{vars} } ) {
                $sub .=
                  "'$input->[0]' => " . $class->substitute( $input->[1] ) . ",";
            }
            unless (
                $class->tsv->{inputPostData}->{$vhost}->{ delete $d->{target} }
                = $class->tsv->{outputPostData}->{$vhost}->{$url} =
                $class->buildSub($sub) )
            {
                $class->tsv->{maintenance}->{$vhost} = 1;
                $class->logger->error( "$class: Unable to build post data: "
                      . $class->tsv->{jail}->error );
            }

            $class->tsv->{postFormParams}->{$vhost}->{$url} = $d;
        }
    }
    return 1;
}

## @imethod protected codeRef conditionSub(string cond)
# Returns a compiled function used to grant users (used by
# locationRulesInit(). The second value returned is a non null
# constant if URL is not protected (by "unprotect" or "skip"), 0 else.
# @param $cond The boolean expression to use
# @param $mainClass  optional
# @return array (ref(sub), int)
sub conditionSub {
    my ( $class, $cond ) = @_;
    $cond =~ s/\(\?#(\d+)\)$//;
    my ( $OK, $NOK ) = ( sub { 1 }, sub { 0 } );

    # Simple cases : accept and deny
    return ( $OK, 0 )
      if ( $cond =~ /^accept$/i );
    return ( $NOK, 0 )
      if ( $cond =~ /^deny$/i );

    # Cases unprotect and skip : 2nd value is 1 or 2
    return ( $OK, UNPROTECT )
      if ( $cond =~ /^unprotect$/i );
    return ( $OK, SKIP )
      if ( $cond =~ /^skip$/i );

    # Case logout
    if ( $cond =~ /^logout(?:_sso)?(?:\s+(.*))?$/i ) {
        my $url = $1;
        return (
            $url
            ? (
                sub {
                    my ( $req, $session ) = @_;
                    $session->{_logout} = $url;
                    return 0;
                },
                0
              )
            : (
                sub {
                    my ( $req, $session ) = @_;
                    $session->{_logout} = $class->tsv->{portal}->($req);
                    return 0;
                },
                0
            )
        );
    }

    # logout_app
    if ( $cond =~ /^logout_app(?:\s+(.*))?$/i ) {
        return $class->logout_app($1);
    }

    # logout_app_sso
    elsif ( $cond =~ /^logout_app_sso(?:\s+(.*))?$/i ) {
        return $class->logout_app_sso($1);
    }

    my $mayskip = 0;
    $mayskip = MAYSKIP if $cond =~ /\bskip\b/;

    # Replace some strings in condition
    $cond = $class->substitute($cond);
    my $sub;
    unless ( $sub = $class->buildSub($cond) ) {
        $class->logger->error( "$class: Unable to build condition ($cond): "
              . $class->tsv->{jail}->error );
    }

    # Return sub and protected flag
    return ( $sub, $mayskip );
}

## These methods should be overriden in subclasses
sub logout_app {
    return ( sub { 1 }, 0 );
}

sub logout_app_sso {
    return ( sub { 1 }, 0 );
}

## @method arrayref aliasInit
# @param options vhostOptions configuration item
# @return arrayref of vhost and aliases
sub aliasInit {
    my ( $class, $conf ) = @_;

    delete $class->tsv->{vhostAlias};
    foreach my $vhost ( keys %{ $conf->{vhostOptions} || {} } ) {
        if ( my $aliases = $conf->{vhostOptions}->{$vhost}->{vhostAliases} ) {
            foreach ( split /\s+/, $aliases ) {
                $class->tsv->{vhostAlias}->{$_} = $vhost;
                $class->logger->debug("Registering $_ as alias of $vhost");
            }
        }
    }
    return 1;
}

# TODO: support wildcards in aliases

## @method arrayref oauth2Init
# @param options vhostOptions configuration item
# @return arrayref of vhost and aliases
sub oauth2Init {
    my ( $class, $conf ) = @_;

    foreach my $rp ( keys %{ $conf->{oidcRPMetaDataOptions} || {} } ) {
        if (    $conf->{oidcRPMetaDataOptions}->{$rp}
            and $conf->{oidcRPMetaDataOptions}->{$rp}
            ->{oidcRPMetaDataOptionsClientID} )
        {
            $class->tsv->{oauth2Options}->{$rp}->{clientId} =
              $conf->{oidcRPMetaDataOptions}->{$rp}
              ->{oidcRPMetaDataOptionsClientID};
        }
    }
    return 1;
}

sub msgBrokerInit {
    my ( $class, $conf ) = @_;

    my $brokerClass = $conf->{messageBroker} || '::NoBroker';
    $brokerClass =~ s/^::/Lemonldap::NG::Common::MessageBroker::/;
    eval "require $brokerClass";
    die $@ if $@;
    $class->tsv->{msgBrokerReader} = $brokerClass->new( $conf, $class->logger );
    $class->tsv->{msgBrokerReader}->subscribe( $conf->{eventQueueName} );
    $class->tsv->{msgBrokerWriter} = $brokerClass->new( $conf, $class->logger );
}

sub substitute {
    my ( $class, $expr ) = @_;
    $expr //= '';

    # substitute special vars, just for retro-compatibility
    $expr =~ s/\$date\b/&date/sg;
    $expr =~ s/\$vhost\b/\$ENV{HTTP_HOST}/sg;
    $expr =~ s/\$ip\b/\$ENV{REMOTE_ADDR}/sg;

    # substitute vars with session data, excepts special vars $_ and $\d+
    $expr =~ s/\$(?!(?:ENV|env)\b)(_\w+|[a-zA-Z]\w*)/\$s->{$1}/sg;
    $expr =~ s/\$ENV\{/\$r->{env}->\{/g;
    $expr =~ s/\$env->\{/\$r->{env}->\{/g;
    $expr =~ s/\bskip\b/q\{999_SKIP\}/g;

    # handle inGroup
    $expr =~ s/\binGroup\(([^)]*)\)/listMatch(\$s->{'hGroups'},$1,1)/g;

    # handle has2f
    $expr =~ s/\bhas2f\(([^),]*)\)/has2f_internal(\$s,$1)/g;

    # handle inSubnet
    $expr =~ s/\binSubnet\(([^)]*)\)/ipInSubnet(\$r->{env}->{REMOTE_ADDR},$1)/g;

    # handle inSubnet
    $expr =~
      s/\binDomain\(([^)]*)\)/inDomain_internal(\$r->{env}->{HTTP_HOST},$1)/g;

    return $expr;
}

sub buildSub {
    my ( $class, $val ) = @_;
    my $res =
      $class->tsv->{jail}->jail_reval("sub{my (\$r,\$s)=\@_;return($val)}");
    unless ($res) {
        $class->logger->error( $class->tsv->{jail}->error );
    }
    return $res;
}

1;