cgi/{reg,edit}user.cgi: Massive rewording of user instructions
[girocco.git] / Girocco / Util.pm
blob7040bf130205c577592d4ca995001134dee0e99e
1 package Girocco::Util;
3 use strict;
4 use warnings;
6 use Girocco::Config;
8 BEGIN {
9 use base qw(Exporter);
10 our @EXPORT = qw(scrypt jailed_file
11 lock_file unlock_file
12 filedb_atomic_append filedb_atomic_edit
13 valid_email valid_repo_url valid_web_url);
17 sub scrypt {
18 my ($pwd) = @_;
19 crypt($pwd, join ('', ('.', '/', 2..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
22 sub jailed_file {
23 my ($filename) = @_;
24 $Girocco::Config::chroot."/$filename";
27 sub lock_file {
28 my ($path) = @_;
30 $path .= '.lock';
32 use Errno qw(EEXIST);
33 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
34 use IO::Handle;
35 my $handle = new IO::Handle;
37 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
38 my $cnt = 0;
39 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
40 ($! == EEXIST) or die "$path open failed: $!";
41 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
42 sleep(1);
45 # XXX: filedb-specific
46 chmod 0664, $path or die "$path g+w failed: $!";
48 $handle;
51 sub unlock_file {
52 my ($path) = @_;
54 rename "$path.lock", $path or die "$path unlock failed: $!";
57 sub filedb_atomic_append {
58 my ($file, $line) = @_;
59 my $id = 65536;
61 open my $src, $file or die "$file open for reading failed: $!";
62 my $dst = lock_file($file);
64 while (<$src>) {
65 my $aid = (split /:/)[2];
66 $id = $aid + 1 if ($aid >= $id);
68 print $dst $_ or die "$file(l) write failed: $!";
71 $line =~ s/\\i/$id/g;
72 print $dst "$line\n" or die "$file(l) write failed: $!";
74 close $dst or die "$file(l) close failed: $!";
75 close $src;
77 unlock_file($file);
79 $id;
82 sub filedb_atomic_edit {
83 my ($file, $fn) = @_;
85 open my $src, $file or die "$file open for reading failed: $!";
86 my $dst = lock_file($file);
88 while (<$src>) {
89 print $dst $fn->($_) or die "$file(l) write failed: $!";
92 close $dst or die "$file(l) close failed: $!";
93 close $src;
95 unlock_file($file);
98 sub valid_email {
99 $_ = $_[0];
100 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-.]+$/;
102 sub valid_web_url {
103 $_ = $_[0];
104 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?(#[a-zA-Z0-9._-]+)?$/;
106 sub valid_repo_url {
107 $_ = $_[0];
108 /^(http|git|svn):\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;