Commit Graph

164 Commits

Author SHA1 Message Date
Thomas Lamprecht
8e677e74e7 Tools: add convert_size for generic byte conversion
We often need to convert between file sizes, for formatting output,
but also code-internal. Some methods expect kilobytes, some gigabytes
and sometimes we need bytes.

While conversion from smaller to bigger units can be simply done with
a left-shift, the opposite conversion may need more attention -
depending on the used context.

If we allocate disks this is quite critical. For example, if we need
to allocate a disk with size 1023 bytes using the
PVE::Storage::vdisk_alloc method (which expects kilobytes) a
right shift by 10 (<=> division by 1024) would result in "0", which
obviously fails.

Thus we round up the converted value if a remainder was lost on the
transformation in this new method. This behaviour is opt-out, to be
on the safe side.

The method can be used in a clear way, as it gives information about
the source and target unit size, unlike "$var *= 1024", which doesn't
gives direct information at all, if not commented or derived
somewhere from its context.

For example:
 > my $size = convert_unit($value, 'gb' => 'kb');
is more clear than:
 > my $size = $value*1024*1024;

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2017-09-11 11:12:41 +02:00
Thomas Lamprecht
eead1ccaa5 run_fork_with_timeout: do not overwrite global signal handlers
perls 'local' must be either used in front of each $SIG{...}
assignments or they must be put in a list, else it affects only the
first variable and the rest are *not* in local context.

This may cause weird behaviour where daemons seemingly do not get
terminating signals delivered correctly and thus may not shutdown
gracefully anymore.

As we only send SIGINT to processes if a manual stop action gets
triggered just catch this one here.

As this is a general method which allows to pass an arbitrary code
payload we cannot sanely handle all signals here, so remove trapping
all other besides SIGINT, if those need to be trapped that should be
done by the caller on a case by case basis.

Fixes: #1495

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2017-09-07 10:27:29 +02:00
Thomas Lamprecht
2d38b8a1b9 tools: add pipe_socket_to_command
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2017-08-21 16:07:30 +02:00
Emmanuel Kasper
72fba9114b Add run_fork_with_timeout utility
This runs subroutine in a forked process
and kills it after a timeout
2017-06-29 15:16:03 +02:00
Thomas Lamprecht
9a41a7b7c9 use more reliable checks in wait_for_vnc_port
We run into problems where this method returned to early, even if the
port wasn't actually ready yet. The reason for this is that we
checked /proc/net/tcp which does not guarantees and always up to date
state of only those ports which are actuall available, i.e. a port
could linger around (time-wait state) or appear even if it wasn't
accepting connections yet (as stated in the kernel docs:
/proc/net/tcp is seen as obsolete by the kernel devs).

Use the `ss` tool from the iproute2 package, it uses netlink to get
the current state and has switches where we can direct it to really
only get the state of those sockets which interest us currently.
I.e., we tell it to get only listening TCP sockets from the requested
port.

The only drawback is that we loop on a run_command, which is slower
than just reading a file. A single loop needs about 1ms here vs the
60µs on the /proc/net/tcp read. But this isn't a api call which is
used highly frequently but rather once per noVNC console open.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2017-06-27 11:22:55 +02:00
Wolfgang Bumiller
a0ecb15991 tools: next_unused_port: use IPPROTO_TCP explicitly
Otherwise perl tries to bind+listen on a UDP socket if the
TCP socket fails - which is a waste since we're looking for
TCP ports.
Additionall since UDP doesn't support listen(), perl will
return EOPNOTSUPP instead of, say, EADDRINUSE. (We don't
care about the error in this code though.)
2017-05-31 07:34:14 +02:00
Wolfgang Bumiller
c14960cc1d tools: unused ports: optional address parameter
While it should be impossible to bind to a wildcard address
when the port is in use by any other address there's one
case where this is allowed, and that's when the port is in
use by an ipv6 address while trying to bind to an ipv4
wildcard.
This currently happens when qemu finds ::1 for the
'localhost' we pass to qemu's spice address while we're
resolving the local nodename via IPv4.
2017-05-31 07:32:17 +02:00
Thomas Lamprecht
c8e94d4bb5 swap raw syscall numbers with syscall.ph for easier porting
Raw syscall numbers were not platform independent, so replace them
with the helpers provided from the syscall.ph perl bits helper.

This makes reading the code easier as a nice side effect.

