1 # Copyright (C) 2019-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::Tmpfile;
6 use parent qw(Exporter);
7 our @EXPORT = qw(tmpfile);
8 use Fcntl qw(:DEFAULT);
12 # use tmpfile instead of open(..., '+>', undef) so we can get an
13 # unlinked filename which makes sense when viewed with lsof
15 # And if we ever stop caring to have debuggable filenames, O_TMPFILE :)
17 # This is also for Perl <5.32 which lacks: open(..., '+>>', undef)
18 # <https://rt.perl.org/Ticket/Display.html?id=134221>
20 my ($id, $sock, $append) = @_;
22 # add the socket inode number so we can figure out which
23 # socket it belongs to
25 $id .= '-ino:'.$st[1];
29 my $fl = O_RDWR | O_CREAT | O_EXCL;
30 $fl |= O_APPEND if $append;
32 my $fn = File::Spec->tmpdir . "/$id-".time.'-'.rand;
33 if (sysopen(my $fh, $fn, $fl, 0600)) { # likely
34 unlink($fn) or warn "unlink($fn): $!"; # FS broken
37 } while ($! == EEXIST);
38 undef # EMFILE/ENFILE/ENOSPC/ENOMEM