Debian Codegraph @

cassandane/Cassandane/Util/Setup.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Util::Setup;
41 use strict;
42 use warnings;
43 use base qw(Exporter);
44 use POSIX;
45 use User::pwent;
46 use Data::Dumper;
47
48 use lib '.';
49 use Cassandane::Util::Log;
50
51 our @EXPORT = qw(&become_cyrus);
52
53 my $me = $0;
54 my @saved_argv = @ARGV;
55
56 sub become_cyrus
57 {
58 my $cyrus = $ENV{CYRUS_USER};
59 $cyrus //= 'cyrus';
60 my $pw = getpwnam($cyrus);
61 die "No user named '$cyrus'"
62 unless defined $pw;
63 my $uid = getuid();
64 if ($uid == $pw->uid)
65 {
66 xlog "already running as user $cyrus" if get_verbose;
67 }
68 elsif ($uid == 0)
69 {
70 xlog "setuid from root to $cyrus" if get_verbose;
71 setgid($pw->gid)
72 or die "Cannot setgid to group $pw->gid: $!";
73 setuid($pw->uid)
74 or die "Cannot setuid to group $pw->uid: $!";
75 }
76 else
77 {
78 xlog "using sudo to re-run as user $cyrus" if get_verbose;
79 my @cmd = ( qw(sudo -u), $cyrus, $me, @saved_argv );
80 exec(@cmd);
81 }
82 }
83
84 1;