blib/lib/IPC/LockTicket.pm untested

filter: Statementstmt 0.0% 0 / 362 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 108 MC/DCmcdc 0.0% 0 / 65 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 695 CC 55 SCAR 42.9
CC
55
Cov
0%
_Check
240.0
MainLock
90.0
SetCustomData
72.0
CRAP 72.7
1 #!/usr/bin/env perl
2  
3 =begin meta_information
4  
5 =encoding utf8
6  
7 License: BSD-2-Clause
8 Program-version: <see below>
9 Description: Libriary for IPC and token based
10 lock mechanism.
11 Contact: Dominik Bernhardt - domasprogrammer@gmail.com or https://github.com/DomAsProgrammer
12  
13 =end meta_information
14  
15 =begin license
16  
17 Transport data between applications (IPC) via Storable library
18 Copyright © 2025 Dominik Bernhardt
19  
20 Redistribution and use in source and binary
21 forms, with or without modification, are permitted
22 provided that the following conditions are met:
23  
24 1. Redistributions of source code must retain the
25 above copyright notice, this list of conditions and the
26 following disclaimer.
27  
28 2. Redistributions in binary form must reproduce
29 the above copyright notice, this list of conditions and
30 the following disclaimer in the documentation and/or
31 other materials provided with the distribution.
32  
33 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
34 HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR
35 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
37 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
38 COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
39 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
40 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
41 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
43 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
44 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
45 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
46 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
47 DAMAGE.
48  
49 =end license
50  
51 =begin version_history
52  
53 v0.1 Beta
54 I often had problems installing IPC::Shareable on dif-
55 ferent platforms.
56 So I built this library runable with only (Enterprise
57 Linux) default Perl installation.
58  
59 v0.2 Beta
60 Missing control added
61  
62 v0.2.1 Beta
63 Extended how_to
64  
65 v1
66 Bugfixes and release
67  
68 v1.1
69 Now protects content of the file, only accessible by
70 owner.
71  
72 v1.2
73 Better target name handling.
74 Enable user to use a second argument for manipulating
75 chmod.
76  
77 v1.3
78 Solved DESTROY bug
79  
80 v1.4
81 Proper error message on missing lock file.
82 Speed improvement by NOT sleeping
83  
84 v1.4.1
85 Just some prettier output.
86  
87 v1.5
88 Renamed
89  
90 v1.5.1
91 Fewer output
92  
93 v1.6
94 Read/write permission check.
95  
96 v1.6.1
97 Read/write permission bug solved.
98 Better working DESTROY function.
99  
100 v1.6.2
101 False coded bolAllowMultiple corrected.
102  
103 v1.6.3
104 Code quality increased.
105 Added dependency: boolean and Try
106  
107 v1.6.3.1
108 Added coments
109  
110 v2.00
111 Significant changes!
112 Renamed
113 Now working with a FIFO array, but nothing should change
114 for the lib user.
115  
116 v2.01
117 Some bugfixes.
118  
119 v2.02
120 Implemented Carp and Exporter.
121 Declared version.
122  
123 v2.03
124 Used END block to properly end the program.
125  
126 v2.04
127 Switched to Perl v5.40.0, removed Try and replaced by
128 feature q{try}
129  
130 v2.05
131 Perl v5.40.0 also supports boolean values nativly.
132 Removed boolean and used builtin's true and false.
133  
134 v2.06
135 Bugfix of lock_retrieve() on scrambled files.
136  
137 v2.07
138 Detection and warning of orphan lock files.
139  
140 v2.08
141 New terminology
142 Compatibility layer
143  
144 v2.09
145 Removed compatibility layer
146  
147 v2.10
148 New dependency for FreeBSD: /run as tmpfs in testing
149 Full fledged pod.
150  
151 v2.10.01
152 Bugfix: Dynamic lock file target mode is now case
153 sensetive agian.
154  
155 v2.11
156 Bugfixes
157  
158 v2.12
159 Cares about lock file's permissions in detail.
160  
161 v2.13
162 Better handling if TokenUnlock() was called if TokenLock() was never called before.
163 Improved manual.
164  
165 v3
166 Verion number change to integer.
167 Public release on MetaCPAN.
168  
169 v4
170 Proper variable naming.
171  
172 =end version_history
173  
174 =begin comment
175  
176 use IPC::LockTicket;
177  
178 my $object = IPC::LockTicket->New(qq{name}, <chmod num>); # For SPEED: Creates a shared handle within
179 # /dev/shm (allowed symbols: m{^[a-z0-9]+$}i)
180 # name like name
181  
182 my $object = IPC::LockTicket->New(qq{/absolute/path.file}, <chmod num>)
183 # For STORAGE: Creates a shared handle at the
184 # given path (must be a file name)
185  
186 $bol_succcess = $object->MainLock(1); # For MULTIPLE usage: allows calling MainLock()
187 # multiple times on same file to allow IPC even
188 # if it's not from a fork (applies only on same
189 # name or file) i.e. it's not failing on
190 # MainLock() if file exists
191  
192 $bol_succcess = $object->MainLock(); # Creates shm/lock-file or if existing and
193 # MULTIPLE is active for file and new object
194 # it implements the PID
195  
196 $bol_succcess = $object->TokenLock(); # Get a ticket to queue up - blocks until it's
197 # our turn
198  
199 $bol_succcess = $object->SetCustomData($reference); # Save any data as reference - be aware this
200 # decreases speed and you fastly run out of
201 # space
202  
203 $reference = $object->GetCustomData(); # Load custom data block
204  
205 $bol_succcess = $object->TokenUnlock(); # We're done and next one's turn is now
206  
207 $bol_succcess = $object->MainUnlock(); # Removes PID from lock file on MULTIPLE. If
208 # no more PIDs are within the lockfile it re-
209 # moves the lock file as well.
210 # Hint: The user of the library must take
211 # care when to MainUnlock() e.g. wait until
212 # all child processes died.
213  
214 =end comment
215  
216 =begin comment
217  
218 V A R I A B L E N A M I N G
219  
220 str string
221 L sql sql code
222 L cmd command string
223 L ver version number
224 L bin binary data, also base64
225 L hex hex coded data
226 L uri path or url
227  
228 int integer number
229 L cnt counter
230 L oct octal number
231 L pid process id number
232 L tsp seconds since period
233  
234 flt floating point number
235  
236 bol boolean
237  
238 mxd unkown data (mixed)
239  
240 ref reference
241 L rxp regular expression
242 L are array reference
243 L dsc file discriptor (type glob)
244 L sub anonymous subfunction - DO NO LONGER USE, since Perl v5.26 functions can be declared lexically non-anonymous!
245 L har hash array reference
246 L tbl table (a hash array with PK as key OR a multidimensional array AND hash arrays as values)
247 L obj object (very often)
248  
249 =end comment
250  
251 =cut
252  
253 ##### C L A S S D E F I N I T I O N #####
254 package IPC::LockTicket;
255  
256 =head1 NAME
257  
258 IPC::LockTicket - Use Storable library to IPC token to prevent parallel access to any resources. Including your custom data to transfer asynchronously.
259  
260 =head1 SYNOPSIS
261  
262 use strict;
263 use warnings;
264 use IPC::LockTicket;
265  
266 my $object = IPC::LockTicket->New(@options);
267  
268 my $object = IPC::LockTicket->New(qq{name}, 0666);
269 # ...or
270 my $object = IPC::LockTicket->New(qq{/absolute/path.file}, 0600)
271  
272 # This fails if the IPC file exists already
273 $bol_succcess = $object->MainLock();
274  
275 $bol_succcess = $object->SetCustomData($reference);
276  
277 # fork() and do within Child1:
278 # Child1 represents best practice.
279  
280 $bol_succcess = $object->TokenLock(); # Blocks unless lock is aquired.
281  
282 $reference = $object->GetCustomData();
283 # Do something with $reference
284 $bol_succcess = $object->SetCustomData($reference);
285  
286 $bol_succcess = $object->TokenUnlock(); # Other children can only use the
287 # updated version, but were blocked until this point. Best practice is
288 # keeping the Time between TokenLock() and TokenUnlock() as short as
289 # possible.
290  
291 # Within a different Child2:
292 $reference = $object->GetCustomData(); # This is safe, but right after this
293 # call the data might change, because it is not controlled through any mechanism.
294 # This is useful if one just needs to get the current state, but doesn't rely on
295 # persistence.
296  
297 # Within another different ChildN:
298 $bol_succcess = $object->SetCustomData($reference); # This is safe, too, but
299 # it might lead to data loss through overwriting existing data.
300  
301 # At the end the parent does:
302 $bol_succcess = $object->MainUnlock();
303  
304 # Hand over a true value if multiple parents shall use the same IPC file:
305 $bol_succcess = $object->MainLock(1);
306  
307 =head1 DESCRIPTION
308  
309 IPC::LockTicket allows one to get a simple token/ticket locking mechanism, like C<flock()> does, but FIFO sorted.
310 It also makes it easy to transport small amount of data between processes.
311  
312 The data you want to transfer must be saved as an anonymous reference, and returns as such.
313  
314 The data is not transferred in real time, but only on request. While you might store whole objects if you need the most recent of them, lock the store, load it, change it and store it again before you unlock it again.
315  
316 In theory, you can store as much data as your disk can hold, but be aware: this will slow down the lock mechanism. Use multiple files in this case: One only holds data (full path), the other is just for locking (dynamic path).
317  
318 =cut
319  
320 ##### L I B R I A R I E S #####
321  
322 use strict;
323 use warnings;
324 use Storable qw(store retrieve lock_store lock_retrieve); # Base for this library
325 use Time::HiRes;
326 use feature qw(try unicode_strings current_sub fc);
327 use open qw(:std :encoding(UTF-8)); # Full UTF-8 support
328 use utf8; # Full UTF-8 support
329 use List::Util qw(first);
330 use Carp;
331 use Exporter;
332 ### MetaCPAN
333 use builtin qw(true false);
334 use English qw( -no_match_vars );
335  
336 BEGIN { # Good practice of Exporter but we don't have anything to export because we behave more like an object.
337 our @EXPORT_OK = ();
338 our $VERSION = q{4};
339 }
340  
341 END {
342 _EndProcedure();
343 }
344  
345 $SIG{INT} = \&_EndProcedure;
346 $SIG{TERM} = \&_EndProcedure;
347  
348  
349 ##### D E C L A R A T I O N #####
350 $ENV{LANG} = q{C.UTF-8};
351 $ENV{LANGUAGE} = q{C.UTF-8};
352 my @objEndSelf = ();
353 my @uriLinuxDirs = qw( /dev/shm /run/shm /run /tmp );
354 my @uriBSDirs = qw( /run /var/spool/lock /tmp );
355 my @uriAccord = ( fc($^O) eq fc(q(FreeBSD)) ) ? @uriBSDirs : @uriLinuxDirs;
356  
357 my $rxpTempFS = qr{^(?:tmp|ram)fs$}i;
358 my $rxpOptionSplit = qr{,\s*};
359 my $rxpMountLinux = qr{^
360 ([^\s]+) # Device 1
361 \s+on\s+
362 ([^\s]+)/* # Mount point 2
363 \s+type\s+
364 ([^\s]+) # File system 3
365 \s*\( # literal braket
366 (.+) # Options 4
367 \s*\)\s* # literal braket
368 $}xx;
369 my $rxpMountBSD = qr{^
370 ([^\s]+) # Device 1
371 \s+on\s+
372 ([^\s]+)/* # Mount point 2
373 \s*\( # literal braket
374 ([^\s,]+) # File system 3
375 (?:, ?)?
376 (.+)? # Options 4
377 \s*\)\s* # literal braket
378 $}xx;
379 my $rxpAccord = ( fc($^O) eq fc(q(FreeBSD)) ) ? $rxpMountBSD : $rxpMountLinux;
380 my $rxpGoodPath = qr{^[-_a-z0-9]{1,218}$}i;
381 my $rxpFullPath = qr{^\.?\.?/.+$};
382 my $rxpWhitespaces = qr{\s+};
383 my $rxpOctalNum = qr{^\o{4}$};
384  
385 ##### M E T H O D S #####
386  
387 =head1 IPC::LockTicket Class METHODS
388  
389 =head3 C<New>
390  
391 my $object = IPC::LockTicket->new($strName, $octPermission) or die;
392  
393 Creates a new IPC::LockTicket object, which is returned. Returns C<undef> on failure. Expects one or two arguments. First the name, optionally secondly the permission as an octal number.
394  
395 =over 2
396  
397 =item name
398  
399 String just matching C<m{^[-_a-z0-9]+$}i> for dynamic naming or a full path to a file.
400 Mandatory.
401  
402 =item permission
403  
404 Access rights that the lock file will have.
405 For example, if just a collision protection shall be implemented, it might be the best to set it to 0666, so collisions can be prevented over the whole system for every user.
406 Expects an octal number, like L<chmod(1)>.
407 Defaults to C<0600>.
408  
409 =back
410  
411 =cut
412  
413 sub new { goto &New; } # Keep regular naming for Perl objects
414 sub New {
415 my $strClass = shift;
416 my $objSelf = {
417 _uriPath => shift, # Path or name for Storable
418 _octPermission => shift, # Permissons for the created file
419 _pidParent => $$,
420 _harData => {
421 bolAllowMultiple => false, # Allows multiple locks on same file
422 arePIDs => [], # MainLock() mechanism ; list of parents
423 refCustomData => undef, # Place to save data for lib user
424 areToken => [ # Array for FIFO handling
425 #{
426 # _pidAgent => PID,
427 # _pidParent => PID,
428 #},
429 ],
430 },
431 };
432  
433 # If name is not a path or a name with prohibited characters
434 if ( $objSelf->{_uriPath}
435 && $objSelf->{_uriPath} =~ m{$rxpGoodPath}i ) {
436 my $bolWorkingDirFound = false;
437 my $areMounts = _GetMounts();
438  
439 # Find a fitting directory
440 lopTestDir:
441 foreach my $strDir ( @uriAccord ) {
442 if ( -d $strDir
443 && -w $strDir
444 && grep { $strDir eq $_->{uriMountPoint} && $_->{strFileSystem} =~ m{$rxpTempFS} } @{$areMounts} ) {
445 $objSelf->{_uriPath} = qq{$strDir/IPC__LockTicket-$objSelf->{_uriPath}.shm};
446 $bolWorkingDirFound = true;
447 last(lopTestDir);
448 }
449 }
450  
451 if ( ! $bolWorkingDirFound ) {
452 # Try even harder
453 lopTestDirAgain:
454 foreach my $strDir ( @uriAccord ) {
455 if ( -d $strDir
456 && -w $strDir ) {
457 $objSelf->{_uriPath} = qq{$strDir/IPC__LockTicket-$objSelf->{_uriPath}.shm};
458 $bolWorkingDirFound = true;
459 last(lopTestDirAgain);
460 }
461 }
462 }
463  
464 # Stop if no fitting dir was found
465 if ( ! $bolWorkingDirFound ) {
466 my $strCaller = (caller(0))[0];
467 croak qq{$strCaller(): Can't find any suitable directory\n}
468 . qq{Expected any of these to exist:\n}
469 . join('', map { qq{ $_\n} } @uriAccord);
470 }
471  
472 }
473  
474 if ( &_Check($objSelf) ) {
475 bless($objSelf, $strClass);
476 push(@objEndSelf, $objSelf);
477 return($objSelf);
478 }
479  
480 return(undef);
481 }
482  
483 =head3 C<DESTROY>
484  
485 my $bolSuccess = $object->DESTROY();
486  
487 Destroys the object so it removes lock files or PIDs from lock files. Automatically called on C<undef($object)>, C<die>, C<exit>, and when C<$object> leaves the scope.
488  
489 B<Not> called if another module C<croak()>s or if the application fails through an exception at runtime.
490  
491 Z<>
492  
493 If not called, the next C<MainLock()> will clear the orphan file, but it is not clear that the content was written properly. If the file is empty or cannot be read, it will not be cleared, but C<MainLock()> will fail. See L<C<MainLock>> for further details.
494  
495 =cut
496  
497 # Similar to MainUnlock, but without blocking tokens
498 sub DESTROY {
499 my $objSelf = shift;
500  
501 # Test if file is readable
502 try {
503 lock_retrieve($objSelf->{_uriPath})
504 }
505 catch ($strError) {
506 # Not readable
507 return(true);
508 }
509  
510 # Only remove PID / lock file if the requesting process has created it
511 if ( -e $objSelf->{_uriPath}
512 && grep { $$ == $_ } $objSelf->_GetPIDs() ) {
513  
514 # Obsolete, doing the same as MainUnlock() while we already have a function for this purpose
515 my @intPIDs = do {
516 local $SIG{CLD} = q{IGNORE};
517 local $SIG{CHLD} = q{IGNORE};
518  
519 grep { kill(0 => $_) } grep { $_ != $$ } $objSelf->_GetPIDs();
520 };
521 # Get running PIDs from lock file which are not the current process
522 # to check if this process is the last one.
523  
524 # If there are other processes running
525 if ( @intPIDs
526 && $objSelf->_MultipleAllowed()
527 && open(my $fh, "<", $objSelf->{_uriPath}) ) {
528 flock($fh, 2);
529  
530 $objSelf->{_harData} = retrieve($objSelf->{_uriPath});
531  
532 # Calculate new data - this is needed, because flock() might have delayed the former request
533 $objSelf->{_harData}{arePIDs} = [ do {
534 local $SIG{CLD} = q{IGNORE};
535 local $SIG{CHLD} = q{IGNORE};
536  
537 grep { kill(0 => $_) } grep { $_ != $$ } @{$objSelf->{_harData}{arePIDs}};
538 } ];
539  
540 store($objSelf->{_harData}, $objSelf->{_uriPath});
541  
542 my $strCaller = (caller(0))[3];
543 close($fh) or die qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
544  
545 # If we exited as last process we now can delete the file
546 if ( ! @{$objSelf->{_harData}{arePIDs}} ) {
547 unlink($objSelf->{_uriPath});
548 }
549 }
550 # If we are the last exiting process
551 else {
552 unlink($objSelf->{_uriPath});
553 }
554 }
555  
556 return(true);
557 }
558  
559 sub _GetMounts {
560 my @strMounts = qx(mount);
561 my @harMounts = (
562 # { HAR
563 # uriDevice => < URI Path to device >,
564 # uriMountPoint => < URI Path to dir >,
565 # strFileSystem => < STR like ext4, autofs, tmpfs, etc. >,
566 # areOptions => [ ARE of split() ],
567 # }
568 );
569  
570 foreach my $strLine ( @strMounts ) {
571 chomp($strLine);
572  
573 if ( $strLine =~ m($rxpAccord) ) {
574 push(@harMounts, {
575 uriDevice => $1,
576 uriMountPoint => $2,
577 strFileSystem => $3,
578 areOptions => [
579 ( $4 ) ? split(m($rxpOptionSplit), $4) : ()
580 ],
581 });
582 }
583 }
584  
585 @harMounts = sort { $b->{uriMountPoint} cmp $a->{uriMountPoint} } @harMounts;
586  
587 return(\@harMounts);
588 }
589  
590 sub _Check {
591 my $objSelf = shift;
592 my $strErrors = '';
593 my $strCaller = (caller(0))[3];
594  
595 if ( $objSelf->{_uriPath}
596 && -s $objSelf->{_uriPath}
597 && open(my $fh, '<', $objSelf->{_uriPath}) ) {
598 flock($fh, 2);
599  
600 # Test if file is readable
601 try {
602 retrieve($objSelf->{_uriPath})
603 }
604 catch ($strError) {
605 $strErrors .= qq{"$objSelf->{_uriPath}": Mailformed shared memory file.\n$strError\n};
606 }
607  
608 close($fh) or $strErrors .= qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
609 }
610 # User failure
611 elsif ( ! $objSelf->{_uriPath} ) {
612 $strErrors .= qq{$strCaller(): Missing argument!\n};
613 }
614 # If open() failes
615 elsif ( -s $objSelf->{_uriPath} ) {
616 $strErrors .= qq{$strCaller(): Unable to open "$objSelf->{_uriPath}"!\n};
617 }
618  
619 # Some more fine tuning
620 if ( $objSelf->{_uriPath}
621 && -d $objSelf->{_uriPath} ) {
622 $strErrors .= qq{"$objSelf->{_uriPath}": A folder can't be a share memory file!\n};
623 }
624 if ( $objSelf->{_uriPath} !~ m{$rxpFullPath} ) {
625 $strErrors .= qq{"$objSelf->{_uriPath}": is an inadequate path or name!\n};
626 }
627  
628 # Protect file if not set other wise
629 if ( defined($objSelf->{_octPermission})
630 && length(qq{$objSelf->{_octPermission}}) > 4 ) {
631 $strErrors .= sprintf(qq{"%04o": Invalid permission. Must be a octal number of four or NULL.\n}, $objSelf->{_octPermission});
632 }
633 elsif ( ! defined($objSelf->{_octPermission}) ) {
634 $objSelf->{_octPermission} = 0600;
635 }
636  
637 # Check permissions
638 if ( -e $objSelf->{_uriPath}
639 && ! -r $objSelf->{_uriPath} ) {
640 $strErrors .= qq{"$objSelf->{_uriPath}": No read permission.\n};
641 }
642 if ( -e $objSelf->{_uriPath}
643 && ! -w $objSelf->{_uriPath} ) {
644 $strErrors .= qq{"$objSelf->{_uriPath}": No write permission.\n};
645 }
646  
647 # What if permissions differ??
648 if ( -e $objSelf->{_uriPath} ) {
649 my %mxdFileStat = ();
650 my @strParts = qw(o g u ts);
651 my %intFilePerms = (); # user:users 0600
652 my @intFileGrpsMbrs = ();
653 my %intObjPerms = (); # root:root 0600
654 my $strEUName = (getpwuid($EUID))[0];
655 my @intObjGrps = ( (getpwuid($EUID))[3] );
656 my $cntPosition = 0;
657 @mxdFileStat{qw(dev ino mode nlink uid gid rdev size atime mtime ctime blksize blocks)} =
658 stat($objSelf->{_uriPath});
659 %intFilePerms =
660 map { $strParts[$cntPosition++] => $_ } #( $_ % 2 ) ? $_ - 1 : $_ } # Execution bit is not required
661 reverse(split('', sprintf(q{%04o}, $mxdFileStat{mode} & 07777)));
662 $cntPosition = 0;
663 %intObjPerms =
664 map { $strParts[$cntPosition++] => $_ } #( $_ % 2 ) ? $_ - 1 : $_ } # Execution bit is not required
665 reverse(split('', sprintf(q{%04o}, $objSelf->{_octPermission})));
666 @intFileGrpsMbrs = # Group's members
667 map { (getpwnam($_))[2] } # UID
668 grep { defined && $_ ne '' }
669 split(m{$rxpWhitespaces}, (getgrgid($mxdFileStat{gid}))[3]);
670 push(@intFileGrpsMbrs, 0); # Root is part of any group
671  
672 # If file owner's group is same as the file's group we need to add the user's name to the File Group Members list, in case it's the user's main group, which won't be shown by getent groups
673 while ( my(undef, undef, $intUID, $intGID) = getpwent() ) {
674  
675 # Users' default groups
676 if ( $intGID == $mxdFileStat{gid} ) {
677 push(@intFileGrpsMbrs, $intUID);
678 }
679 }
680  
681 while ( my(undef, undef, $intGID, $strMembers) = getgrent() ) {
682  
683 # We need to know all real groups
684 if ( grep { $strEUName eq $_ } split(m{$rxpWhitespaces}, $strMembers) ) {
685 push(@intObjGrps, $intGID);
686 }
687 }
688  
689 if ( $intFilePerms{o} > $intObjPerms{o} # General rights are to high
690 || $intFilePerms{g} > $intObjPerms{g} # General rights are to high
691  
692 # File is not owned by user's real groups
693 ||( !( grep { $mxdFileStat{gid} == $_ } @intObjGrps )
694 && $intFilePerms{g} > $intObjPerms{o} ) # Foreign group has more rights as wanted for other users
695  
696  
697 # File is not owned effective user
698 ||($mxdFileStat{uid} != $EUID
699 && (
700  
701 ## File owner is part of file owning group -> access can happen through group
702 #(grep { $mxdFileStat{uid} == $_ } @intFileGrpsMbrs
703 #&& $intFilePerms{g} > $intObjPerms{o} )
704 #
705 ## File owner is not part of file owning group -> access happens only through owner
706 #||( !( grep { $mxdFileStat{uid} == $_ } @intFileGrpsMbrs )
707 ( !( grep { $mxdFileStat{uid} == $_ } @intFileGrpsMbrs )
708 && $intFilePerms{u} > $intObjPerms{o} )
709  
710 ) ) ) {
711 $strErrors .= qq{Existing file "$objSelf->{_uriPath}" has douptful permissions.\n};
712  
713 }
714 }
715  
716 if ( $strErrors ) {
717 croak $strErrors; # die
718 }
719  
720 return(true);
721 }
722  
723 # Returns an array of integers which represents all registered PIDs of current lock file
724 sub _GetPIDs {
725 my $objSelf = shift;
726  
727 try {
728 $objSelf->{_harData} = lock_retrieve($objSelf->{_uriPath});
729 }
730 catch ($strError) {
731 carp qq{"$objSelf->{_uriPath}": Mailformed shared memory file.\n$strError\n};
732 return(undef);
733 }
734  
735 return(@{$objSelf->{_harData}{arePIDs}});
736 }
737  
738 # Save a array of integer
739 sub _SetPIDs {
740 my $objSelf = shift;
741 my @intPIDs = @_;
742  
743 if ( open(my $fh, "<", $objSelf->{_uriPath}) ) {
744 flock($fh, 2);
745  
746 $objSelf->{_harData} = retrieve($objSelf->{_uriPath});
747  
748 $objSelf->{_harData}{arePIDs} = [ @intPIDs ];
749  
750 store($objSelf->{_harData}, $objSelf->{_uriPath});
751  
752 my $strCaller = (caller(0))[3];
753 close($fh) or die qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
754 }
755  
756 return(true);
757 }
758  
759 # Returns boolean value
760 sub _MultipleAllowed {
761 my $objSelf = shift;
762  
763 try {
764 $objSelf->{_harData} = lock_retrieve($objSelf->{_uriPath});
765 }
766 catch ($strError) {
767 carp qq{"$objSelf->{_uriPath}": Mailformed shared memory file.\n$strError\n};
768 return(undef);
769 }
770  
771 return($objSelf->{_harData}{bolAllowMultiple});
772 }
773  
774 =head3 C<MainLock>
775  
776 my $bolSuccess = $object->MainLock();
777 my $bolSuccess = $object->MainLock(1);
778  
779 Checks if a lock file exists and creates it if not. Fails if file exists and process stored within is alive.
780 If a C<true> value is supplied, locking is non-exclusive but shared. If the file exists and was also created non-exclusively, locking is successful. This way the lock file is shared with several processes, requesting non-exclusive mode.
781 If C<false> is returned from C<MainLock> no lock file was created/claimed.
782 Meaning:
783  
784 ____________________________________________________________________________________________________________________________________
785 | Call mode | MainLock() | MainLock() | MainLock() | MainLock() | MainLock(1) | MainLock(1) | MainLock(1) | MainLock(1) |
786 | Lock file | empty* | shared | exclusive | non-existent | empty* | shared | exclusive | non-existent |
787 | MainLock returns | false | false | false | true | false | true | false | true |
788 ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
789  
790 *= empty or any other non-Storable data.
791  
792 =cut
793  
794 # Creates the lock file
795 sub MainLock {
796 my $objSelf = shift;
797 my $bolMultipleAllowed = shift;
798  
799 # If the file exists
800 if ( -e $objSelf->{_uriPath}
801 && $objSelf->_Check() ) { # Dies in _Check if failed
802  
803 # If multiple is allowed we register our PID
804 if ( $bolMultipleAllowed
805 && $objSelf->_MultipleAllowed() ) {
806 $objSelf->TokenLock();
807  
808 my @intPIDs = $objSelf->_GetPIDs();
809  
810 if ( grep { $_ == $$ } @intPIDs ) {
811 carp qq{WARNING: Same process tried to MainLock() again.\n};
812 $objSelf->TokenUnlock();
813 return(false);
814 }
815 else {
816 $objSelf->_SetPIDs( @intPIDs, $$ );
817 }
818  
819 $objSelf->TokenUnlock();
820 return(true);
821 }
822 # Or it must be exclusive
823 else {
824 $objSelf->TokenLock();
825 my @intPIDs = $objSelf->_GetPIDs();
826  
827 local $SIG{CLD} = q{IGNORE};
828 local $SIG{CHLD} = q{IGNORE};
829  
830 # Did we lock up?
831 if ( grep { $$ == $_ } @intPIDs ) {
832 carp qq{WARNING: Same process tried to MainLock() again.\n};
833 $objSelf->TokenUnlock();
834 return(false);
835 }
836 # There are processes running on this lock file
837 elsif ( grep { kill(0 => $_) } @intPIDs ) {
838 $objSelf->TokenUnlock();
839 return(false);
840 }
841 else {
842 carp qq{ERROR: Was the former instance not exited porperly?\nOrphan lock file found: "$objSelf->{_uriPath}".};
843 return(false);
844 }
845 }
846 }
847 # Create file and write our format
848 elsif ( ! -e $objSelf->{_uriPath} ) {
849 if ( open(my $fh, ">", $objSelf->{_uriPath}) ) {
850 close($fh);
851  
852 chmod($objSelf->{_octPermission}, $objSelf->{_uriPath});
853  
854 $objSelf->{_harData}{bolAllowMultiple} = ( $bolMultipleAllowed ) ? true : false;
855 $objSelf->{_pidParent} = $$;
856 push(@{$objSelf->{_harData}{arePIDs}}, $$);
857  
858 lock_store($objSelf->{_harData}, $objSelf->{_uriPath});
859 }
860 else {
861 return(false);
862 }
863 }
864 else {
865 return(false);
866 }
867  
868 return(true);
869 }
870  
871 =head3 C<MainUnlock>
872  
873 $object->MainUnlock();
874  
875 Removes lock. The lock file is deleted if this is the last process accessing it.
876 Returns only a true value.
877  
878 If it is a shared lock and not the last process accessing it, only the PID entries are removed from the lock file.
879  
880 =cut
881  
882 # Removes lock file or the PID from those
883 sub MainUnlock {
884 my $objSelf = shift;
885  
886 if ( ! -e $objSelf->{_uriPath} ) {
887 my $strCaller = (caller(0))[3];
888 croak qq{$strCaller(): Lock file missing\nHave you ever called MainLock() ?\n};
889 }
890  
891 if ( $objSelf->_MultipleAllowed() ) {
892 my @intPIDs = ();
893  
894 $objSelf->TokenLock();
895  
896 @intPIDs = do {
897 local $SIG{CLD} = q{IGNORE};
898 local $SIG{CHLD} = q{IGNORE};
899  
900 grep { kill(0 => $_) } grep { $_ != $$ } $objSelf->_GetPIDs();
901 };
902  
903 if ( @intPIDs ) {
904 $objSelf->_SetPIDs(@intPIDs);
905 $objSelf->TokenUnlock();
906 }
907 else {
908 unlink($objSelf->{_uriPath});
909 }
910  
911 }
912 else {
913 unlink($objSelf->{_uriPath});
914 }
915  
916 return(true);
917 }
918  
919 sub _CleanAgentsList (\@) {
920 my $areList = shift;
921 my %bolTestedParent = ();
922  
923 local $SIG{CLD} = q{IGNORE};
924 local $SIG{CHLD} = q{IGNORE};
925  
926 # if parent was not tested yet test if alive, but we don't test ourself, but any other agent
927 return(grep { ( $bolTestedParent{$_->{_pidParent}}++ || kill(0 => $_->{_pidParent}) ) && ( $_->{_pidAgent} == $$ || kill(0 => $_->{_pidAgent}) ) } @{$areList});
928 }
929  
930 =head3 C<TokenLock>
931  
932 $object->TokenLock();
933  
934 Can only be called after C<MainLock> and before C<MainUnlock> otherwise C<die>s.
935 Requests exclusive lock, i.e., any C<TokenLock> is blocking until C<TokenUnlock> was called, or the locking process is dead. Process checks are done to prevent infinite locks through broken children or parents, but this is not proper usage. Don't just C<exit>, but call C<TokenUnlock> and C<MainUnlock> in appropriate sequence before ending processes!
936 Returns a true value or blocks.
937  
938 =cut
939  
940 # Integrated lock system
941 sub TokenLock {
942 my $objSelf = shift;
943 my $bolInit = true;
944 my $strCaller = (caller(0))[3];
945  
946 if ( ! -e $objSelf->{_uriPath} ) {
947 croak qq{$strCaller(): Lock file missing\nHave you ever called MainLock() ?\n};
948 }
949  
950 while ( true ) {
951 if ( -e $objSelf->{_uriPath}
952 && open(my $fh, "<", $objSelf->{_uriPath}) ) {
953 flock($fh, 2);
954  
955 # Load current data
956 $objSelf->{_harData} = retrieve($objSelf->{_uriPath});
957  
958 @{$objSelf->{_harData}{areToken}} = _CleanAgentsList(@{$objSelf->{_harData}{areToken}});
959  
960 # If we never got a token, we request one
961 if ( $bolInit
962 && ! first { $_->{_pidAgent} == $$ } @{$objSelf->{_harData}{areToken}} ) {
963 $bolInit = false;
964 push(@{$objSelf->{_harData}{areToken}}, { _pidAgent => $$, _pidParent => $objSelf->{_pidParent} });
965 }
966 # Die if something strange happened
967 elsif ( ! -e $objSelf->{_uriPath}
968 || ( ! $bolInit
969 && ! first { $_->{_pidParent} == $objSelf->{_pidParent} } @{$objSelf->{_harData}{areToken}} ) ) {
970 # Parent exited (and maybe we weren't informed to exit)
971 close($fh) or die qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
972 exit(120);
973 }
974  
975 store($objSelf->{_harData}, $objSelf->{_uriPath});
976  
977 close($fh) or die qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
978  
979 # Check if it's our turn
980 if ( $objSelf->{_harData}{areToken}[0]{_pidAgent} == $$ ) {
981 return(true);
982 }
983 # Wait if it isn't our turn yet
984 else {
985 Time::HiRes::sleep(0.01); # Needed to prevent permanent spamming on CPU and FS
986 }
987 }
988 elsif ( ! -e $objSelf->{_uriPath} ) {
989 # Parent exited (and maybe we weren't informed to exit)
990 exit(120);
991 }
992 }
993 }
994  
995 =head3 C<TokenUnlock>
996  
997 $object->TokenUnlock();
998  
999 Can only be called after C<MainLock> and before C<MainUnlock> otherwise C<die>s.
1000 Removes the token from the lock file so any other request of C<TokenLock> can be satisfied.
1001 Returns false if unlock is done while not holding the lock.
1002 Otherwise, it returns true.
1003  
1004 =cut
1005  
1006 sub TokenUnlock {
1007 my $objSelf = shift;
1008 my $bolSuccess = true;
1009 my $strCaller = (caller(0))[3];
1010  
1011 if ( ! -e $objSelf->{_uriPath} ) {
1012 croak qq{$strCaller(): Lock file missing\nHave you ever called MainLock() ?\n};
1013 }
1014  
1015 if ( open(my $fh, "<", $objSelf->{_uriPath}) ) {
1016 flock($fh, 2);
1017  
1018 $objSelf->{_harData} = retrieve($objSelf->{_uriPath});
1019  
1020 if ( $objSelf->{_harData}{areToken}[0]{_pidAgent} != $$ ) {
1021 carp qq{Lock is on PID $objSelf->{_harData}{areToken}[0]{_pidAgent}, but PID $$ tries to unlock. Nothing done.\n};
1022  
1023 $bolSuccess = false;
1024 }
1025  
1026 @{$objSelf->{_harData}{areToken}} = grep { $_->{_pidAgent} != $$ } # Remove ourself from list, either where we are
1027 _CleanAgentsList(@{$objSelf->{_harData}{areToken}}); # Regular clean up
1028  
1029 store($objSelf->{_harData}, $objSelf->{_uriPath});
1030  
1031 close($fh) or die qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
1032 }
1033 else {
1034 # Open failed
1035  
1036 $bolSuccess = false;
1037 }
1038  
1039 return($bolSuccess);
1040 }
1041  
1042 =head3 C<SetCustomData>
1043  
1044 $object->TokenLock();
1045 $object->SetCustomData($reference);
1046 $object->TokenUnlock();
1047  
1048 Writes a custom data reference in a reserved area. See L<CAVEATS> and L<GOOD PRACTICE> for further details.
1049 Should be preceded by C<TokenLock()> and followed by C<TokenUnlock()>.
1050 Returns only a true value or C<die>s.
1051  
1052 =cut
1053  
1054 # Allows transporting developers data between processes (custom IPC)
1055 sub SetCustomData {
1056 my $objSelf = shift;
1057 my $refData = shift;
1058 my $strCaller = (caller(0))[3];
1059  
1060 if ( ! -e $objSelf->{_uriPath} ) {
1061 croak qq{$strCaller(): Lock file missing\nHave you ever called MainLock() ?\n};
1062 }
1063  
1064 if ( !( ref($refData)
1065 || ! defined($refData) ) ) {
1066 croak qq{$strCaller(): refData=:"$refData" is not a reference nor NULL\n};
1067 }
1068  
1069 if ( open(my $fh, "<", $objSelf->{_uriPath}) ) {
1070 flock($fh, 2);
1071  
1072 $objSelf->{_harData} = retrieve($objSelf->{_uriPath});
1073  
1074 if ( ref($refData) eq q{ARRAY} ) {
1075 $objSelf->{_harData}{refCustomData} = [ @{$refData} ];
1076 }
1077 elsif ( ref($refData) eq q{HASH} ) {
1078 $objSelf->{_harData}{refCustomData} = { %{$refData} };
1079 }
1080 elsif ( ref($refData) eq q{SCALAR} ) {
1081 $objSelf->{_harData}{refCustomData} = ${$refData} . "";
1082 }
1083 elsif ( ref($refData) eq q{CODE} ) {
1084 $objSelf->{_harData}{refCustomData} = $refData;
1085 }
1086 else { # Undef undef
1087 $objSelf->{_harData}{refCustomData} = undef;
1088 }
1089  
1090 store($objSelf->{_harData}, $objSelf->{_uriPath});
1091  
1092 close($fh) or die qq{$strCaller(): Unable to close "$objSelf->{_uriPath}" properly\n};
1093 }
1094  
1095 return(true);
1096 }
1097  
1098 =head3 C<GetCustomData>
1099  
1100 $refData = $object->GetCustomData();
1101  
1102 Load the reference, formerly saved by C<SetCustomData>.
1103 Returns C<undef> either it was never set or an error occurred.
1104  
1105 =cut
1106  
1107 # Allows transporting developers data between processes (custom IPC)
1108 sub GetCustomData {
1109 my $objSelf = shift;
1110  
1111 if ( ! -e $objSelf->{_uriPath} ) {
1112 my $strCaller = (caller(0))[3];
1113 croak qq{$strCaller(): Lock file missing\nHave you ever called MainLock() ?\n};
1114 }
1115  
1116 try {
1117 $objSelf->{_harData} = lock_retrieve($objSelf->{_uriPath});
1118 }
1119 catch ($strError) {
1120 carp qq{"$objSelf->{_uriPath}": Mailformed shared memory file.\n$strError\n};
1121 return(undef);
1122 }
1123  
1124 return($objSelf->{_harData}{refCustomData});
1125 }
1126  
1127 sub _EndProcedure {
1128 foreach my $objSelf ( @objEndSelf ) {
1129 &DESTROY($objSelf);
1130 }
1131 }
1132  
1133 =head1 LOCKING
1134  
1135 Locking works like a traffic light: Only if honoured, it can do its magic. L<C<flock()>|https://perldoc.perl.org/functions/flock> works the same way: only if all members honour the lock, it can be guaranteed to work properly.
1136 There are several methods implemented to prevent infinite locks through unexpectedly died processes.
1137 But the core of this is the token handling itself, providing a FIFO locking mechanism. The first process which called C<TokenLock> is the first that will gain the lock. The last process, called C<TokenLock> has to wait until the second to last called C<TokenUnlock>.
1138 C<TokenLock> is blocking. Until the former processes either call C<TokenUnlock> or unexpectedly died.
1139  
1140 =head1 CAVEATS
1141  
1142 Using C<SetCustomData> can lead to problems. For example, if a huge array is stored, the memory can exceed. However, even worse is: the more data is stored within, the slower the locking mechanism gets, because it has to write all the data every time it checks or changes the lock file.
1143 Refer to L<GOOD PRACTICE> how to prevent this.
1144  
1145 =head1 GOOD PRACTICE
1146  
1147 =head3 Transferring huge amounts of data between processes
1148  
1149 # Parent
1150 my $objLock = IPC::LockTicket->New('MyApp');
1151 my $objIPC = IPC::LockTicket->New('/var/tmp/MyApp/storage.ipc');
1152 $objLock->MainLock(1);
1153 $objIPC->MainLock(1);
1154 ...
1155  
1156 # Child 1 has much data to transfer
1157 $objLock->TokenLock();
1158 $objIPC->SetCustomData($referenceToHugeHashArray);
1159 $objLock->TokenUnlock();
1160 ...
1161  
1162 # Child 2 shall work on the data
1163 $objLock->TokenLock();
1164 my $referenceToHugeHashArray = $objIPC->GetCustomData();
1165 $objIPC->SetCustomData(undef); # Clear storage to prevent working on the same elements several times...
1166 $objLock->TokenUnlock(); # ...and unlock fastly.
1167  
1168 if ( defined($referenceToHugeHashArray) ) {
1169 # Do something with the data...
1170 exit(0);
1171 }
1172 else {
1173 # Data was emptied or no data were saved yet.
1174 exit(0);
1175 }
1176  
1177 Use dynamic naming for locking mechanisms only. This way, C<IPC::LockTicket> tries to find the best location to store the file on its own while you keep the file small.
1178 For use of custom data transfer between processes, use full path notation and store on a slower, but huge partition.
1179 This way the lock mechanism can keep its speed, but you can transfer huge data as well.
1180 Maybe it is a better idea to use something like a database instead of a lock file for those situations. To consider this: the data is stored as a blob from L<Storable>. This works well if you write once and clear the data afterwards. But it will re-write the whole file every time C<SetCustomData> is called. This is inefficient if only a new hash pair shall be added and can make your app awfully slow. Better would be to prevent parallel database table access through IPC::LockTicket, so no redundant work happens, while databases are optimized to handle small amounts of data. Consider S<C<Child 2>> reading the whole table, then truncating it. After that S<C<Child 1>> might again write something new into the table.
1181  
1182 =head3 Shared locks
1183  
1184 It is possible to run C<MainLock(1)> within the children, but this is bad practice and strongly discouraged! Shared locks shall only be shared between the main processes (parents) while children only use the C<TokenLock> and C<TokenUnlock> methods.
1185 The lock objects created through C<New('name')> can be copied though C<fork>ing.
1186 But C<New> sets what is understood as the I<parent> PID to the calling process. C<MainLock> and C<MainUnlock> expect to be run within the I<parent> process.
1187 C<TokenLock> is more optimized for speed than C<MainLock> is.
1188  
1189 =head1 AUTHOR
1190  
1191 Dominik Bernhardt, domasprogrammer@gmail.com
1192  
1193 =head1 CREDITS
1194  
1195 Thanks for the hard time, much to learn and ideas I got through:
1196  
1197 =over 2
1198  
1199 =item L<Storable|https://metacpan.org/pod/Storable>
1200  
1201 =item L<IPC::Shareable|https://metacpan.org/pod/IPC::Shareable>
1202  
1203 =item L<C<flock()>|https://perldoc.perl.org/functions/flock>
1204  
1205 =back
1206  
1207 =head1 SEE ALSO
1208  
1209 L<perl(1)>, L<Storable|https://metacpan.org/pod/Storable>
1210  
1211 =cut
1212  
1213 1;