As syscall.ph is not an ordinary module and makes problems when it is
required by multiple modules we make a own module PVE::Syscall which
loads it and allows to export the necessary constants in a sane way.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2017-05-24 11:24:34 +02:00
Wolfgang Bumiller
d9f86d0d87 Tools: make file-locking aware of external exception sources
Previously an external exception (eg. caused by a SIGARLM in a code
which is already inside a run_with_timeout() call) could happen in
various places where we did not properly this situation.
For instance after calling $lock_func() but before reaching the cleanup
code. In this case a lock was leaked.
Additionally the code was broken in that it used perl's automatic hash
creation side effect ($a->{x}->{y} implicitly initializing $a->{x} with
an empty hash when it did not exist). The effect was that if our own
time out was triggered after the initial check for an existing file
handle inside $lock_func() happened (extremely rare since perl would have
to be running insanely slow), the cleanup did:

    if (my $fh = $lock_handles->{$$}->{$filename}->{fh}) {

This recreated $lock_handles->{$$}->{$filename} as an empty hash.
A subsequent call to lock_file_full() will think a file descriptor
already exists because the check simply used:

    if (!$lock_handles->{$$}->{$filename}) {

While this could have been a one-line fix for this one particular case,
we'd still not be taking external timeouts into account causing the
first issue described above.
2017-05-12 11:40:26 +02:00
Dietmar Maurer
6d46baf63a mark decode_utf8_parameters() as depreciated 2017-05-02 11:51:29 +02:00
Thomas Lamprecht
38d9aa1247 run_command: default exit code to -1
When the child process running the command got  an signal or failed
to execute exitcode was still undefined as we extract it just only
after the signal/failed to execute check.
This led to:
 > Use of uninitialized value in numeric ne (!=) at
 > /usr/share/perl5/PVE/API2/Qemu.pm line 1433.
errors if we used run_commands `noerr` param and checked for the
commands exit code.

So just default the exit code to -1 for such cases.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2017-04-10 14:50:13 +02:00
Dietmar Maurer
ccf60d3bb8 PVE::Tools::dump_journal: allow to filter a specific service 2017-04-04 06:35:24 +02:00
Emmanuel Kasper
d3c8f0c182 Add utility subroutine to get the fully qualified domain name of a host 2017-04-03 11:07:01 +02:00
Dietmar Maurer
9867ff7a83 PVE::Tools::encrypt_pw() - new helper copied from pve-access-control 2017-03-30 17:49:26 +02:00
Dominik Csapak
0f3f314ed7 add keeplocale parameter to run_command
since the "lang" param has not worked, introduce a "keeplocale"
parameter instead.

the default behaviour is the same (set LC_ALL to 'C'), but we can use
the parameter to keep the locale from the host (eg. for the vncshell)

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2017-03-09 09:24:52 +01:00
Dominik Csapak
3c476ed580 (maybe) fixes #1229: fix port reservation
when reserving ports, we use lock_file to lock the
reservation file, but then use file_set_content which
writes a new file and renames it, making the lock invalid
and different processes waiting for the lock get inconsistent
data

instead we use a designated lock file for the lock, so that we don't
lose the lock when writing the reservation file

this should fix the problem that sometimes multiple vms get the
same vnc/spice port

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2017-02-16 15:02:55 +01:00
Dominik Csapak
813a5c0d26 fix trailing whitespaces
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2017-02-16 09:15:47 +01:00
Dietmar Maurer
034a8181c6 safe_read_from: add filename parameter to improve error messages 2016-11-28 07:42:34 +01:00
Wolfgang Bumiller
77b2b96ffc tempfile: use /tmp for fallback-tempfiles
At this point we know it's not a tmpfs (as tmpfs definitely
supports O_TMPFILE), so /tmp makes more sense than /run as
default path.
2016-11-02 12:47:05 +01:00
Wolfgang Bumiller
7e1ee743f4 tempfile: unliked-file fallback
some file systems (eg. ZFS) don't support O_TMPFILE
2016-11-02 12:44:35 +01:00
Wolfgang Bumiller
f0cfc20e65 Fix #1188: tempfile: use /run by default
as /tmp is not a tmpfs by default and some file systems
(like ZFS) don't support O_TMPFILE
2016-11-02 12:43:16 +01:00
Wolfgang Bumiller
ce338f4fbc harden file_set_contents against symlink attacks 2016-08-16 17:12:55 +02:00
Wolfgang Bumiller
123921731a tools: optional prefix for random_ether_addr 2016-07-14 09:01:01 +02:00
Wolfgang Bumiller
d743b69c4b fix mac address generation limitation
Commit de9a267 introduced vec() to optimize the generation
by using binary operations instead of converting back and
forth between hex and strings, but forgot to switch over to
the binary sha1 method. This resulted in only the first 6
hex digits of the output string making up the address.
2016-07-05 13:42:30 +02:00
Wolfgang Bumiller
28705ff6d1 df: untaint the result 2016-07-04 14:13:41 +02:00
Fabian Grünbichler
c9c6d91073 catch malformed mailto/mailfrom in sendmail 2016-06-09 17:55:38 +02:00
Fabian Grünbichler
1a0c010327 remove duplicate 'set -o pipefail' 2016-06-07 10:37:25 +02:00
Wolfgang Bumiller
0b9cf991e5 added: enter_systemd_scope
This essentially performas the task of systemd-run while
also waiting for the job to finish.

With the systemd-run version in jessie we run into a race
condition where the executed process can start forking child
processes before the systemd daemon is done setting up the
scope's cgroups, causing the children to NOT be included in
the cgroups. This means the child processes (in our case
qemu) will not adhere to the limits we want to apply to it
via cgroups.

enter_systemd_scope() performs the setup task of systemd-run
and waits for the job to finish, after this we can spawn the
qemu process without systemd-run.
2016-06-03 11:26:13 +02:00
Wolfgang Bumiller
c064776576 Allow O_PATH and O_TMPFILE to be exported 2016-06-01 11:29:59 +02:00
Wolfgang Bumiller
21c56a963f added: openat, mkdirat 2016-06-01 11:29:49 +02:00
Dietmar Maurer
0a7de8204e sort keymap array 2016-04-30 11:54:20 +02:00
Fabian Grünbichler
48df47a466 Add validate_ssh_public_keys
validate format of SSH public keys using ssh-keygen -l and
temp files.
2016-04-05 12:24:38 +02:00
Dietmar Maurer
5a873e6d35 sendmail: minor cleanups 2016-04-05 06:27:29 +02:00
Thomas Lamprecht
b61a47dbeb Tools: add sendmail
can be used to send multipart (HTML, plain) mails to one or more
recipients at once.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2016-04-05 06:21:45 +02:00
Wolfgang Bumiller
26598a513b Tools: tempfile and tempfile_contents 2016-04-05 06:18:41 +02:00
Wolfgang Bumiller
d0229d1d82 fix O_PATH value 2016-04-05 06:14:12 +02:00
Thomas Lamprecht
19e95cd08f Add since and until parameter to dump_journal
journalctl can check their validness itself
2016-03-02 06:22:47 +01:00
Wolfgang Bumiller
44acb12c27 added syncfs syscall and sync_mountpoint helper 2016-02-11 11:24:11 +01:00
Fabian Grünbichler
f127adaba5 Implement refcounting for flocks
This was already implemented in PVE::LXC::lock_aquire() and
lock_release(). Enabling refcounting in the general
PVE::Tools::lock_file() and lock_file_full() methods allows
us to use one code base for flocking.

Furthermore, we could get rid of various xx_no_lock methods
that were required because the old non-refcounting version
did not support nested flocks (the inner most flock would
close the file handle and thus release the flock).
2016-02-10 11:12:12 +01:00
Wolfgang Bumiller
891b224a8f Tools: add setns system call 2016-01-23 08:59:07 +01:00
Thomas Lamprecht
b148e99f3f Output also lockname if it cannot be acquired
If we can't acquire the lock in lock_file_full and get interrupted
by a signal inqeual to EINTR (e.g. SIGTERM), output also it's name
in the error message to allow better debugging.

Also fix a typo.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2015-12-19 09:05:00 +01:00
Thomas Lamprecht
7e82692825 run_command: return exit code and add noerr
Allow to return the exit code of the executed command.
And as we do not reach the return of the exit code if it was not 0,
a noerr parameter is also needed so we can suppress the 'command
failed' die in case of an exit code unequal to 0.

This is required as some programs return another value than 0 when
they succeed, For example `systemctl list-jobs` returns  a value
>= 0 on a successful execution, normally 1.
Without this patch a run_command call to `systemctl list-jobs` gets
marked as failed although it was successful.

This does not break current behaviour in any way as setting the
noerr parameter is required to return something other than 0 or
undef, which are equal in a boolean comparison.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2015-11-30 12:59:45 +01:00
Wolfgang Link
23e0e0d786 add function file_copy
to have a save copy.
2015-11-26 08:08:31 +01:00
Wolfgang Bumiller
be8f0477bc fix CLONE constant declaration 2015-10-30 11:04:51 +01:00
Wolfgang Bumiller
817c6be02c Tools: make unshare behave like other perl syscalls
Most syscall wrappers in perl return 1 on success and our
current use of Tools::unshare isn't using the return value
(yet), so let's fix this while we can.

Also it seems to make sense to use prototyping on syscalls
to add some compile-time argument checking.
2015-10-30 11:03:55 +01:00
Wolfgang Bumiller
97c8c8577d Tools::df: fork and use Filesys::Df
Instead of depending on the 'df' commandline tool do a
fork() to create a killable process and run Filesys::Df,
returning the data over a pipe.
2015-10-30 07:00:37 +01:00
Dietmar Maurer
85d5625a15 random_ether_addr: code cleanups 2015-10-09 11:48:25 +02:00
Philipp Marek
de9a267fec Shorter implementation of random_ether_addr(). 2015-10-09 11:46:50 +02:00
Wolfgang Bumiller
cd9bd2526a Tools::IPV4OCTET: move longer alternatives forward
In an alternation /a|b|c/ the first match matches, so while
'1.1.1.121' matches /^$IPV4RE$/ (note the ^ and $ anchors),
parsing a line like /nameserver ($IPV4RE)/ would only
extract '1.1.1.12', ignoring the last '1' due to the /[1-9]/
alternative matching before the /1[0-9]/ one.
2015-10-05 12:31:24 +02:00
Wolfgang Bumiller
176b1186bd INotify::read_etc_resolv_conf: ipv6 support 2015-10-05 12:30:44 +02:00
Wolfgang Bumiller
952fd95e84 Tools: add unshare system call
Including the important CLONE_* constants.
2015-09-17 13:20:15 +02:00
Wolfgang Bumiller
fcdc0cfc8a Tools::run_command: array of arrays special case
Passing an array of arrays to run_command will cause each
array to be treated like a command piped to the following
command. Each argument is shell-quoted unless its passed by
reference.
2015-09-16 09:08:53 +02:00
Wolfgang Bumiller
bd9c3a3654 document run_command 2015-09-16 09:07:42 +02:00
Wolfgang Bumiller
c38cea65b6 Tools::run_with_timeout improvement + hires alarm
The following situations could lead to the 'unknown error':
1) As commented, when the alarm triggered after the first
signal handler was installed and before the new alarm was
installed. In this case the $signalcount was increased,
and worse: the original signal handler was never called.

