| 1 | package AmberDB::Base; | ||
| 2 | |||
| 3 | use 5.016; | ||
| 4 | use warnings; | ||
| 5 | use Encode qw(is_utf8 encode decode); | ||
| 6 | use Carp qw(croak cluck); | ||
| 7 | use File::Spec; | ||
| 8 | use Fcntl qw(:DEFAULT :flock); | ||
| 9 | use Digest::SHA qw(sha256_hex); | ||
| 10 | use parent qw(AmberDB::Locale AmberDB::Array); | ||
| 11 | |||
| 12 | our $VERSION = '5.26.6'; | ||
| 13 | my $CREATED = '2014-12-20'; | ||
| 14 | |||
| 15 | # ------------------------------------------------ | ||
| 16 | sub new { | ||
| 17 | my $class = shift; | ||
| 18 | my %args = ( ref $_[0] eq 'HASH' ) ? %{ $_[0] } : @_; | ||
| 19 | |||
| 20 | # Initialise the Language engine with the supplied language tag. | ||
| 21 | # SUPER::new is AmberDB::Locale::new — it handles locale loading. | ||
| 22 | my $self = $class->SUPER::new(%args); | ||
| 23 | return $self; | ||
| 24 | } | ||
| 25 | |||
| 26 | # ============================================================================ | ||
| 27 | # STRING UTILITIES (Trim & Whitespace Normalization) | ||
| 28 | # ============================================================================ | ||
| 29 | |||
| 30 | # $adb->trim_space($string, [$flatten]) | ||
| 31 | # Strips leading/trailing whitespace and normalizes internal spaces/newlines. | ||
| 32 | # --------------------------------------------------------------------- | ||
| 33 | sub trim_space { | ||
| 34 | my ( $self, $string, $flatten ) = @_; | ||
| 35 | |||
| 36 | return '' unless defined $string && length $string; | ||
| 37 | |||
| 38 | $string =~ s/ / /g; | ||
| 39 | $string =~ s/^\s+//; | ||
| 40 | $string =~ s/\s+$//; | ||
| 41 | $string =~ s/\r\n/\n/g; | ||
| 42 | |||
| 43 | if ($flatten) { | ||
| 44 | $string =~ s/[\r\n\t\s]+/ /g; | ||
| 45 | $string =~ s/ *([,;]) */$1/g; | ||
| 46 | $string =~ s/^\s+//; | ||
| 47 | $string =~ s/\s+$//; | ||
| 48 | } | ||
| 49 | else { | ||
| 50 | $string =~ s/\n/\\n/g; | ||
| 51 | $string =~ s/\t/\\t/g; | ||
| 52 | $string =~ s/\s+/ /g; | ||
| 53 | $string =~ s/ *([,;]) */$1/g; | ||
| 54 | $string =~ s/ *\\n */\n/g; | ||
| 55 | $string =~ s/ *\\t */\t/g; | ||
| 56 | } | ||
| 57 | |||
| 58 | return $string; | ||
| 59 | } | ||
| 60 | |||
| 61 | # $data = $adb->set_charset($from, $to, $data); | ||
| 62 | # Converts between character encoding tables... | ||
| 63 | # ------------------------------------------------ | ||
| 64 | sub set_charset { | ||
| 65 | my ( $self, $from, $to, $data ) = @_; | ||
| 66 | |||
| 67 | ( $from && $to && $data ) or return; | ||
| 68 | |||
| 69 | return $data if ( $to eq "utf8" && utf8::is_utf8($data) ); | ||
| 70 | return encode( $to, decode( $from, $data ) ); | ||
| 71 | } | ||
| 72 | |||
| 73 | # Extracts search words from string... | ||
| 74 | # my %words = $self->get_words($string); | ||
| 75 | # my %words = $self->get_words($string, $write, $table); | ||
| 76 | # ------------------------------------------------ | ||
| 77 | sub get_words { | ||
| 78 | my ( $self, $string, $action, $table ) = @_; | ||
| 79 | |||
| 80 | $string or return; | ||
| 81 | |||
| 82 | if ( ref($string) eq 'ARRAY' ) { | ||
| 83 | $string = join " ", @$string; | ||
| 84 | } | ||
| 85 | |||
| 86 | my $is_write = ( $action && ( $action eq "write" || $action eq "1" ) ) ? 1 : 0; | ||
| 87 | |||
| 88 | # 1. En basta kelimeleri split et | ||
| 89 | my @tokens = split /\s+/, $string; | ||
| 90 | return () unless @tokens; | ||
| 91 | |||
| 92 | my %words; | ||
| 93 | my ( $minchar, %jump, $has_meta ); | ||
| 94 | |||
| 95 | foreach my $str (@tokens) { | ||
| 96 | next unless length $str; | ||
| 97 | |||
| 98 | # 2. Kelime bazinda cache kontrolu: $self->get_cache('gw', $rawword) => islenmis | ||
| 99 | my $str_val = $self->get_cache( 'gw', $str ); | ||
| 100 | |||
| 101 | if ( !defined $str_val ) { | ||
| 102 | # Cache'in altina alinan minchar ve stop_word ayarlari | ||
| 103 | if ( !$has_meta ) { | ||
| 104 | if ($table) { | ||
| 105 | my $table_info = $self->table_info($table); | ||
| 106 | if ( $table_info && $table_info->{stop_word} ) { | ||
| 107 | my $stop_word = $self->to_ascii( $table_info->{stop_word} ); | ||
| 108 | $stop_word = $self->trim_space($stop_word); | ||
| 109 | $stop_word = lc($stop_word); | ||
| 110 | %jump = map { $_ => 1 } split /\s+/, $stop_word; | ||
| 111 | } | ||
| 112 | $minchar = ( $table_info && $table_info->{min_char} ) ? $table_info->{min_char} : 2; | ||
| 113 | } | ||
| 114 | else { | ||
| 115 | $minchar = 2; | ||
| 116 | } | ||
| 117 | $has_meta = 1; | ||
| 118 | } | ||
| 119 | |||
| 120 | # Eger kelime minchar'dan kisa ise bosluk olarak cachele | ||
| 121 | if ( $minchar && length($str) < $minchar ) { | ||
| 122 | $self->set_cache( 'gw', $str, '' ); | ||
| 123 | next; | ||
| 124 | } | ||
| 125 | |||
| 126 | $str_val = $self->normalize_word( $str, $is_write ); | ||
| 127 | |||
| 128 | # mincharlari islerken onlari da bosluk olarak cachele | ||
| 129 | my @sub; | ||
| 130 | foreach my $w ( split /\s+/, $str_val ) { | ||
| 131 | next unless length $w; | ||
| 132 | if ( $minchar && length($w) < $minchar ) { | ||
| 133 | $self->set_cache( 'gw', $w, '' ); | ||
| 134 | next; | ||
| 135 | } | ||
| 136 | push @sub, $w; | ||
| 137 | } | ||
| 138 | $str_val = join( " ", @sub ); | ||
| 139 | $self->set_cache( 'gw', $str, $str_val ); | ||
| 140 | } | ||
| 141 | |||
| 142 | next unless length $str_val; | ||
| 143 | |||
| 144 | if ( $table && !$has_meta ) { | ||
| 145 | my $table_info = $self->table_info($table); | ||
| 146 | if ( $table_info && $table_info->{stop_word} ) { | ||
| 147 | my $stop_word = $self->to_ascii( $table_info->{stop_word} ); | ||
| 148 | $stop_word = $self->trim_space($stop_word); | ||
| 149 | $stop_word = lc($stop_word); | ||
| 150 | %jump = map { $_ => 1 } split /\s+/, $stop_word; | ||
| 151 | } | ||
| 152 | $has_meta = 1; | ||
| 153 | } | ||
| 154 | |||
| 155 | foreach my $w ( split /\s+/, $str_val ) { | ||
| 156 | next unless length $w; | ||
| 157 | if ( $jump{$w} ) { | ||
| 158 | $self->set_cache( 'gw', $w, '' ); | ||
| 159 | $self->set_cache( 'gw', $str, '' ) if $str eq $w; | ||
| 160 | next; | ||
| 161 | } | ||
| 162 | $words{$w} = $w; | ||
| 163 | } | ||
| 164 | } | ||
| 165 | |||
| 166 | return %words; | ||
| 167 | } | ||
| 168 | |||
| 169 | # ============================================================================ | ||
| 170 | |||
| 171 | |||
| 172 | # ============================================================================ | ||
| 173 | # FILESYSTEM DIRECTORY UTILITIES | ||
| 174 | # ============================================================================ | ||
| 175 | |||
| 176 | # $bool = $adb->dir_exist($dir); | ||
| 177 | # Checks if a directory, alias, symbolic link, or filesystem entry exists. | ||
| 178 | # ------------------------------------------------ | ||
| 179 | sub dir_exist { | ||
| 180 | my ( $self, $dir ) = @_; | ||
| 181 | |||
| 182 | return 0 unless defined $dir && length $dir; | ||
| 183 | return ( -d $dir || -l $dir || -e $dir ) ? 1 : 0; | ||
| 184 | } | ||
| 185 | |||
| 186 | # my @files = $adb->dir_files($dir, [$pattern], [%opts]); | ||
| 187 | # ------------------------------------------------ | ||
| 188 | sub dir_files { | ||
| 189 | my ( $self, $dir, $pattern, %opts ) = @_; | ||
| 190 | |||
| 191 | return () unless defined $dir && length($dir) && -d $dir; | ||
| 192 | |||
| 193 | my $full_path = $opts{full_path} // 1; | ||
| 194 | my $files_only = $opts{files_only} // 1; | ||
| 195 | my $do_sort = $opts{sort} // 1; | ||
| 196 | |||
| 197 | my $regex; | ||
| 198 | if ( defined $pattern && length($pattern) ) { | ||
| 199 | if ( ref($pattern) eq 'Regexp' ) { | ||
| 200 | $regex = $pattern; | ||
| 201 | } | ||
| 202 | else { | ||
| 203 | my $p = $pattern; | ||
| 204 | $p = quotemeta($p); | ||
| 205 | $p =~ s/\\\*/.*/g; | ||
| 206 | $p =~ s/\\\?/./g; | ||
| 207 | $regex = qr/^$p$/; | ||
| 208 | } | ||
| 209 | } | ||
| 210 | |||
| 211 | opendir my $dh, $dir or return (); | ||
| 212 | my @entries = grep { $_ ne '.' && $_ ne '..' } readdir($dh); | ||
| 213 | closedir $dh; | ||
| 214 | |||
| 215 | my @results; | ||
| 216 | foreach my $entry (@entries) { | ||
| 217 | if ( $regex ) { | ||
| 218 | next unless $entry =~ $regex; | ||
| 219 | } | ||
| 220 | |||
| 221 | my $path = File::Spec->catfile( $dir, $entry ); | ||
| 222 | if ( $files_only ) { | ||
| 223 | next unless -f $path; | ||
| 224 | } | ||
| 225 | |||
| 226 | push @results, $full_path ? $path : $entry; | ||
| 227 | } | ||
| 228 | |||
| 229 | return $do_sort ? sort { $a cmp $b } @results : @results; | ||
| 230 | } | ||
| 231 | |||
| 232 | # ============================================================================ | ||
| 233 | # RECORD SORTING BY ID (Fallback utility) | ||
| 234 | # ============================================================================ | ||
| 235 | |||
| 236 | # @liste = $self->db_sortid("_", @liste); # if no table | ||
| 237 | # @liste = $self->db_sortid("table_id", @liste); | ||
| 238 | # ------------------------------------------------ | ||
| 239 | sub db_sortid { | ||
| 240 | my ( $self, $table, @records ) = @_; | ||
| 241 | |||
| 242 | scalar @records or return (); | ||
| 243 | |||
| 244 | my $is_simple = $self->config('use_simple') || ( $table && $self->table_attr( $table, 'use_simple' ) ); | ||
| 245 | my $field = ( ref( $records[0] ) eq "ARRAY" ) ? 0 : undef; | ||
| 246 | my $sort_type = $is_simple ? 'ascii' : 'num'; | ||
| 247 | |||
| 248 | return $self->array_sort( $sort_type, 'desc', $field, @records ); | ||
| 249 | } | ||
| 250 | |||
| 251 | # ============================================================================ | ||
| 252 | # PATHS AND CONFIGURATION | ||
| 253 | # ============================================================================ | ||
| 254 | |||
| 255 | # $self->set_datadir("/path/to/dbase") | ||
| 256 | # ------------------------------------------------ | ||
| 257 | sub set_datadir { | ||
| 258 | my ( $self, $dbase_dir ) = @_; | ||
| 259 | |||
| 260 | $dbase_dir or return; | ||
| 261 | |||
| 262 | # declarations (persistent storage only; ramdisk directories are dynamically provisioned on mount) | ||
| 263 | my @dirs = qw( | ||
| 264 | dbase_dir table_dir schema_dir backup_dir | ||
| 265 | buffer_dir journal_dir lock_dir session_dir config_dir | ||
| 266 | ); | ||
| 267 | foreach my $dir (@dirs) { | ||
| 268 | $self->{_path}->{$dir} //= ""; | ||
| 269 | } | ||
| 270 | |||
| 271 | $self->{_path}->{dbase_dir} = $dbase_dir; | ||
| 272 | |||
| 273 | # db_ext tanımlı ve "db" değil ise simple moduna al | ||
| 274 | my $db_ext = $self->config('db_ext'); | ||
| 275 | if ( length($db_ext) && $db_ext ne "db" ) { | ||
| 276 | $self->config( use_simple => 1 ); | ||
| 277 | } | ||
| 278 | |||
| 279 | # do not proceed if simple mode | ||
| 280 | if ( $self->config('use_simple') ) { | ||
| 281 | $self->{_path}->{backup_dir} = $dbase_dir; | ||
| 282 | $self->{_path}->{buffer_dir} = $dbase_dir; | ||
| 283 | $self->{_path}->{journal_dir} = $dbase_dir; | ||
| 284 | $self->{_path}->{schema_dir} = $dbase_dir; | ||
| 285 | $self->{_path}->{table_dir} = $dbase_dir; | ||
| 286 | $self->{_path}->{lock_dir} = "$dbase_dir/lock"; | ||
| 287 | $self->{_path}->{session_dir} = "$dbase_dir/session"; | ||
| 288 | $self->{_path}->{config_dir} = "$dbase_dir/config"; | ||
| 289 | return 1; | ||
| 290 | } | ||
| 291 | |||
| 292 | $self->{_path}->{journal_dir} = "$dbase_dir/journal"; | ||
| 293 | $self->{_path}->{backup_dir} = "$dbase_dir/backup"; | ||
| 294 | $self->{_path}->{buffer_dir} = "$dbase_dir/buffer"; | ||
| 295 | $self->{_path}->{schema_dir} = "$dbase_dir/schema"; | ||
| 296 | $self->{_path}->{table_dir} = "$dbase_dir/table"; | ||
| 297 | $self->{_path}->{lock_dir} = "$dbase_dir/lock"; | ||
| 298 | $self->{_path}->{session_dir} = "$dbase_dir/session"; | ||
| 299 | $self->{_path}->{config_dir} = "$dbase_dir/config"; | ||
| 300 | |||
| 301 | # Auto-load connect.pl if present in datadir | ||
| 302 | my $conn_file = "$dbase_dir/config/connect.pl"; | ||
| 303 | if ( -f $conn_file ) { | ||
| 304 | my $target = ( $conn_file =~ m{^(?:\./|[a-zA-Z]:|/|\\)} ) ? $conn_file : "./$conn_file"; | ||
| 305 | my $cfg = do $target; | ||
| 306 | if ( $cfg && ref($cfg) eq 'HASH' && $cfg->{database} ) { | ||
| 307 | $self->{_connect}->{database} = $cfg->{database}; | ||
| 308 | } | ||
| 309 | } | ||
| 310 | |||
| 311 | unless ( $self->config('test') || $self->config('no_mkdir') || $^C ) { | ||
| 312 | if ( defined $dbase_dir && $dbase_dir ne "." && $dbase_dir ne "" ) { | ||
| 313 | for my $dir ( | ||
| 314 | $self->{_path}->{dbase_dir}, | ||
| 315 | $self->{_path}->{table_dir}, | ||
| 316 | $self->{_path}->{schema_dir}, | ||
| 317 | $self->{_path}->{backup_dir}, | ||
| 318 | $self->{_path}->{buffer_dir}, | ||
| 319 | $self->{_path}->{journal_dir}, | ||
| 320 | $self->{_path}->{lock_dir}, | ||
| 321 | $self->{_path}->{session_dir}, | ||
| 322 | ) { | ||
| 323 | if ( defined $dir && length($dir) && !$self->dir_exist($dir) ) { | ||
| 324 | $self->make_path($dir); | ||
| 325 | } | ||
| 326 | } | ||
| 327 | } | ||
| 328 | } | ||
| 329 | |||
| 330 | $self->ramdisk_setup() unless $^C || $self->config('no_mkdir'); | ||
| 331 | return 1; | ||
| 332 | } | ||
| 333 | |||
| 334 | # Utility method to create a directory path. | ||
| 335 | # ------------------------------------------------ | ||
| 336 | sub make_path { | ||
| 337 | my ( $self, $path ) = @_; | ||
| 338 | return 1 if $^C; | ||
| 339 | unless ( -d $path ) { | ||
| 340 | require File::Path; | ||
| 341 | File::Path::make_path($path); | ||
| 342 | } | ||
| 343 | return 1; | ||
| 344 | } | ||
| 345 | |||
| 346 | # my $cfg_val = $adb->config("language"); | ||
| 347 | # ------------------------------------------------ | ||
| 348 | sub config { | ||
| 349 | my ( $self, @args ) = @_; | ||
| 350 | |||
| 351 | # 1. No arguments: return shallow copy of all configuration | ||
| 352 | if ( !@args ) { | ||
| 353 | return { %{ $self->{_cfg} || {} } }; | ||
| 354 | } | ||
| 355 | |||
| 356 | # 2. Single scalar argument: getter -> $adb->config('language') | ||
| 357 | if ( @args == 1 && !ref( $args[0] ) ) { | ||
| 358 | my $key = $args[0]; | ||
| 359 | if ( $key eq 'user' ) { | ||
| 360 | return $self->{_connect}->{username} // $self->{_cfg}->{user} // 'user_system'; | ||
| 361 | } | ||
| 362 | if ( $key eq 'simple' || $key eq 'use_simple' ) { | ||
| 363 | return $self->{_cfg}->{use_simple} // ''; | ||
| 364 | } | ||
| 365 | return $self->{_cfg}->{ $key } // ''; | ||
| 366 | } | ||
| 367 | |||
| 368 | # 3. Setter: key-value list or hashref | ||
| 369 | my %pairs = ( @args == 1 && ref( $args[0] ) eq 'HASH' ) ? %{ $args[0] } : @args; | ||
| 370 | |||
| 371 | my $hooks = { | ||
| 372 | language => sub { | ||
| 373 | my $val = shift; | ||
| 374 | $self->{_cfg}->{language} = $val; | ||
| 375 | $self->_load_locale($val); | ||
| 376 | }, | ||
| 377 | db_ext => sub { | ||
| 378 | my $val = shift; | ||
| 379 | $self->{_cfg}->{db_ext} = $val; | ||
| 380 | $self->{db_ext} = $val; | ||
| 381 | if ( defined $val && $val ne "db" ) { | ||
| 382 | $self->{_cfg}->{use_simple} = 1; | ||
| 383 | } | ||
| 384 | $self->_invalidate_table_paths(); | ||
| 385 | }, | ||
| 386 | use_simple => sub { | ||
| 387 | my $val = shift; | ||
| 388 | $self->{_cfg}->{use_simple} = $val ? 1 : 0; | ||
| 389 | $self->_invalidate_table_paths(); | ||
| 390 | }, | ||
| 391 | simple => sub { | ||
| 392 | my $val = shift; | ||
| 393 | $self->{_cfg}->{use_simple} = $val ? 1 : 0; | ||
| 394 | $self->_invalidate_table_paths(); | ||
| 395 | }, | ||
| 396 | use_ramdisk => sub { | ||
| 397 | my $val = shift; | ||
| 398 | my $tier = $self->_normalize_ramdisk_tier($val); | ||
| 399 | if ( $tier == 3 ) { | ||
| 400 | $tier = 0; | ||
| 401 | } | ||
| 402 | $self->{_cfg}->{use_ramdisk} = $tier; | ||
| 403 | $self->_invalidate_table_paths(); | ||
| 404 | }, | ||
| 405 | }; | ||
| 406 | |||
| 407 | while ( my ( $key, $val ) = each %pairs ) { | ||
| 408 | if ( exists $hooks->{$key} ) { | ||
| 409 | $hooks->{$key}->($val); | ||
| 410 | } | ||
| 411 | else { | ||
| 412 | $self->{_cfg}->{$key} = $val; | ||
| 413 | if ( $key eq 'user' ) { | ||
| 414 | $self->{_connect}->{username} = $val; | ||
| 415 | } | ||
| 416 | } | ||
| 417 | } | ||
| 418 | |||
| 419 | return $self; | ||
| 420 | } | ||
| 421 | |||
| 422 | # my $dbase_dir = $adb->path("dbase_dir"); # getter | ||
| 423 | # $adb->path({ backup_dir => "$tmpdir/backup" }); # setter | ||
| 424 | # $adb->path( custom_path => "/opt/data" ); # setter | ||
| 425 | # ------------------------------------------------ | ||
| 426 | sub path { | ||
| 427 | my ( $self, @args ) = @_; | ||
| 428 | |||
| 429 | # 1. No arguments: return shallow copy of all path mappings | ||
| 430 | if ( !@args ) { | ||
| 431 | return { %{ $self->{_path} || {} } }; | ||
| 432 | } | ||
| 433 | |||
| 434 | # 2. Single scalar argument: getter -> $adb->path('dbase_dir') | ||
| 435 | if ( @args == 1 && !ref( $args[0] ) ) { | ||
| 436 | return $self->{_path}->{ $args[0] } // ''; | ||
| 437 | } | ||
| 438 | |||
| 439 | # 3. Setter: key-value list or hashref | ||
| 440 | my %pairs = ( @args == 1 && ref( $args[0] ) eq 'HASH' ) ? %{ $args[0] } : @args; | ||
| 441 | |||
| 442 | for my $key ( keys %pairs ) { | ||
| 443 | $self->{_path}->{$key} = $pairs{$key}; | ||
| 444 | } | ||
| 445 | $self->_invalidate_table_paths(); | ||
| 446 | |||
| 447 | return $self; | ||
| 448 | } | ||
| 449 | |||
| 450 | # Invalidate cached table paths if global path-affecting configurations change | ||
| 451 | # ------------------------------------------------ | ||
| 452 | sub _invalidate_table_paths { | ||
| 453 | my ($self) = @_; | ||
| 454 | |||
| 455 | if ( $self->{_table} && ref( $self->{_table} ) eq 'HASH' ) { | ||
| 456 | for my $tbl ( keys %{ $self->{_table} } ) { | ||
| 457 | delete $self->{_table}->{$tbl}->{_path} | ||
| 458 | if ref( $self->{_table}->{$tbl} ) eq 'HASH'; | ||
| 459 | } | ||
| 460 | } | ||
| 461 | } | ||
| 462 | |||
| 463 | # ============================================================================ | ||
| 464 | # AUTHENTICATION & PASSWORD CRYPTOGRAPHY (Salted SHA-256) | ||
| 465 | # ============================================================================ | ||
| 466 | |||
| 467 | # my $shadow = $adb->hash_password($password, [$salt]); | ||
| 468 | # --------------------------------------------------------------------- | ||
| 469 | sub hash_password { | ||
| 470 | my ( $self, $password, $salt ) = @_; | ||
| 471 | return '' unless defined $password && length $password; | ||
| 472 | |||
| 473 | # 16-character cryptographically secure hex salt | ||
| 474 | $salt //= sprintf( "%08x%08x", int( rand(0xFFFFFFFF) ), int( rand(0xFFFFFFFF) ) ); | ||
| 475 | |||
| 476 | my $hash = sha256_hex( $salt . $password ); | ||
| 477 | return "sha256\$$salt\$$hash"; | ||
| 478 | } | ||
| 479 | |||
| 480 | # my $ok = $adb->verify_password($password, $stored_shadow); | ||
| 481 | # --------------------------------------------------------------------- | ||
| 482 | sub verify_password { | ||
| 483 | my ( $self, $password, $stored_shadow ) = @_; | ||
| 484 | # Passwordless allowed if stored shadow is empty or undef | ||
| 485 | return 1 if !defined $stored_shadow || !length $stored_shadow; | ||
| 486 | $password //= ''; | ||
| 487 | |||
| 488 | my ( $algo, $salt, $expected ) = split /\$/, $stored_shadow; | ||
| 489 | return 0 unless defined $algo && defined $salt && defined $expected; | ||
| 490 | |||
| 491 | if ( $algo eq 'sha256' ) { | ||
| 492 | my $computed = sha256_hex( $salt . $password ); | ||
| 493 | return lc($computed) eq lc($expected) ? 1 : 0; | ||
| 494 | } | ||
| 495 | return $stored_shadow eq $password ? 1 : 0; | ||
| 496 | } | ||
| 497 | |||
| 498 | # ============================================================================ | ||
| 499 | # DATABASE CONNECTION & CLIENT AUTH PROFILE (connect.pl) | ||
| 500 | # ============================================================================ | ||
| 501 | |||
| 502 | sub _connect_file { | ||
| 503 | my ($self) = @_; | ||
| 504 | my $config_dir = $self->path('config_dir') || ( ( $self->path('dbase_dir') || "." ) . "/config" ); | ||
| 505 | return "$config_dir/connect.pl"; | ||
| 506 | } | ||
| 507 | |||
| 508 | sub _load_connect_config { | ||
| 509 | my ($self) = @_; | ||
| 510 | my $file = $self->_connect_file(); | ||
| 511 | return undef unless -f $file; | ||
| 512 | |||
| 513 | my $target = ( $file =~ m{^(?:\./|[a-zA-Z]:|/|\\)} ) ? $file : "./$file"; | ||
| 514 | my $data = do $target; | ||
| 515 | return undef unless ref($data) eq 'HASH'; | ||
| 516 | |||
| 517 | # Auto-upgrade: if any user entry or top-level entry has plain 'password', hash into 'shadow' and delete 'password' | ||
| 518 | my $modified = 0; | ||
| 519 | if ( defined $data->{password} && length $data->{password} ) { | ||
| 520 | $data->{shadow} = $self->hash_password( delete $data->{password} ); | ||
| 521 | $modified = 1; | ||
| 522 | } | ||
| 523 | if ( $data->{users} && ref( $data->{users} ) eq 'HASH' ) { | ||
| 524 | for my $u ( keys %{ $data->{users} } ) { | ||
| 525 | my $u_info = $data->{users}->{$u}; | ||
| 526 | next unless ref($u_info) eq 'HASH'; | ||
| 527 | if ( defined $u_info->{password} && length $u_info->{password} ) { | ||
| 528 | $u_info->{shadow} = $self->hash_password( delete $u_info->{password} ); | ||
| 529 | $modified = 1; | ||
| 530 | } | ||
| 531 | } | ||
| 532 | } | ||
| 533 | if ($modified) { | ||
| 534 | $self->_save_connect_config($data); | ||
| 535 | } | ||
| 536 | |||
| 537 | return $data; | ||
| 538 | } | ||
| 539 | |||
| 540 | sub _save_connect_config { | ||
| 541 | my ( $self, $data ) = @_; | ||
| 542 | my $file = $self->_connect_file(); | ||
| 543 | return unless defined $file && ref($data) eq 'HASH'; | ||
| 544 | |||
| 545 | my ($dir) = $file =~ m{^(.+)[/\\][^/\\]+$}; | ||
| 546 | $self->make_path($dir) if $dir && !$self->dir_exist($dir); | ||
| 547 | |||
| 548 | require Data::Dumper; | ||
| 549 | local $Data::Dumper::Terse = 1; | ||
| 550 | local $Data::Dumper::Indent = 1; | ||
| 551 | local $Data::Dumper::Sortkeys = 1; | ||
| 552 | my $dump = Data::Dumper::Dumper($data); | ||
| 553 | $dump =~ s/^\s+|\s+$//g; | ||
| 554 | |||
| 555 | if ( open my $fh, '>', $file ) { | ||
| 556 | print $fh "# AmberDB Database Connection & Client Auth Profile\n"; | ||
| 557 | print $fh "return " . $dump . ";\n"; | ||
| 558 | close $fh; | ||
| 559 | return 1; | ||
| 560 | } | ||
| 561 | return 0; | ||
| 562 | } | ||
| 563 | |||
| 564 | # my $sess_path = $adb->session_file($token); | ||
| 565 | # --------------------------------------------------------------------- | ||
| 566 | sub session_file { | ||
| 567 | my ( $self, $token ) = @_; | ||
| 568 | return '' unless defined $token && length $token; | ||
| 569 | my $session_dir = $self->path('session_dir') || ( ( $self->path('dbase_dir') || "." ) . "/session" ); | ||
| 570 | return "$session_dir/cli_$token"; | ||
| 571 | } | ||
| 572 | |||
| 573 | # my $token = $adb->generate_token(); | ||
| 574 | # --------------------------------------------------------------------- | ||
| 575 | sub generate_token { | ||
| 576 | my ($self) = @_; | ||
| 577 | for ( 1 .. 1000 ) { | ||
| 578 | my $token = sprintf( "%04d", int( rand(9000) ) + 1000 ); | ||
| 579 | my $sf = $self->session_file($token); | ||
| 580 | next if $sf && -f $sf; | ||
| 581 | my $cf = ".amberdb/session/sess_$token"; | ||
| 582 | next if -f $cf; | ||
| 583 | return $token; | ||
| 584 | } | ||
| 585 | return sprintf( "%04d", int( rand(9000) ) + 1000 ); | ||
| 586 | } | ||
| 587 | |||
| 588 | sub _load_session { | ||
| 589 | my ( $self, $token ) = @_; | ||
| 590 | return undef unless defined $token && length $token; | ||
| 591 | my @files = ( $self->session_file($token), ".amberdb/session/sess_$token" ); | ||
| 592 | |||
| 593 | for my $sf (@files) { | ||
| 594 | next unless $sf && -f $sf; | ||
| 595 | my $target = ( $sf =~ m{^(?:\./|[a-zA-Z]:|/|\\)} ) ? $sf : "./$sf"; | ||
| 596 | my $data = do $target; | ||
| 597 | return $data if ref($data) eq 'HASH'; | ||
| 598 | |||
| 599 | if ( open my $fh, '<', $sf ) { | ||
| 600 | local $/; | ||
| 601 | my $raw = <$fh>; | ||
| 602 | close $fh; | ||
| 603 | if ( $raw && $raw =~ /^\s*\{/ ) { | ||
| 604 | require JSON::PP; | ||
| 605 | my $jdata = eval { JSON::PP::decode_json($raw) }; | ||
| 606 | return $jdata if $jdata && ref($jdata) eq 'HASH'; | ||
| 607 | } | ||
| 608 | } | ||
| 609 | } | ||
| 610 | return undef; | ||
| 611 | } | ||
| 612 | |||
| 613 | sub _save_session { | ||
| 614 | my ( $self, $token, $data ) = @_; | ||
| 615 | return unless defined $token && length $token; | ||
| 616 | my $sf = $self->session_file($token); | ||
| 617 | return unless $sf; | ||
| 618 | |||
| 619 | my ($dir) = $sf =~ m{^(.+)[/\\][^/\\]+$}; | ||
| 620 | $self->make_path($dir) if $dir && !$self->dir_exist($dir); | ||
| 621 | |||
| 622 | require Data::Dumper; | ||
| 623 | local $Data::Dumper::Terse = 1; | ||
| 624 | local $Data::Dumper::Indent = 1; | ||
| 625 | local $Data::Dumper::Sortkeys = 1; | ||
| 626 | my $dump = Data::Dumper::Dumper($data); | ||
| 627 | $dump =~ s/^\s+|\s+$//g; | ||
| 628 | |||
| 629 | if ( open my $fh, '>', $sf ) { | ||
| 630 | print $fh "# AmberDB Active CLI Session Token: $token\n"; | ||
| 631 | print $fh "return " . $dump . ";\n"; | ||
| 632 | close $fh; | ||
| 633 | } | ||
| 634 | |||
| 635 | # Also sync local .amberdb/session/sess_$token | ||
| 636 | my $local_dir = ".amberdb/session"; | ||
| 637 | $self->make_path($local_dir) unless -d $local_dir; | ||
| 638 | my $local_file = "$local_dir/sess_$token"; | ||
| 639 | if ( open my $lfh, '>', $local_file ) { | ||
| 640 | require JSON::PP; | ||
| 641 | print $lfh JSON::PP::encode_json($data); | ||
| 642 | close $lfh; | ||
| 643 | } | ||
| 644 | |||
| 645 | return 1; | ||
| 646 | } | ||
| 647 | |||
| 648 | sub _delete_session { | ||
| 649 | my ( $self, $token ) = @_; | ||
| 650 | return unless defined $token && length $token; | ||
| 651 | my $sf = $self->session_file($token); | ||
| 652 | unlink $sf if $sf && -f $sf; | ||
| 653 | my $local_file = ".amberdb/session/sess_$token"; | ||
| 654 | unlink $local_file if -f $local_file; | ||
| 655 | } | ||
| 656 | |||
| 657 | # my $val_or_token = $adb->connect([$key | %args]); | ||
| 658 | # --------------------------------------------------------------------- | ||
| 659 | sub connect { | ||
| 660 | my ( $self, @args ) = @_; | ||
| 661 | |||
| 662 | # 1. Single scalar argument: attribute getter -> $adb->connect('database') | ||
| 663 | if ( @args == 1 && !ref( $args[0] ) ) { | ||
| 664 | my $k = $args[0]; | ||
| 665 | $k = 'database' if $k eq 'dbase' || $k eq 'dbname'; | ||
| 666 | $k = 'username' if $k eq 'user' || $k eq 'usr'; | ||
| 667 | $k = 'password' if $k eq 'pass' || $k eq 'passwd'; | ||
| 668 | return $self->{_connect}->{$k} // ''; | ||
| 669 | } | ||
| 670 | |||
| 671 | # If called with no args and already connected with valid token, return active token | ||
| 672 | if ( !@args && defined $self->{_connect}->{token} && length $self->{_connect}->{token} ) { | ||
| 673 | return $self->{_connect}->{token}; | ||
| 674 | } | ||
| 675 | |||
| 676 | # 2. Connection / Authentication Action -> $adb->connect(%args) or $adb->connect() | ||
| 677 | my %opts = ( @args == 1 && ref( $args[0] ) eq 'HASH' ) ? %{ $args[0] } : @args; | ||
| 678 | |||
| 679 | my $token = delete $opts{token} // delete $opts{tok}; | ||
| 680 | my $database = delete $opts{database} // delete $opts{dbase} // delete $opts{dbname} // delete $opts{db} // $self->{_connect}->{database}; | ||
| 681 | my $username = delete $opts{username} // delete $opts{user} // delete $opts{usr} // $self->{_connect}->{username}; | ||
| 682 | my $password = delete $opts{password} // delete $opts{pass} // delete $opts{passwd} // $self->{_connect}->{password}; | ||
| 683 | |||
| 684 | # Sub-case A: Resume session via token | ||
| 685 | if ( defined $token && length $token ) { | ||
| 686 | my $sess = $self->_load_session($token); | ||
| 687 | if ( $sess && ref($sess) eq 'HASH' ) { | ||
| 688 | $self->{_connect}->{token} = $token; | ||
| 689 | $self->{_connect}->{database} = $sess->{connect}->{database} // $sess->{database} // $self->{_connect}->{database} // ''; | ||
| 690 | $self->{_connect}->{username} = $sess->{connect}->{username} // $sess->{username} // $self->{_connect}->{username} // 'user_system'; | ||
| 691 | $self->{_connect}->{password} = $sess->{connect}->{password} // $sess->{password} // ''; | ||
| 692 | $self->{_cfg}->{user} = $self->{_connect}->{username}; | ||
| 693 | return $token; | ||
| 694 | } | ||
| 695 | return undef; | ||
| 696 | } | ||
| 697 | |||
| 698 | # Sub-case B: Authenticate credentials & generate session token | ||
| 699 | my $connect_cfg = $self->_load_connect_config(); | ||
| 700 | |||
| 701 | # Database default if not specified in connect | ||
| 702 | if ( !defined $database || !length $database ) { | ||
| 703 | if ( $connect_cfg && $connect_cfg->{database} ) { | ||
| 704 | $database = $connect_cfg->{database}; | ||
| 705 | } | ||
| 706 | else { | ||
| 707 | $database = 'amberdb'; | ||
| 708 | } | ||
| 709 | } | ||
| 710 | |||
| 711 | |||
| 712 | $username //= 'cli'; | ||
| 713 | $password //= ''; | ||
| 714 | |||
| 715 | # Bootstrap connect.pl on first connection if missing or empty | ||
| 716 | if ( !$connect_cfg || !ref($connect_cfg->{users}) || !keys %{ $connect_cfg->{users} } ) { | ||
| 717 | $connect_cfg = { | ||
| 718 | database => $database, | ||
| 719 | created_at => time(), | ||
| 720 | users => { | ||
| 721 | $username => { | ||
| 722 | shadow => ( defined $password && length $password ) ? $self->hash_password($password) : '', | ||
| 723 | role => 'admin', | ||
| 724 | }, | ||
| 725 | web => { | ||
| 726 | shadow => '', | ||
| 727 | role => 'web', | ||
| 728 | }, | ||
| 729 | cli => { | ||
| 730 | shadow => '', | ||
| 731 | role => 'cli', | ||
| 732 | }, | ||
| 733 | }, | ||
| 734 | }; | ||
| 735 | $self->_save_connect_config($connect_cfg); | ||
| 736 | } | ||
| 737 | else { | ||
| 738 | # Check database mismatch if specified | ||
| 739 | if ( $connect_cfg->{database} && $database && lc($connect_cfg->{database}) ne lc($database) ) { | ||
| 740 | croak "[AMBERDB_AUTH_ERROR] Database mismatch: requested '$database' but store is '$connect_cfg->{database}'"; | ||
| 741 | } | ||
| 742 | $database = $connect_cfg->{database} if $connect_cfg->{database}; | ||
| 743 | |||
| 744 | # Check user | ||
| 745 | my $user_info = $connect_cfg->{users}->{$username}; | ||
| 746 | if ( !$user_info ) { | ||
| 747 | croak "[AMBERDB_AUTH_ERROR] User '$username' not authorized for database '$database'"; | ||
| 748 | } | ||
| 749 | |||
| 750 | # Auto-upgrade plain text password in connect.pl to shadow if present | ||
| 751 | if ( exists $user_info->{password} && defined $user_info->{password} && length $user_info->{password} ) { | ||
| 752 | my $plain = delete $user_info->{password}; | ||
| 753 | $user_info->{shadow} = $self->hash_password($plain); | ||
| 754 | $self->_save_connect_config($connect_cfg); | ||
| 755 | } | ||
| 756 | |||
| 757 | # Password check: | ||
| 758 | # If both shadow and password are empty/missing: passwordless access allowed (local trust / backwards compat) | ||
| 759 | my $shadow = $user_info->{shadow} // ''; | ||
| 760 | if ( length $shadow ) { | ||
| 761 | if ( !defined $password || !length $password ) { | ||
| 762 | croak "[AMBERDB_AUTH_ERROR] Password required for user '$username'"; | ||
| 763 | } | ||
| 764 | if ( !$self->verify_password( $password, $shadow ) ) { | ||
| 765 | croak "[AMBERDB_AUTH_ERROR] Invalid password for user '$username'"; | ||
| 766 | } | ||
| 767 | } | ||
| 768 | } | ||
| 769 | |||
| 770 | # Authentication successful: issue token | ||
| 771 | my $new_token = $self->generate_token(); | ||
| 772 | $self->{_connect}->{database} = $database; | ||
| 773 | $self->{_connect}->{username} = $username; | ||
| 774 | $self->{_connect}->{password} = $password; | ||
| 775 | $self->{_connect}->{token} = $new_token; | ||
| 776 | $self->{_cfg}->{user} = $username; | ||
| 777 | |||
| 778 | # Save session | ||
| 779 | my $sess_data = { | ||
| 780 | token => $new_token, | ||
| 781 | created_at => time(), | ||
| 782 | updated_at => time(), | ||
| 783 | connect => { | ||
| 784 | database => $database, | ||
| 785 | username => $username, | ||
| 786 | }, | ||
| 787 | path => { %{ $self->path() } }, | ||
| 788 | cfg => { %{ $self->config() } }, | ||
| 789 | }; | ||
| 790 | $self->_save_session( $new_token, $sess_data ); | ||
| 791 | |||
| 792 | return $new_token; | ||
| 793 | } | ||
| 794 | |||
| 795 | sub disconnect { | ||
| 796 | my ( $self, $token ) = @_; | ||
| 797 | $token //= $self->{_connect}->{token}; | ||
| 798 | if ( defined $token && length $token ) { | ||
| 799 | $self->_delete_session($token); | ||
| 800 | } | ||
| 801 | $self->{_connect}->{token} = ''; | ||
| 802 | $self->{_connect}->{password} = ''; | ||
| 803 | return 1; | ||
| 804 | } | ||
| 805 | |||
| 806 | # ============================================================================ | ||
| 807 | # USER MANAGEMENT METHODS (connect.pl API) | ||
| 808 | # ============================================================================ | ||
| 809 | |||
| 810 | sub user_add { | ||
| 811 | my ( $self, $username, $password, %opts ) = @_; | ||
| 812 | croak "Username required" unless defined $username && length $username; | ||
| 813 | |||
| 814 | my $cfg = $self->_load_connect_config() // { database => $self->connect('database') || 'amberdb', users => {} }; | ||
| 815 | $cfg->{users} //= {}; | ||
| 816 | |||
| 817 | my $shadow = ( defined $password && length $password ) ? $self->hash_password($password) : ''; | ||
| 818 | $cfg->{users}->{$username} = { | ||
| 819 | shadow => $shadow, | ||
| 820 | role => $opts{role} // 'user', | ||
| 821 | created_at => time(), | ||
| 822 | }; | ||
| 823 | $self->_save_connect_config($cfg); | ||
| 824 | return 1; | ||
| 825 | } | ||
| 826 | |||
| 827 | sub user_passwd { | ||
| 828 | my ( $self, $username, $password ) = @_; | ||
| 829 | croak "Username required" unless defined $username && length $username; | ||
| 830 | |||
| 831 | my $cfg = $self->_load_connect_config(); | ||
| 832 | croak "Database connection config not found" unless $cfg && $cfg->{users}->{$username}; | ||
| 833 | |||
| 834 | $cfg->{users}->{$username}->{shadow} = ( defined $password && length $password ) ? $self->hash_password($password) : ''; | ||
| 835 | $cfg->{users}->{$username}->{updated_at} = time(); | ||
| 836 | $self->_save_connect_config($cfg); | ||
| 837 | return 1; | ||
| 838 | } | ||
| 839 | |||
| 840 | sub user_del { | ||
| 841 | my ( $self, $username ) = @_; | ||
| 842 | croak "Username required" unless defined $username && length $username; | ||
| 843 | |||
| 844 | my $cfg = $self->_load_connect_config(); | ||
| 845 | return 0 unless $cfg && exists $cfg->{users}->{$username}; | ||
| 846 | |||
| 847 | delete $cfg->{users}->{$username}; | ||
| 848 | $self->_save_connect_config($cfg); | ||
| 849 | return 1; | ||
| 850 | } | ||
| 851 | |||
| 852 | sub user_list { | ||
| 853 | my ($self) = @_; | ||
| 854 | my $cfg = $self->_load_connect_config(); | ||
| 855 | return () unless $cfg && ref($cfg->{users}) eq 'HASH'; | ||
| 856 | |||
| 857 | my @list; | ||
| 858 | for my $u ( sort keys %{ $cfg->{users} } ) { | ||
| 859 | my $ud = $cfg->{users}->{$u}; | ||
| 860 | push @list, { | ||
| 861 | username => $u, | ||
| 862 | role => $ud->{role} // 'user', | ||
| 863 | has_password => ( defined $ud->{shadow} && length $ud->{shadow} ) ? 1 : 0, | ||
| 864 | created_at => $ud->{created_at} // 0, | ||
| 865 | }; | ||
| 866 | } | ||
| 867 | return @list; | ||
| 868 | } | ||
| 869 | |||
| 870 | sub user_verify { | ||
| 871 | my ( $self, $username, $password ) = @_; | ||
| 872 | return 0 unless defined $username && length $username; | ||
| 873 | |||
| 874 | my $cfg = $self->_load_connect_config(); | ||
| 875 | return 0 unless $cfg && ref($cfg->{users}) eq 'HASH'; | ||
| 876 | |||
| 877 | my $ud = $cfg->{users}->{$username}; | ||
| 878 | return 0 unless $ud; | ||
| 879 | |||
| 880 | my $shadow = $ud->{shadow} // ''; | ||
| 881 | return 1 if !length($shadow); # Passwordless allowed | ||
| 882 | return 0 unless defined $password && length $password; | ||
| 883 | return $self->verify_password( $password, $shadow ); | ||
| 884 | } | ||
| 885 | |||
| 886 | # my ($count, @records) = $adb->recs_cutting($offset, $limit, @records); | ||
| 887 | # ------------------------------------------------ | ||
| 888 | sub recs_cutting { | ||
| 889 | my ( $self, $offset, $limit, @records ) = @_; | ||
| 890 | |||
| 891 | $offset ||= 0; | ||
| 892 | $limit ||= 0; | ||
| 893 | $offset = 0 if $offset < 0; | ||
| 894 | my $count = scalar @records; | ||
| 895 | return ( $count, @records ) unless $limit; | ||
| 896 | |||
| 897 | my $end = ( $offset + $limit ) > $count ? $count : ( $offset + $limit ); | ||
| 898 | @records = @records[ $offset .. ( $end - 1 ) ]; | ||
| 899 | |||
| 900 | return ( $count, @records ); | ||
| 901 | } | ||
| 902 | |||
| 903 | # Minimal date helper without external dependencies. | ||
| 904 | # Populates $self->{date}: year, day_id, minute_id, second_id, str | ||
| 905 | # ------------------------------------------------ | ||
| 906 | sub init_date { | ||
| 907 | my ($self) = @_; | ||
| 908 | |||
| 909 | if ( $self->can('get_date') ) { | ||
| 910 | $self->{date} = $self->get_date(); | ||
| 911 | } | ||
| 912 | else { | ||
| 913 | my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime(time); | ||
| 914 | $year += 1900; | ||
| 915 | $mon += 1; | ||
| 916 | |||
| 917 | my $month = sprintf "%02d", $mon; | ||
| 918 | my $day = sprintf "%02d", $mday; | ||
| 919 | my $hr = sprintf "%02d", $hour; | ||
| 920 | my $mn = sprintf "%02d", $min; | ||
| 921 | my $sc = sprintf "%02d", $sec; | ||
| 922 | |||
| 923 | $self->{date} = { | ||
| 924 | year => $year, | ||
| 925 | day_id => "${year}${month}${day}", | ||
| 926 | minute_id => "${year}${month}${day}${hr}${mn}", | ||
| 927 | second_id => "${year}${month}${day}${hr}${mn}${sc}", | ||
| 928 | str => "${day}/${month}/${year} - ${hr}:${mn}:${sc}", | ||
| 929 | }; | ||
| 930 | } | ||
| 931 | |||
| 932 | return $self->{date}; | ||
| 933 | } | ||
| 934 | |||
| 935 | # ============================================================================ | ||
| 936 | # JOURNAL FILE OPERATIONS (Streaming Append, Safe Read, Atomic Rotate) | ||
| 937 | # Default Directory: $dbase_dir/journal/ | ||
| 938 | # File Naming: | ||
| 939 | # Active Queue: dbstore/journal/sync_ramdisk | ||
| 940 | # Rotated Queue: dbstore/journal/sync_ramdisk_1741512300 | ||
| 941 | # Transaction: dbstore/journal/txn_1741512300_1_4820 | ||
| 942 | # ============================================================================ | ||
| 943 | |||
| 944 | sub journal_dir { | ||
| 945 | my ($self) = @_; | ||
| 946 | my $dir = $self->path('journal_dir') | ||
| 947 | || ( ( $self->path('dbase_dir') || "." ) . "/journal" ); | ||
| 948 | $dir =~ s{[\\/]+$}{}; | ||
| 949 | unless ( -d $dir ) { | ||
| 950 | $self->make_path($dir); | ||
| 951 | } | ||
| 952 | return $dir; | ||
| 953 | } | ||
| 954 | |||
| 955 | sub journal_slot { | ||
| 956 | my ( $self, $name ) = @_; | ||
| 957 | $name //= 'journal'; | ||
| 958 | |||
| 959 | my $jdir = $self->journal_dir(); | ||
| 960 | |||
| 961 | my $prefix = ''; | ||
| 962 | if ( $self->config('use_section') ) { | ||
| 963 | $prefix = ( $self->config('section') // "center" ) . "-"; | ||
| 964 | } | ||
| 965 | |||
| 966 | my $file_name = "${prefix}${name}"; | ||
| 967 | return wantarray ? ( $jdir, $file_name ) : "$jdir/$file_name"; | ||
| 968 | } | ||
| 969 | |||
| 970 | sub _resolve_journal_path { | ||
| 971 | my ( $self, $target ) = @_; | ||
| 972 | return unless defined $target && length $target; | ||
| 973 | |||
| 974 | if ( $target =~ m{[/\\]} ) { | ||
| 975 | return $target; | ||
| 976 | } | ||
| 977 | return $self->journal_slot($target); | ||
| 978 | } | ||
| 979 | |||
| 980 | sub journal_append { | ||
| 981 | my ( $self, $slot_or_path, @entries ) = @_; | ||
| 982 | |||
| 983 | my $target_path = $self->_resolve_journal_path($slot_or_path); | ||
| 984 | return unless defined $target_path && length $target_path; | ||
| 985 | return unless @entries; | ||
| 986 | |||
| 987 | my $lock_file = "${target_path}.lock"; | ||
| 988 | open my $lfh, '>>', $lock_file or do { | ||
| 989 | cluck "[DB_JOURNAL] Cannot open lock file $lock_file: $!\n"; | ||
| 990 | return; | ||
| 991 | }; | ||
| 992 | flock( $lfh, LOCK_EX ); | ||
| 993 | |||
| 994 | open my $fh, '>>', $target_path or do { | ||
| 995 | flock( $lfh, LOCK_UN ); | ||
| 996 | close $lfh; | ||
| 997 | cluck "[DB_JOURNAL] Cannot open $target_path for append: $!\n"; | ||
| 998 | return; | ||
| 999 | }; | ||
| 1000 | |||
| 1001 | foreach my $item (@entries) { | ||
| 1002 | my $line; | ||
| 1003 | if ( ref($item) eq 'ARRAY' ) { | ||
| 1004 | $line = $self->journal_encode( @$item ); | ||
| 1005 | } | ||
| 1006 | else { | ||
| 1007 | $line = "$item"; | ||
| 1008 | } | ||
| 1009 | chomp $line; | ||
| 1010 | print $fh "$line\n"; | ||
| 1011 | } | ||
| 1012 | |||
| 1013 | $fh->flush; | ||
| 1014 | close $fh; | ||
| 1015 | |||
| 1016 | flock( $lfh, LOCK_UN ); | ||
| 1017 | close $lfh; | ||
| 1018 | |||
| 1019 | return 1; | ||
| 1020 | } | ||
| 1021 | |||
| 1022 | sub journal_read { | ||
| 1023 | my ( $self, $slot_or_path ) = @_; | ||
| 1024 | |||
| 1025 | my $target_path = $self->_resolve_journal_path($slot_or_path); | ||
| 1026 | return () unless defined $target_path && -e $target_path; | ||
| 1027 | |||
| 1028 | my $lock_file = "${target_path}.lock"; | ||
| 1029 | my $lfh; | ||
| 1030 | if ( -e $lock_file ) { | ||
| 1031 | open $lfh, '<', $lock_file; | ||
| 1032 | flock( $lfh, LOCK_SH ) if $lfh; | ||
| 1033 | } | ||
| 1034 | |||
| 1035 | open my $fh, '<', $target_path or do { | ||
| 1036 | if ($lfh) { flock( $lfh, LOCK_UN ); close $lfh; } | ||
| 1037 | cluck "[DB_JOURNAL] Cannot open $target_path for read: $!\n"; | ||
| 1038 | return (); | ||
| 1039 | }; | ||
| 1040 | |||
| 1041 | my @lines = <$fh>; | ||
| 1042 | close $fh; | ||
| 1043 | |||
| 1044 | if ($lfh) { | ||
| 1045 | flock( $lfh, LOCK_UN ); | ||
| 1046 | close $lfh; | ||
| 1047 | } | ||
| 1048 | |||
| 1049 | my @records; | ||
| 1050 | for my $line (@lines) { | ||
| 1051 | my $rec = $self->journal_decode($line); | ||
| 1052 | push @records, $rec if $rec; | ||
| 1053 | } | ||
| 1054 | |||
| 1055 | return @records; | ||
| 1056 | } | ||
| 1057 | |||
| 1058 | sub journal_rotate { | ||
| 1059 | my ( $self, $slot_or_path, $epoch ) = @_; | ||
| 1060 | |||
| 1061 | my $target_path = $self->_resolve_journal_path($slot_or_path); | ||
| 1062 | return unless defined $target_path && -e $target_path && -s $target_path; | ||
| 1063 | |||
| 1064 | my $lock_file = "${target_path}.lock"; | ||
| 1065 | open my $lfh, '>>', $lock_file or return; | ||
| 1066 | flock( $lfh, LOCK_EX ); | ||
| 1067 | |||
| 1068 | unless ( -e $target_path && -s $target_path ) { | ||
| 1069 | flock( $lfh, LOCK_UN ); | ||
| 1070 | close $lfh; | ||
| 1071 | return; | ||
| 1072 | } | ||
| 1073 | |||
| 1074 | $epoch //= time(); | ||
| 1075 | my $base_rotated = "${target_path}_${epoch}"; | ||
| 1076 | my $rotated_path = $base_rotated; | ||
| 1077 | my $counter = 1; | ||
| 1078 | while ( -e $rotated_path ) { | ||
| 1079 | $rotated_path = "${base_rotated}_${counter}"; | ||
| 1080 | $counter++; | ||
| 1081 | } | ||
| 1082 | |||
| 1083 | my $ok = rename( $target_path, $rotated_path ); | ||
| 1084 | |||
| 1085 | flock( $lfh, LOCK_UN ); | ||
| 1086 | close $lfh; | ||
| 1087 | |||
| 1088 | return $ok ? $rotated_path : undef; | ||
| 1089 | } | ||
| 1090 | |||
| 1091 | sub journal_delete { | ||
| 1092 | my ( $self, $slot_or_path ) = @_; | ||
| 1093 | |||
| 1094 | my $target_path = $self->_resolve_journal_path($slot_or_path); | ||
| 1095 | return unless defined $target_path; | ||
| 1096 | |||
| 1097 | if ( -e $target_path ) { | ||
| 1098 | unlink $target_path; | ||
| 1099 | } | ||
| 1100 | my $lock_file = "${target_path}.lock"; | ||
| 1101 | if ( -e $lock_file ) { | ||
| 1102 | unlink $lock_file; | ||
| 1103 | } | ||
| 1104 | return 1; | ||
| 1105 | } | ||
| 1106 | |||
| 1107 | sub journal_scan { | ||
| 1108 | my ( $self, $prefix ) = @_; | ||
| 1109 | $prefix //= 'sync_ramdisk_'; | ||
| 1110 | |||
| 1111 | my $jdir = $self->journal_dir(); | ||
| 1112 | return () unless -d $jdir; | ||
| 1113 | |||
| 1114 | my $sec_prefix = ''; | ||
| 1115 | if ( $self->config('use_section') ) { | ||
| 1116 | $sec_prefix = ( $self->config('section') // "center" ) . "-"; | ||
| 1117 | } | ||
| 1118 | my $full_prefix = "${sec_prefix}${prefix}"; | ||
| 1119 | |||
| 1120 | opendir my $dh, $jdir or return (); | ||
| 1121 | my @found; | ||
| 1122 | while ( my $f = readdir($dh) ) { | ||
| 1123 | next if $f eq '.' || $f eq '..' || $f =~ /\.lock$/; | ||
| 1124 | if ( index($f, $full_prefix) == 0 && $f =~ /_\d+(?:_\d+)?$/ ) { | ||
| 1125 | push @found, "$jdir/$f"; | ||
| 1126 | } | ||
| 1127 | } | ||
| 1128 | closedir $dh; | ||
| 1129 | |||
| 1130 | return sort @found; | ||
| 1131 | } | ||
| 1132 | |||
| 1133 | 1; |