Commit Graph

77 Commits

Author SHA1 Message Date
Lennart Poettering ae2a15bc14 macro: introduce TAKE_PTR() macro
This macro will read a pointer of any type, return it, and set the
pointer to NULL. This is useful as an explicit concept of passing
ownership of a memory area between pointers.

This takes inspiration from Rust:

https://doc.rust-lang.org/std/option/enum.Option.html#method.take

and was suggested by Alan Jenkins (@sourcejedi).

It drops ~160 lines of code from our codebase, which makes me like it.
Also, I think it clarifies passing of ownership, and thus helps
readability a bit (at least for the initiated who know the new macro)
2018-03-22 20:21:42 +01:00
Lennart Poettering d56fced9e0 fileio: port parse_env_file_internal() to use _cleanup_free_ (#8511) 2018-03-21 11:59:56 +01:00
Lennart Poettering 8ac2f74fb6 tree-wide: make use of fsync_directory_of_file() all over the place
Let's make use this at various places we call fsync(), to make things
fully reliable, as the kernel devs suggest to first fsync() files and
then fsync() the directories they are located in.
2018-02-20 15:39:31 +01:00
Lennart Poettering ad5d4b1703 cocci: use strempty() at more places
This shortens the code by a few lines.
2018-01-10 17:11:19 +01:00
Lennart Poettering 99c61f6b00 fileio: minor tweak to executable_is_script()
If read_line() returns ENOBFUS this means the line was overly long. When
we use this for checking whether an executable is a script, then this
shouldn't be propagated as-is, but simply as "this is not a script".
2018-01-04 13:28:24 +01:00
Lennart Poettering 91dc2bf74d fileio: tweak write_string_stream_ts() to write out trailing \n in one go even if buffering is off
This tweaks write_string_stream_ts() in one minor way: when stdio
buffering has been turned off, let's append the newline we shall append
to the buffer we write ourselves so that the kernel only gets one
syscall for the result. When buffering is enabled stdio will take care
of that anyway.

Follow-up for #7750.
2018-01-04 13:28:24 +01:00
Mike Gilbert ba8b8c9e40 fileio: write_string_stream_ts: check for file errors immediately 2017-12-29 08:45:30 -05:00
Mike Gilbert 94d3b60ff6 fileio: write_string_stream_ts: return errors from fputs and fputc
Ignoring errors from these functions may mask errors returned by the
kernel.

Fixes: https://github.com/systemd/systemd/issues/7744
2017-12-29 08:45:30 -05:00
Lennart Poettering fbd0b64f44
tree-wide: make use of new STRLEN() macro everywhere (#7639)
Let's employ coccinelle to do this for us.

Follow-up for #7625.
2017-12-14 19:02:29 +01:00
Lennart Poettering 35bbbf85e0 basic: turn off stdio locking for a couple of helper calls
These helper calls are potentially called often, and allocate FILE*
objects internally for a very short period of time, let's turn off
locking for them too.
2017-12-14 10:46:19 +01:00
Yu Watanabe 1bb8d1fce8
Merge pull request #7618 from tiagosh/sysctl_use_read_line
Make systemd-sysctl use read_line() and LONG_LINE_MAX
2017-12-14 13:58:53 +09:00
Tiago Salem Herrmann 12ec9c3099 sysctl: disable buffer while writing to /proc
fputs() writes only first 2048 bytes and fails
to write to /proc when values are larger than that.
This patch adds a new flag to WriteStringFileFlags
that make it possible to disable the buffer under
specific cases.
2017-12-13 15:03:41 -02:00
Lennart Poettering 234519ae6d tree-wide: drop a few == NULL and != NULL comparison
Our CODING_STYLE suggests not comparing with NULL, but relying on C's
downgrade-to-bool feature for that. Fix up some code to match these
guidelines. (This is not comprehensive, the coccinelle output for this
is unfortunately kinda borked)
2017-12-11 16:05:40 +01:00
Yu Watanabe 7accca234d fileio: include sys/mman.h 2017-11-26 02:40:23 +09:00
Zbigniew Jędrzejewski-Szmek 53e1b68390 Add SPDX license identifiers to source files under the LGPL
This follows what the kernel is doing, c.f.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5fd54ace4721fc5ce2bb5aef6318fcf17f421460.
2017-11-19 19:08:15 +01:00
Lennart Poettering 57d6f70019 fileio: make use of DEFINE_TRIVIAL_CLEANUP_FUNC where it makes sense 2017-11-13 10:24:03 +01:00
Zbigniew Jędrzejewski-Szmek 3f6914175c util-lib: mark variable with _unused_ to silence clang warning
_unused_ means "the variable is meant to be possible unused and gcc
will not generate a warning about it", which is exactly what we need here,
since we're only declaring it for the side effect of _cleanup_.
2017-11-01 23:10:25 +01:00
Zbigniew Jędrzejewski-Szmek a2deeb41f6 Merge pull request #6891 from poettering/read-line
add read_line() helper as bounded getline() and make use of it at some places
2017-09-24 20:51:01 +02:00
Zbigniew Jędrzejewski-Szmek 2e33df93de fileio: return 0 from read_one_line_file on success
Fixup for f4b51a2d09. Suggested by Evgeny Vereshchagin.
2017-09-24 14:27:21 +02:00
Zbigniew Jędrzejewski-Szmek f858e5148e fileio: use _cleanup_ for FILE unlocking 2017-09-23 11:08:57 +02:00
Lennart Poettering 5a89faf0e0 fileio: initialize errno to zero before we do fread()
if there was something in the read buffer already errno might not be set
on error, let's detect that case.
2017-09-22 21:05:03 +02:00
Lennart Poettering ff0e7e05c9 fileio: try to read one byte too much in read_full_stream()
Let's read one byte more than the file size we read from stat() on the
first fread() invocation. That way, the first read() will already be
short and indicate eof to fread().

This is a minor optimization, and replaces #3908.
2017-09-22 21:03:33 +02:00
Lennart Poettering 9dd1b1e869 fileio: move fsync() logic into write_string_stream_ts()
That way, write_string_stream_ts() becomes more powerful, and we can
remove duplicate code from  write_string_file_atomic() and
write_string_file_ts().
2017-09-22 20:59:39 +02:00
Lennart Poettering b183713383 fileio: make write_string_stream() accept flags parameter
Let's make write_string_stream() and write_string_file() more alike, and
pass the same flag set so that we can remove a number of boolean
parameters.
2017-09-22 20:55:34 +02:00
Lennart Poettering 2eabcc772b fileio: support writing atomic files with timestamp
Let's make sure "ts" is taken into account when writing atomic files,
too.
2017-09-22 20:45:06 +02:00
Lennart Poettering f4b51a2d09 fileio: rework read_one_line_file() on top of read_line() 2017-09-22 20:34:15 +02:00
Lennart Poettering 4f9a66a32d fileio: add new helper call read_line() as bounded getline() replacement
read_line() is much like getline(), and returns a line read from a
FILE*, of arbitrary sizes. In contrast to gets() it will grow the buffer
dynamically, and in contrast to getline() it will place a user-specified
boundary on the line.
2017-09-22 20:34:15 +02:00
Alan Jenkins 265710c205 fileio: rename function parameter to avoid masking global symbol
> glibc exports a function called sync(), we should probably avoid
> overloading that as a variable here locally (gcc even used to warn about
> that, not sure why it doesn't anymore), to avoid confusion around what
> "if (sync)" actually means
2017-08-29 10:56:32 +01:00
Alan Jenkins 0675e94ab5 "Don't fear the fsync()"
For files which are vital to boot

1. Avoid opening any window where power loss will zero them out or worse.
   I know app developers all coded to the ext3 implementation, but
   the only formal documentation we have says we're broken if we actually
   rely on it.  E.g.

   * `man mount`, search for `auto_da_alloc`.
   * http://www.linux-mtd.infradead.org/faq/ubifs.html#L_atomic_change
   * https://thunk.org/tytso/blog/2009/03/15/dont-fear-the-fsync/

2. If we tell the kernel we're interested in writing them to disk, it will
   tell us if that fails.  So at minimum, this means we play our part in
   notifying the user about errors.

I refactored error-handling in `udevadm-hwdb` a little.  It turns out I did
exactly the same as had already been done in the `systemd-hwdb` version,
i.e. commit d702dcd.
2017-08-17 20:26:36 +01:00
Lennart Poettering 4b61c87511 tree-wide: fput[cs]() → fput[cs]_unlocked() wherever that makes sense (#6396)
As a follow-up for db3f45e2d2 let's do the
same for all other cases where we create a FILE* with local scope and
know that no other threads hence can have access to it.

For most cases this shouldn't change much really, but this should speed
dbus introspection and calender time formatting up a bit.
2017-07-21 10:35:45 +02:00
Lennart Poettering df0ff12775 tree-wide: make use of getpid_cached() wherever we can
This moves pretty much all uses of getpid() over to getpid_raw(). I
didn't specifically check whether the optimization is worth it for each
replacement, but in order to keep things simple and systematic I
switched over everything at once.
2017-07-20 20:27:24 +02:00
Zbigniew Jędrzejewski-Szmek 39c38d773f basic/fileio: extend atomic file writing with timestamp setting
There should be no functional change.
2017-05-11 10:23:36 -04:00
Zbigniew Jędrzejewski-Szmek 371328dc74 basic/fileio: use IN_SET 2017-02-21 11:15:51 -05:00
Zbigniew Jędrzejewski-Szmek 2ea8081a55 basic/fileio: fix memleak when discarding an invalid variable
Fixes #5405.
2017-02-21 11:15:50 -05:00
Ray Strode b82f58bfe3 basic: support default and alternate values for env expansion
Sometimes it's useful to provide a default value during an environment
expansion, if the environment variable isn't already set.

For instance $XDG_DATA_DIRS is suppose to default to:

/usr/local/share/:/usr/share/

if it's not yet set. That means callers wishing to augment
XDG_DATA_DIRS need to manually add those two values.

This commit changes replace_env to support the following shell
compatible default value syntax:

XDG_DATA_DIRS=/foo:${XDG_DATA_DIRS:-/usr/local/share/:/usr/share}

Likewise, it's useful to provide an alternate value during an
environment expansion, if the environment variable isn't already set.

For instance, $LD_LIBRARY_PATH will inadvertently search the current
working directory if it starts or ends with a colon, so the following
is usually wrong:

LD_LIBRARY_PATH=/foo/lib:${LD_LIBRARY_PATH}

To address that, this changes replace_env to support the following
shell compatible alternate value syntax:

LD_LIBRARY_PATH=/foo/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

[zj: gate the new syntax under REPLACE_ENV_ALLOW_EXTENDED switch, so
existing callers are not modified.]
2017-02-20 23:32:53 -05:00
Zbigniew Jędrzejewski-Szmek 184d190473 Tighten checking for variable validity
In the future we might want to allow additional syntax (for example
"unset VAR". But let's check that the data we're getting does not contain
anything unexpected.
2017-02-20 23:32:53 -05:00
Zbigniew Jędrzejewski-Szmek ccad1fd07c Allow braceless variables to be expanded
(Only in environment.d files.)

We have only basic compatibility with shell syntax, but specifying variables
without using braces is probably more common, and I think a lot of people would
be surprised if this didn't work.
2017-02-20 23:30:50 -05:00
Ray Strode 37f3ffca27 basic: add new merge_env_file function
merge_env_file is a new function, that's like load_env_file, but takes a
pre-existing environment as an input argument. New environment entries are
merged. Variable expansion is performed.

Falling back to the process environment is supported (when a flag is set).
Alternatively this could be implemented as passing an additional fallback
environment array, but later on we're adding another flag to allow braceless
expansion, and the two flags can be combined in one arg, so there's less
stuff to pass around.
2017-02-20 18:49:14 -05:00
Zbigniew Jędrzejewski-Szmek 99003e01b6 env-util,fileio: immediately replace variables in load_env_file_push()
strv_env_replace was calling env_match(), which in effect allowed multiple
values for the same key to be inserted into the environment block. That's
pointless, because APIs to access variables only return a single value (the
latest entry), so it's better to keep the block clean, i.e. with just a single
entry for each key.

Add a new helper function that simply tests if the part before '=' is equal in
two strings and use that in strv_env_replace.

In load_env_file_push, use strv_env_replace to immediately replace the previous
assignment with a matching name.

Afaict, none of the callers are materially affected by this change, but it
seems like some pointless work was being done, if the same value was set
multiple times. We'd go through parsing and assigning the value for each
entry. With this change, we handle just the last one.
2017-02-20 18:49:14 -05:00
Zbigniew Jędrzejewski-Szmek ac46681881 basic/fileio: add helper function for a set of two common checks 2017-02-20 18:49:14 -05:00
Zbigniew Jędrzejewski-Szmek 504afd7c34 core/manager: split out creation of serialization fd out to a helper
There is a slight change in behaviour: the user manager for root will create a
temporary file in /run/systemd, not /tmp. I don't think this matters, but
simplifies implementation.
2017-02-20 18:49:09 -05:00
Lennart Poettering 676bcb0fc0 util-lib: add easy helpers for temporary directories that rmdir()ed via _cleanup_
This adds mkdtemp_malloc() that is a combination of mkdtemp() plus strdup(). It
initializes its return paremeter only if the temporary directory could be
created successfully, so that the parameter is exactly non-NULL when the
directory exists.

rmdir_and_free() and rmdir_and_freep() are also added, and the latter may be
used inside of _cleanup_ for such a directory string variable, to automatically
rmdir() the directory if it is non-NULL when the scope exits.

rmdir_and_free() is similar to the existing rm_rf_and_free() however, is only
removes a single directory and does not operate recursively.
2016-12-07 18:38:41 +01:00
Zbigniew Jędrzejewski-Szmek 605405c6cc tree-wide: drop NULL sentinel from strjoin
This makes strjoin and strjoina more similar and avoids the useless final
argument.

spatch -I . -I ./src -I ./src/basic -I ./src/basic -I ./src/shared -I ./src/shared -I ./src/network -I ./src/locale -I ./src/login -I ./src/journal -I ./src/journal -I ./src/timedate -I ./src/timesync -I ./src/nspawn -I ./src/resolve -I ./src/resolve -I ./src/systemd -I ./src/core -I ./src/core -I ./src/libudev -I ./src/udev -I ./src/udev/net -I ./src/udev -I ./src/libsystemd/sd-bus -I ./src/libsystemd/sd-event -I ./src/libsystemd/sd-login -I ./src/libsystemd/sd-netlink -I ./src/libsystemd/sd-network -I ./src/libsystemd/sd-hwdb -I ./src/libsystemd/sd-device -I ./src/libsystemd/sd-id128 -I ./src/libsystemd-network --sp-file coccinelle/strjoin.cocci --in-place $(git ls-files src/*.c)

git grep -e '\bstrjoin\b.*NULL' -l|xargs sed -i -r 's/strjoin\((.*), NULL\)/strjoin(\1)/'

This might have missed a few cases (spatch has a really hard time dealing
with _cleanup_ macros), but that's no big issue, they can always be fixed
later.
2016-10-23 11:43:27 -04:00
Topi Miettinen 646853bdd8 fileio: simplify mkostemp_safe() (#4090)
According to its manual page, flags given to mkostemp(3) shouldn't include
O_RDWR, O_CREAT or O_EXCL flags as these are always included. Beyond
those, the only flag that all callers (except a few tests where it
probably doesn't matter) use is O_CLOEXEC, so set that unconditionally.
2016-09-13 08:20:38 +02:00
Yann E. MORIN 1d9ed17178 basic/fileio: we always have O_TMPFILE now
fileio makes use of O_TMPFILE when it is available.

We now always have O_TMPFILE, defined in missing.h if missing
from the toolchain headers.

Have fileio include missing.h and drop the guards around the
use of O_TMPFILE.
2016-08-29 12:49:10 +02:00
Zbigniew Jędrzejewski-Szmek 3bb81a80bd Merge pull request #3818 from poettering/exit-status-env
beef up /var/tmp and /tmp handling; set $SERVICE_RESULT/$EXIT_CODE/$EXIT_STATUS on ExecStop= and make sure root/nobody are always resolvable
2016-08-05 20:55:08 -04:00
Vito Caputo 82b103a7ce fileio: fix MIN/MAX mixup (#3896)
The intention is to clamp the value to READ_FULL_BYTES_MAX, which
would be the minimum of the two.
2016-08-05 00:09:23 -04:00
Vito Caputo c2d11a6302 fileio: fix read_full_stream() bugs (#3887)
read_full_stream() _always_ allocated twice the memory needed, due to
only breaking the realloc() && fread() loop when fread() returned 0,
requiring another iteration and exponentially enlarged buffer just to
discover the EOF condition.

This also caused file sizes >2MiB && <= 4MiB to erroneously be treated
as E2BIG, due to the inappropriately doubled buffer size exceeding
4*1024*1024.

Also made the 4*1024*1024 magic number a READ_FULL_BYTES_MAX constant.
2016-08-04 22:52:02 +02:00
Lennart Poettering 992e8f224b util-lib: rework /tmp and /var/tmp handling code
Beef up the existing var_tmp() call, rename it to var_tmp_dir() and add a
matching tmp_dir() call (the former looks for the place for /var/tmp, the
latter for /tmp).

Both calls check $TMPDIR, $TEMP, $TMP, following the algorithm Python3 uses.
All dirs are validated before use. secure_getenv() is used in order to limite
exposure in suid binaries.

This also ports a couple of users over to these new APIs.

The var_tmp() return parameter is changed from an allocated buffer the caller
will own to a const string either pointing into environ[], or into a static
const buffer. Given that environ[] is mostly considered constant (and this is
exposed in the very well-known getenv() call), this should be OK behaviour and
allows us to avoid memory allocations in most cases.

Note that $TMPDIR and friends override both /var/tmp and /tmp usage if set.
2016-08-04 16:27:07 +02:00
Lennart Poettering 87410f166e fileio: imply /tmp as directory if passed as NULL to open_tmpfile_unlinkable()
We can make this smarter one day, to honour $TMPDIR and friends, but for now,
let's just use /tmp.
2016-07-25 20:35:04 +02:00