2) When $code died, since the call itself wasn't in an eval
block, we'd leave the eval block containing the inner alarm
signal handler. Then there's a time window from leaving the
signal block (and with that restoring the first installed
only-counting signal-handler) and reaching the code to
restore the previous alarm where the counting alarm handler
could get triggered by our own alarm set before running
$code. In this case at least the the old alarm would be
restored, but we'd still trigger the 'unknown error'.

The new code starts off by suspending the original alarm
before installing any signal handler, then installing the
timeout handler inside the first eval block. The $code is
then run inside another eval block to make sure we reach the
alarm(0) statement before restoring the old signal handler
and alarm timeout.
2015-08-28 10:45:26 +02:00
Wolfgang Bumiller
b261377727 Add generic parse_host_and_port function
Added a generic function to split a host+port string to the
host and port part supporting the two most common ipv6
notations beside domains and ipv4: with brackets for the
address or a dot as port separator.
2015-08-25 12:58:09 +02:00
Dietmar Maurer
6de95a662f new helper dump_journal to view systemd journal 2015-06-09 12:15:41 +02:00
Wolfgang Bumiller
22d4efe612 fix a regex typo in run_command
m/|/ is always true as it effectively matches 'nothing or nothing
anywhere in a string'
looks like it was supposed to be m/\|/
2015-05-28 10:28:44 +02:00
Wolfgang Bumiller
e43b3a0f50 prevent the use of AI_ADDRCONFIG
perl's IO::Socket::IP passes AI_ADDRCONFIG if no GetAddrInfoFlags are passed,
which is often useful but also causes it to error when explicitly trying to
bind to 127.0.0.1 when there are no _other_ IPv4 addresses present.
2015-05-27 15:32:08 +02:00
Wolfgang Bumiller
a0b6ef523a new helper: getaddrinfo_all
As it's commonly used in ipv6 support code a getaddrinfo wrapper passing
default flags and dealing with the (err,result) tuple was added.
2015-05-12 10:35:35 +02:00
Wolfgang Bumiller
467752183d add a socket family argument to next_*_port functions
Instead of assuming a local address of 0.0.0.0, the next_*_port family
of functions now takes an optional packet family argument (AF_INET/AF_INET6),
used for ipv6 support.
2015-05-12 10:35:31 +02:00
Wolfgang Bumiller
a956854f8d add utility to fetch the socket family for a hostname 2015-05-08 12:36:30 +02:00
Wolfgang Bumiller
8df6b79439 provide Tools::unpack_sockaddr_in46 2015-05-08 12:36:11 +02:00
Wolfgang Bumiller
00dc9d0fa9 Use IO::Socket::IP instead of INET 2015-05-08 12:35:15 +02:00
Dietmar Maurer
b51b16e6f5 rename data to src 2015-02-27 16:57:20 +01:00