Commit graph

402 commits

Author SHA1 Message Date
Thomas Haller ca7bb15591
shared: cleanup dlopening libjansson depending on configure options
- assert that WITH_JANSSON and JANSSON_SONAME are defined consistently.
  This check ensures that we can check at compile time that nm_json_vt()
  will always fail (because JANSSON_SONAME) is undefined.
  That is interesting, because this means you can do a compile time
  for !WITH_JANSSON, and know if nm_json_vt() will *never* succeed.
  With that, we could let the linker know when the code is unused
  and remove all uses of nm_json_vt(), without using the traditional
  conditional compilation with "#if WITH_JANSSON". But of course, we
  currently don't do this micro optimization to remove defunct code.

- drop the "mode" helper variable and pass the flags directly to
  dlopen().
2020-07-09 12:57:15 +02:00
Thomas Haller 18692faa9f
shared: drop unused code from "shared/nm-glib-aux/nm-jansson.h" 2020-07-09 12:57:15 +02:00
Thomas Haller 7054b11328
all: bump libjansson dependency to 2.7
jansson 2.7 was released October 2014. It's also in Ubuntu 16.06.
Other distros (like CentOS 7.5 and Debian Stretch/9) have both newer
versions.

Bump the requirement, simply because our CI does not use such old version
so it's not clear whether it works at all.
2020-07-09 12:57:15 +02:00
Thomas Haller ae5e8fc26b
shared/tests: add test for checking "nm-json-aux.h"
Our "nm-json-aux.h" redefines various things from <jansson.h> header.

Add a unit test that checks that what we redefine exactly matches what
libjansson would provide, so that they are compatible.
2020-07-09 12:57:15 +02:00
Thomas Haller 57de0c27a7
shared,libnm: rename nm_json_aux_gstr_*() API to nm_json_gstr_*() 2020-07-09 11:47:06 +02:00
Thomas Haller 4a7da1ca4b
shared: merge nm-glib-aux/nm-json.[hc] into nm-json-aux.[hc]
They serve a similar purpose.

Previously, nm-json-aux.h contained the virtual function table for accessing
the dynamically loaded libjansson. But there is no reason why our own
helper functions from nm-json.h cannot be there too.
2020-07-09 11:47:06 +02:00
Thomas Haller 3814467b88
libnm,shared: move nm-json.[hc] to shared/nm-glib-aux
nm-json.[hc] uses libjansson, but only loads it at runtime with dlopen. There
is no more run compile time dependency. Move it to shared, so that it can be
(theoretically) used by other components.

Also, drop the conditional compilation. Granted, if you don't build with
libjansson enabled, then the JANSSON_SONAME define is unset and the code
will fail to load at runtime (which is fine). However, we can still build
against our JSON wrappers. The code savings of conditional build are minimal
so drop it.
2020-07-09 11:47:05 +02:00
Beniamino Galvani 4599be093e libnm-core: don't print value for no-value attributes 2020-07-08 09:43:06 +02:00
Beniamino Galvani ee946ca27d libnm-core: pass variant-attribute-spec to format function
The output of nm_utils_format_variant_attributes() must be accepted by
nm_utils_parse_variant_attributes(), producing the initial attributes.

The latter has a special handling of some attributes, depending on the
input NMVariantAttributeSpec list. For example, if the
NMVariantAttributeSpec is a boolean with the 'no_value' flag, the
parser doesn't look for a value.

Pass the NMVariantAttributeSpec list to the format function so that it
can behave in the same way as the parse one.
2020-07-08 09:43:06 +02:00
Thomas Haller 1d6e208c12
shared: move NM_AUTO_DEFINE_FCN*(), nm_auto_free and nm_clear_pointer() to "nm-std-aux.h" 2020-07-07 22:25:42 +02:00
Thomas Haller 4b63297d95
shared: drop definitions for bool/true/false from "nm-macros-internal.h"
Previously, we did not have a hard dependency on C99. Nowadays, we
actually build against C11, so we have <stdbool.h>. These definitions
are no longer necessary nor do we care about building against plain
C89.
2020-07-07 22:25:42 +02:00
Thomas Haller 3b80c6c28f
shared: make NM_BOOLEAN_EXPR() macro composable and use it for _G_BOOLEAN_EXPR()
We redefine _G_BOOLEAN_EXPR(), so let it use NM_BOOLEAN_EXPR().

Also, we use G_LIKELY() (and thus NM_BOOLEAN_EXPR()) inside nm_assert(),
and we use nm_assert() in some macros. To be able to nest nm_assert()
calls, we need to create unique variable names for NM_BOOLEAN_EXPR().
2020-07-07 21:52:22 +02:00
Thomas Haller f0deb24249
shared: move various basic helpers from "nm-macros-internal.h" to "nm-std-aux.h"
These are generally useful and independent of glib. Move them to
nm-std-aux, which has no glib dependency.
2020-07-07 21:33:25 +02:00
Yuri Chornoivan 4e33f8cd89
all: fix minor typos
https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/565
2020-07-07 11:33:46 +02:00
Thomas Haller d407c1271c
shared: move NM_SET_OUT() to "nm-std-aux.h" 2020-07-06 14:11:22 +02:00
Thomas Haller 220825836a
shared: move nm_utils_get_next_realloc_size() to nm-std-aux 2020-07-06 14:11:22 +02:00
Thomas Haller b109d63376
shared: add min/max macros to "nm-std-aux.h" 2020-07-06 11:45:37 +02:00
Thomas Haller 5361317f68
shared: add macros for declaration attribute to "nm-std-aux.h" 2020-07-06 11:45:37 +02:00
Thomas Haller 030d68aef7
shared: add nm_assert() to "nm-std-aux.h"
Having assertion macros that are disabled by default, is not
only useful for our glib code, but should also be available
for nm-std-aux. Move the macros.
2020-07-06 11:45:37 +02:00
Sayed Shah 7337ab8959
all: fix typo in man pages
There should be a comma after 'Otherwise' and 'Currently'.

https://bugzilla.redhat.com/show_bug.cgi?id=1852452

https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/560
2020-07-03 10:48:04 +02:00
Thomas Haller e2bd722358
shared: refactor nm_utils_parse_next_line() and add tests
- add unit test for nm_utils_parse_next_line()

- as line delimiter also accept "\r\n" and "\r" (beside "\n", "\0" and
  EOF).

- fix returning lines with embedded "\0" characters. The line ends
  on the first "\n" or "\0", whatever comes first. The code before
  didn't ensure that with:

     line_end = memchr (line_start, '\n', *inout_len);
     if (!line_end)
         line_end = memchr (line_start, '\0', *inout_len);
2020-07-03 10:34:27 +02:00
Thomas Haller e7357419cd
shared: add nm_str_buf_finalize_to_gbytes() helper 2020-07-03 10:34:26 +02:00
Antonio Cardace aa5959a595
nm-shared-utils: add util to parse out lines from a string
https://bugzilla.redhat.com/show_bug.cgi?id=1821787
2020-06-26 16:47:56 +02:00
Thomas Haller 45b346554a
shared: add nm_str_buf_reset() helper 2020-06-26 09:29:53 +02:00
Thomas Haller d83908b6a1
shared: add nm_utils_escaped_tokens_escape_strbuf*() helpers 2020-06-26 09:29:53 +02:00
Thomas Haller a5a5656582
shared: add nm_utils_escaped_tokens_escape_unnecessary() util 2020-06-26 09:29:53 +02:00
Thomas Haller 5222f1b5ff
shared: add nm_str_buf_append_required_delimiter() 2020-06-26 09:29:52 +02:00
Thomas Haller 85e27b1f9c
shared: add nm_str_buf_append_c_hex() helper 2020-06-26 09:29:52 +02:00
Thomas Haller 069be33fbd
shared: add nm_hexchar() helper 2020-06-26 09:29:52 +02:00
Thomas Haller d53abfd989
shared: add nm_str_buf_append0() and nm_str_buf_append_len0() helper
These are basically nm_str_buf_append()/nm_str_buf_append_len() and
nm_str_buf_get_str() in one.
2020-06-26 09:29:52 +02:00
Thomas Haller 506f95ecaf
shared: add NM_UTILS_GET_NEXT_REALLOC_SIZE_32 and _40 macros 2020-06-26 09:29:51 +02:00
Thomas Haller de4df9f529
shared: return non-const pointer from nm_str_buf_get_str()
It's more convenient in certain cases. The user is allowed
to modified the content of the returned buffer.
2020-06-26 09:29:51 +02:00
Thomas Haller 081650eb67
shared: avoid copying empty string in nm_str_buf_append_printf() 2020-06-25 22:46:27 +02:00
Thomas Haller 10779d545a
shared: add nm_utils_strsplit_quoted()
We want to parse "/proc/cmdline". That is space separated with support
for quoting and escaping. Our implementation becomes part of stable
behavior, and we should interpret the kernel command line the same way
as the system does. That means, our implementation should match
systemd's.
2020-06-23 00:42:37 +02:00
Thomas Haller a2142e884b
shared: add nm_str_buf_append_c_repeated() helper 2020-06-22 21:33:59 +02:00
Thomas Haller c6809df4cd
shared: make NM_STR_BUF_INIT() an inline function
In the previous form, NM_STR_BUF_INIT() was a macro. That makes sense,
however it's not really possible to make that a macro without evaluating
the reservation length multiple times. That means,

    NMStrBuf strbuf = NM_STR_BUF_INIT (nmtst_get_rand_uint32 () % 100, FALSE);

leads to a crash. That is unfortunate, so instead make it an inline
function that returns a NMStrBut struct. Usually, we avoid functions
that returns structs, but here we do it.
2020-06-22 21:20:03 +02:00
Thomas Haller d69f057a65
shared: add nm_strvarray_get_strv_non_empty() helper 2020-06-22 11:57:25 +02:00
Thomas Haller fd34fe50a2
shared: fix string truncation in nm_str_buf_append_printf()
If g_vsnprintf() returns that it wants to write 5 characters, it
really needs space for 5+1 characters. If we have 5 characters
available, it would have written "0123\0", which leaves the buffer
broken.

Fixes: eda47170ed ('shared: add NMStrBuf util')
2020-06-21 12:41:53 +02:00
Thomas Haller 83c79bc7a8
shared: allow empty NMStrBuf buffers with un-allocated memory
Previously, for simplicity, NMStrBuf did not support buffers without any
data allocated. However, supporting that has very little
overhead/complexity, so do it.

Now you can initialize buffers to have no data allocated, and when
appending data, it will automatically grow.
2020-06-20 19:22:04 +02:00
Thomas Haller fff812e255
shared: refactor nm_utils_strdict_to_variant_ass() to use nm_utils_named_values_from_strdict()
It is pretty much the same code this way, but shorter.
2020-06-19 17:07:26 +02:00
Thomas Haller cdb38df7e5
shared,core: rename and move function to nm_utils_strdict_to_variant_asv() 2020-06-19 17:07:26 +02:00
Thomas Haller ee9e1ceefc
shared: avoid allocating temporary buffer for nm_utils_named_values_from_strdict()
Iterating hash tables gives an undefined order. Often we want to have
a stable order, for example when printing the content of a hash or
when converting it to a "a{sv}" variant.

How to achieve that best? I think we should only iterate the hash once,
and not require additional lookups. nm_utils_named_values_from_strdict()
achieves that by returning the key and the value together. Also, often
we only need the list for a short time, so we can avoid heap allocating
the list, if it is short enough. This works by allowing the caller to
provide a pre-allocated buffer (usually on the stack) and only as fallback
allocate a new list.
2020-06-19 17:07:25 +02:00
Thomas Haller 4d6b96b48f
shared: make NMUtilsNamedValue.value_ptr non const
If the value pointer is const, it is commonly inconvenient and requires
a cast. Requiring casts on a common base does not increase type safety,
but is annoying.
2020-06-19 17:07:19 +02:00
Thomas Haller edfe9fa9a2
glib: always re-implement g_steal_pointer()
g_steal_pointer() is marked as GLIB_AVAILABLE_STATIC_INLINE_IN_2_44,
that means we get a deprecated warning. Avoid that. We anyway
re-implement the macro so that we can use it before 2.44 and so
that it always does the typeof() cast.
2020-06-15 15:56:30 +02:00
Thomas Haller 393bc8c8f6
shared: add nm_utils_buf_utf8safe_escape_cp() helper 2020-06-11 16:49:26 +02:00
Thomas Haller 39127758bd
shared: add nm_utils_ether_addr_equal(), nm_utils_ether_addr_cmp() 2020-06-11 12:00:52 +02:00
Thomas Haller fce73b1c82
shared: add nm_g_variant_builder_add_sv_*() helpers 2020-06-11 12:00:52 +02:00
Beniamino Galvani f695dd8de3 libnm-core: support variant attributes of type int32 and uint64 2020-06-08 15:31:41 +02:00
Beniamino Galvani f768bd8091 shared: add FIXME about interpretation of variant-attribute bytestrings 2020-06-08 15:31:41 +02:00
Thomas Haller ef9fe85096
shared: move _nm_utils_format_variant_attributes*() API to "shared/nm-glib-aux"
This has no dependency on libnm, libnm-core, or src. Move it to the
general purpose toolbox.
2020-05-14 17:21:12 +02:00
Thomas Haller bb19f6e29c
shared: add NM_UTILS_NAMED_VALUE_INIT() macro 2020-05-13 10:28:04 +02:00
Thomas Haller 0f22f77b1c
shared: support stripping whitespace from nm_utils_buf_utf8safe_unescape()
When parsing user input if is often convenient to allow stripping whitespace.
Especially with escaped strings, the user could still escape the whitespace,
if the space should be taken literally.

Add support for that to nm_utils_buf_utf8safe_unescape().

Note that this is not the same as calling g_strstrip() before/after
unescape. That is, because nm_utils_buf_utf8safe_unescape() correctly
preserves escaped whitespace. If you call g_strstrip() before/after
the unescape, you don't know whether the whitespace is escaped.
2020-05-13 10:28:04 +02:00
Thomas Haller 5fe447d4a6
shared: assert that nm_utils_buf_utf8safe_unescape() doesn't reallocate memory
We want to use the function to unescape (compress) secrets. As such, we want
to be sure that no secrets are leaked in memory due to growing the buffer with
realloc. In fact, reallocation should never happen. Assert for that.

As reallocation cannot happen, we could directly fill a buffer with
API like nm_utils_strbuf_*(). But NMStrBuf has low overhead even in this
case.
2020-05-13 10:28:04 +02:00
Thomas Haller dbf14dc38c
shared: add nm_str_is_empty() helper
We have nm_str_not_empty() which is the inverse of that. The purpose
of nm_str_not_empty() is to normalize a string to either return
%NULL or a non-empty string, like

   const char *
   get_name (Object *obj)
   {
        return nm_str_not_empty (obj->name);
   }

Sometimes, we however want to check whether a string is not empty.
So, we previously had two choices:

1) use a temporary variable:

     const char *tmp;

     tmp = get_string ();
     if (tmp && tmp[0])
        ...

The problem with this variant is that it's more verbose (by requiring a
temporary variable). Another downside is that there are multiple ways
how to check for an empty string (!tmp[0], tmp[0] == '\0', !strlen (tmp),
strlen (tmp) == 0), and sure enough they are all in use.

2) use !nm_str_not_empty(). But this double negation looks really odd
and confusing.

Add nm_str_is_empty() instead.
2020-05-08 11:10:51 +02:00
Thomas Haller 0b2ecf5e35
shared: add NM_G_PARAM_SPEC_GET_DEFAULT_*() helper macros 2020-05-08 08:02:48 +02:00
Thomas Haller a0b2955907
shared: add NM_ENSURE_NOT_NULL() macro 2020-05-08 08:00:41 +02:00
Thomas Haller e31b31e5e5
shared: add nm_g_error_matches() helper 2020-05-07 14:08:31 +02:00
Thomas Haller a617177070
shared: add NM_STR_HAS_PREFIX_WITH_MORE() helper 2020-05-07 14:08:31 +02:00
Thomas Haller 5a09292f1f
shared: fix accessing "str" argument to NM_STR_HAS_PREFIX() macro twice
Macros preferably behave function-like, for example in that they evaluate
arguments exactly ones. Sometimes, we want to evaluate arguments
lazily, like in NM_IN_SET() or nm_g_set_error_take_lazy(). But it
is almost always undesirable to evaluate an argument more than once.

Fix NM_STR_HAS_PREFIX() for that.

Also, rename the local variable to not use the name "_str",
which may be a common name that the caller would like to use.
2020-05-07 14:08:31 +02:00
Thomas Haller 5056e0d3c8
shared: add nm_strvarray_*() helper API
GPtrArray does not support NULL terminating the pointer array. That
makes it cumbersome to use it for tracking a strv array. Add a few
helper functions nm_strvarray_*() that help using a GArray instead.
2020-05-06 15:19:27 +02:00
Thomas Haller 8dd74fe364
shared: add nm_indirect_g_free() helper 2020-05-06 15:19:25 +02:00
Thomas Haller 070535c6f6
shared: add nm_g_array_len() helper 2020-05-06 15:19:24 +02:00
Thomas Haller 46bee5298b
shared: add nm_g_ptr_array_len() helper 2020-05-06 15:19:23 +02:00
Thomas Haller ee7fbc954e shared/glib: prevent users to use g_cancellable_reset()
When handling a GCancellable, you make decisions based on when the cancelled
property of a GCancellable changes. Correctly handling a cancellable becoming
uncancelled again is really complicated, nor is it clear what it even means:
should the flipping be treated as cancellation or not? Probably if the
cancelled property gets reset, you already start aborting and there is
no way back. So, you would want that a cancellation is always handled.
But it's hard to implement that correctly, and it's odd to claim
something was cancelled, if g_cancellable_is_cancelled() doesn't agree
(anymore).

Avoid such problems by preventing users to call g_cancellable_reset().
2020-04-28 18:35:59 +02:00
Thomas Haller 32664c72a5 shared: add nm_gbytes_get_empty() singleton getter 2020-04-28 18:35:59 +02:00
Thomas Haller 2a26562ec8 shared: add nm_gbytes_hash() and nm_gbytes_equal() 2020-04-28 18:35:59 +02:00
Thomas Haller cd5157a0c3 shared: add nm_utils_invoke_on_timeout()
Add nm_utils_invoke_on_timeout() beside nm_utils_invoke_on_idle().
They are fundamentally similar, except one schedules an idle handler
and the other a timeout.

Also, use the current g_main_context_get_thread_default() as context
instead of the singleton instance. That is a change in behavior, but
the only caller of nm_utils_invoke_on_idle() is the daemon, which
doesn't use different main contexts. Anyway, to avoid anybody being
tripped up by this also change the order of arguments. It anyway
seems nicer to first pass the cancellable, and the callback and user
data as last arguments. It's more in line with glib's asynchronous
methods.

Also, in the unlikely case that the cancellable is already cancelled
from the start, always schedule an idle action to complete fast.
2020-04-24 13:58:46 +02:00
Thomas Haller 95ccfdb69a shared: add NM_CMP_DIRECT_PTR() macro 2020-04-22 09:49:45 +02:00
Thomas Haller f3ca61e6e4 shared/trivial: fix typo in code comment and reword 2020-04-10 10:55:22 +02:00
Thomas Haller 3e1e63e57d cli/polkit: make parsing polkit-agent-helper-1 protocol more conforming
- in io_watch_have_data(), ensure that we handle incomplete lines
that don't yet have a newline by waiting for more data. That means,
if the current content of the in_buffer does not have a newline, we
wait longer.

- in io_watch_have_data(), implement (and ignore) certain commands
instead of failing the request.

- in io_watch_have_data(), no longer g_compress() the entire line.
"polkitagenthelper-pam.c" never backslash escapes the command, it
only escapes the arguments. Of course, there should be no difference
in practice, except that we don't want to handle escape sequences
in the commands.

- in io_watch_have_data(), compare SUCCESS/FAILURE literally.
"polkitagenthelper-pam.c" never appends any trailing garbage to these
commands, and we shouldn't handle that (although "polkitagentsession.c"
does).

- when io_watch_have_data() completes with success, we cannot destroy
AuthRequest right away. It probably still has data pending that we first
need to write to the polkit helper. Wait longer, and let io_watch_can_write()
complete the request.

- ensure we always answer the GDBusMethodInvocation. Otherwise, it gets
leaked.

- use NMStrBuf instead of GString.
2020-04-10 10:44:57 +02:00
Thomas Haller 2384033b05 shared: fix returning EAGAIN from nm_utils_fd_read()
We cannot just swallow EAGAIN and pretend that not bytes were read.

read() returning zero means end of file. The caller needs to distinguish
between end of file and EAGAIN.
2020-04-10 10:44:50 +02:00
Thomas Haller 8c637e693a shared/strbuf: fix signedness of integer comparison in nm_str_buf_append_printf() 2020-04-10 10:44:48 +02:00
Thomas Haller 741258a928 shared/strbuf: rename private, mutable fields in NMStrBuf structure
NMStrBuf is not an opaque structure, so that we can allocate it on the
stack or embed it in a struct.

But most of the fields should not be touched outside of the
implementation.

Also, "len" and "allocated" fields may be accessed directly, but
they should not be modified.

Rename the fields to make that clearer.
2020-04-10 10:44:47 +02:00
Thomas Haller 560b840a11 shared/strbuf: add nm_str_buf_is_initalized() helper 2020-04-10 10:44:46 +02:00
Thomas Haller 19fff8444e shared/strbuf: add nm_str_buf_erase() helper 2020-04-10 10:44:45 +02:00
Thomas Haller f8efed528d shared/strbuf: add nm_str_buf_get_str_unsafe() helper function to give direct access to string buffer 2020-04-10 10:44:44 +02:00
Thomas Haller 7dc467bbbc shared/strbuf: add nm_str_buf_set_size() helper function 2020-04-10 10:44:43 +02:00
Thomas Haller a2d52669aa shared/strbuf: add nm_str_buf_ensure_trailing_c() helper function 2020-04-10 10:44:42 +02:00
Thomas Haller 64894182ca shared/strbuf: expose read only value for "allocated" buffer size
We cannot actually mark the field as const, because then you could no
longer initialize a variable that contains a NMStrBuf with designated
initializers.

We also want to keep the "_allocated" alias, for the only places that
are allowed to mutate the field: inside "nm-str-buf.h". Add an alias
for that field, that is allowed to be read, provided that you don't
modify it!

The alternative would be a nm_str_buf_get_allocated() accessor, but
that seems unnecessarily verbose when you could just access the field.
2020-04-10 10:44:41 +02:00
Thomas Haller 7ff170a28f shared/strbuf: don't have const values in NMStrBuf
Before, if a struct had a field of type NMStrBuf (which is sensible to do),
then you could not longer initialize the entire struct with

  *ptr = (Type) { };

because NMStrBuf contained const fields.

The user should never set these fields directly and use nm_str_buf_*() to modify
them them. But no longer mark them as const, because that breaks valid
use cases.
2020-04-10 10:44:40 +02:00
Thomas Haller 43ba2cb933 shared/strbuf: allow forward declaring "struct _NMStrBuf" 2020-04-10 10:44:39 +02:00
Thomas Haller abacc1e919 shared/strbuf: only clear the bytes that we actually wrote to
The allocated buffes are not known to be written. It is unnecessary to
clear them.

If the user writes sensitive data to those locations, without using
the NMStrBuf API, then it is up to the user to bzero the memory
accordingly.
2020-04-10 10:44:38 +02:00
Thomas Haller d1c2572e11 shared: add NM_UTILS_GET_NEXT_REALLOC_SIZE_1000 define
When we have a buffer that we want to grow exponentially with
nm_utils_get_next_realloc_size(), then there are certain buffer
sizes that are better suited.

For example, if you have an empty NMStrBuf (len == 0), and you
want to allocate roughly one kilobyte, then 1024 is a bad choice,
because nm_utils_get_next_realloc_size() will give you 2024 bytes.

NM_UTILS_GET_NEXT_REALLOC_SIZE_1000 might be better in this case.
2020-04-10 10:44:37 +02:00
Thomas Haller ef0c289104 shared/tests: avoid undefined behavior in test_nm_utils_get_next_realloc_size() test 2020-04-10 10:27:27 +02:00
Thomas Haller 2c2ed2374f shared: fix static assert in NM_MORE_ASSERT_ONCE()
NM_MORE_ASSERTS 0 means that more assertions are disabled.
NM_MORE_ASSERT_ONCE() should never be triggered when more
assertions are disabled altogether. It is thus not allowed
to called "if (NM_MORE_ASSERT_ONCE (0))", because that code
would always be enabled.
2020-04-10 08:11:52 +02:00
Thomas Haller be8be0f091 shared: fix crash in _NM_UTILS_STRING_TABLE_LOOKUP_DEFINE()
If you have a LIST with 7 elements, and you lookup a value that
is not in the (sorted) list and would lie before the first element,
the binary search will dig down to imin=0, imid=0, imax=0 and
strcmp will give positive cmp value (indicating that the searched
value is sorted before).

Then, we would do "imax = imid - 1;", which wrapped to G_MAXUINT,
and the following "if (G_UNLIKELY (imin > imax))" would not hit,
resulting in an out of bound access next.

The easy fix is to not used unsigned integers.

The binary search was adapted from nm_utils_array_find_binary_search()
and nm_utils_ptrarray_find_binary_search(), which already used signed
integers to avoid this problem.

Fixes: 17d9b852c8 ('shared: explicitly implement binary search in NM_UTILS_STRING_TABLE_LOOKUP_DEFINE*()')
2020-04-10 07:57:08 +02:00
Thomas Haller 5cc7abd7a4 shared: add nm_utils_escaped_tokens_options_*() API
This will be used for splitting and escaping option parameters in
nmcli (vpn.data).
2020-04-04 19:51:34 +02:00
Thomas Haller d1a9c2bd42 shared: add flags for nm_utils_escaped_tokens_escape_full()
Add flags to explicitly escape leading or trailing spaces. Note
that we were already escaping trailing spaces.

This will be used later when supporting backslash escapes for
option parameters for nmcli (vpn.data).
2020-04-04 19:51:34 +02:00
Thomas Haller ab9dc9f6d4 shared: refactor initializing character lookup tables for strsplit 2020-04-04 19:51:34 +02:00
Thomas Haller 484d44fc87 shared/trivial: improve code comments about NMUtilsStrsplitSetFlags flags 2020-04-04 19:51:34 +02:00
Thomas Haller 76784e0c97 shared: add nm_str_is_stripped() util 2020-04-04 19:51:34 +02:00
Thomas Haller 63545d31ca shared: add nm_g_hash_table_*() utils for accepting %NULL hash argument 2020-04-04 19:51:34 +02:00
Thomas Haller 55a058aeef libnmm,shared: extract and move nm_utils_strdict_to_variant_ass() to shared
This is a helper function that converts a string dictionary to an "a{ss}"
GVariant. It is generally useful, and should be independent from the
caller.
2020-04-04 19:51:34 +02:00
Thomas Haller 09dcb18381 shared: use NMStrBuf in _nm_utils_enum_to_str_full()
Just for showcase and to hit the code from the unit-tests
that we have.

Also, just to show, the following runs about 25 % faster than before,
which isn't bad for such a simple replacement.

    {
         GType gtype = nm_test_general_color_flags_get_type ();
         const int N_RUN = 1000000;
         int i_run;
         guint8 c = 0;

         for (i_run = 0; i_run < N_RUN; i_run++) {
              gs_free char *str = NULL;

              str = _nm_utils_enum_to_str_full (gtype, i_run % 10, ",", NULL);
              c += str[0];
         }
         return c % 3;
    }

$ perf stat -r 200 -B libnm-core/tests/test-general

Before:

 Performance counter stats for 'libnm-core/tests/test-general' (200 runs):

            204.48 msec task-clock:u              #    0.997 CPUs utilized            ( +-  0.53% )
                 0      context-switches:u        #    0.000 K/sec
                 0      cpu-migrations:u          #    0.000 K/sec
               267      page-faults:u             #    0.001 M/sec                    ( +-  0.05% )
       702,987,494      cycles:u                  #    3.438 GHz                      ( +-  0.54% )
     1,698,874,415      instructions:u            #    2.42  insn per cycle           ( +-  0.00% )
       410,394,229      branches:u                # 2006.970 M/sec                    ( +-  0.00% )
         1,770,484      branch-misses:u           #    0.43% of all branches          ( +-  0.40% )

           0.20502 +- 0.00108 seconds time elapsed  ( +-  0.53% )

After:

 Performance counter stats for 'libnm-core/tests/test-general' (200 runs):

            155.71 msec task-clock:u              #    0.996 CPUs utilized            ( +-  0.50% )
                 0      context-switches:u        #    0.000 K/sec
                 0      cpu-migrations:u          #    0.000 K/sec
               266      page-faults:u             #    0.002 M/sec                    ( +-  0.05% )
       539,994,118      cycles:u                  #    3.468 GHz                      ( +-  0.49% )
     1,116,016,733      instructions:u            #    2.07  insn per cycle           ( +-  0.00% )
       283,974,158      branches:u                # 1823.760 M/sec                    ( +-  0.00% )
         1,377,786      branch-misses:u           #    0.49% of all branches          ( +-  0.43% )

          0.156255 +- 0.000786 seconds time elapsed  ( +-  0.50% )
2020-04-03 11:31:12 +02:00
Thomas Haller d5d7b4781e shared: pre-allocate GString with 16 bytes for _nm_utils_enum_to_str_full()
In the next commit, GString will be replaced by NMStrBuf. Then, we will
pre-allocate a string buffer with 16 bytes, and measure the performance
difference. To have it comparable, adjust the pre-allocation size also
with GString.
2020-04-03 11:31:12 +02:00
Thomas Haller 686b58571b shared: use NMStrBuf for implementing nm_utils_str_utf8safe_unescape() 2020-04-03 11:31:12 +02:00
Thomas Haller beec47e70a shared: use nm_utils_buf_utf8safe_unescape() for nm_utils_str_utf8safe_unescape()
nm_utils_buf_utf8safe_unescape() is almost the same as g_strcompress(),
with the only difference is that if the string contains NUL escapes "\000",
it will be handled correctly.

In other words, g_strcompress() and nm_utils_str_utf8safe_unescape() can only
unescape values, that contain no NUL escapes. That's why we added our
own binary unescape function.

As we already have our g_strcompress() variant, use it. It just gives it more
testing and usage. Also, we have full control over it's behavior. For example,
g_strcompress() issues a g_warning() when encountering a trailing '\\'. I
think this makes it unsuitable to unescape untrusted data. Either the function
should fail, or just make the best of it. Currently, our implementation
does the latter.
2020-04-03 11:31:12 +02:00
Thomas Haller 27e788cce8 shared: add NM_UTILS_STR_UTF8_SAFE_FLAG_SECRET flag
The new flag tells that as we re-allocate data buffers during
escaping, we bzero the memory to avoid leaking secrets.
2020-04-03 11:31:12 +02:00
Thomas Haller eda47170ed shared: add NMStrBuf util
Our own implementation of a string buffer like GString.

Advantages (in decreasing relevance):

- Since we are in control, we can easily let it nm_explicit_bzero()
  the memory. The regular GString API cannot be used in such a case.
  While nm_explicit_bzero() may or may not be of questionable benefit,
  the problem is that if the underlying API counteracts the aim of
  clearing memory, it gets impossible. As API like NMStrBuf supports
  it, clearing memory is a easy as enable the right flag.
  This would for example be useful for example when we read passwords
  from a file or file descriptor (e.g. try_spawn_vpn_auth_helper()).

- We have API like

    nmp_object_to_string (const NMPObject *obj,
                          NMPObjectToStringMode to_string_mode,
                          char *buf,
                          gsize buf_size);

  which accept a fixed size output buffer. This has the problem of
  how choosing the right sized buffer. With NMStrBuf such API could
  be instead

    nmp_object_to_string (const NMPObject *obj,
                          NMPObjectToStringMode to_string_mode,
                          NMStrBuf *buf);

  which can automatically grow (using heap allocation). It would be
  easy to extend NMStrBuf to use a fixed buffer or limiting the
  maximum string length. The point is, that the to-string API wouldn't
  have to change. Depending on the NMStrBuf passed in, you can fill
  an unbounded heap allocated string, a heap allocated string up to
  a fixed length, or a static string of fixed length. NMStrBuf currently
  only implements the unbounded heap allocate string case, but it would
  be simple to extend.

  Note that we already have API like nm_utils_strbuf_*() to fill a buffer
  of fixed size. GString is not useable for that (efficiently), hence
  this API exists. NMStrBuf could be easily extended to replace this API
  without usability or performance penalty. So, while this adds one new
  API, it could replace other APIs.

- GString always requires a heap allocation for the container. In by far
  most of the cases where we use GString, we use it to simply construct
  a string dynamically. There is zero use for this overhead. If one
  really needs a heap allocated buffer, NMStrBuf can easily embedded
  in a malloc'ed memory and boxed that way.

- GString API supports inserting and removing range. We almost never
  make use of that. We only require append-only, which is simple to
  implement.

- GString needs to NUL terminate the buffer on every append. It
  has unnecessary overhead for allowing a usage of where intermediate
  buffer contents are valid strings too. That is not the case with
  NMStrBuf: the API requires the user to call nm_str_buf_get_str() or
  nm_str_buf_finalize(). In most cases, you would only access the string
  once at the end, and not while constructing it.

- GString always grows the buffer size by doubling it. I don't think
  that is optimal. I don't think there is one optimal approach for how
  to grow the buffer, it depends on the usage patterns. However, trying
  to make an optimal choice here makes a difference. QT also thinks so,
  and I adopted their approach in nm_utils_get_next_realloc_size().
2020-04-03 11:31:12 +02:00
Thomas Haller 04d0d1bbe5 shared: add nm_utils_get_next_realloc_size() helper
When growing a buffer by appending a previously unknown number
of elements, the often preferable strategy is growing it exponentially,
so that the amortized runtime and re-allocation costs scale linearly.
GString just always increases the buffer length to the next power of
two. That works.

I think there is value in trying to find an optimal next size. Because
while it doesn't matter in terms of asymptotic behavior, in practice
a better choice should make a difference. This is inspired by what QT
does ([1]), to take more care when growing the buffers:

  - QString allocates 4 characters at a time until it reaches size 20.
  - From 20 to 4084, it advances by doubling the size each time. More
    precisely, it advances to the next power of two, minus 12. (Some memory
    allocators perform worst when requested exact powers of two, because
    they use a few bytes per block for book-keeping.)
  - From 4084 on, it advances by blocks of 2048 characters (4096 bytes).
    This makes sense because modern operating systems don't copy the entire
    data when reallocating a buffer; the physical memory pages are simply
    reordered, and only the data on the first and last pages actually needs
    to be copied.

Note that a QT is talking about 12 characters, so we use 24 bytes
head room.

[1] https://doc.qt.io/qt-5/containers.html#growth-strategies
2020-04-03 11:31:12 +02:00
Thomas Haller d51be7e963 shared: use nm_secret_mem_try_realloc_take() in nm_utils_fd_get_contents() 2020-04-03 11:31:12 +02:00
Thomas Haller e9a2a85799 shared: add nm_secret_mem_realloc() helpers 2020-04-03 11:31:12 +02:00
Thomas Haller 5ab04919a2 shared: use G_UNLIKELY() macro for unlikely branch in nm_explicit_bzero() 2020-04-03 11:31:12 +02:00
Thomas Haller b6fdc30a88 shared: cleanup _get_hash_key_init() and better explain the reasoning
- add more code comments

- refactor the code flow in _get_hash_key_init() to follow a simpler
  code path.

- use c_siphash_hash() instead of 3 separate steps.

- Drop "?: static_seed" from nm_hash_static(). It's not useful, because
  the only _get_hash_key() for which _get_hash_key()^static_seed is zero
  is ~static_seed. That means, only one value of all the static seeds
  can result in zero here. At that point, we can just coerce that value
  to 3679500967u directly.
2020-04-03 11:26:49 +02:00
Thomas Haller 573b02f7d7 shared: add nm_pgbytes_hash()/nm_pgbytes_equal()
For hashing of a pointer to a GBytes*.

This is useful if your key is a GBytes array, and the
first field in your to be hashed struct.
2020-04-03 11:26:49 +02:00
Thomas Haller b1503d8a72 shared: add nm_hash_mem() helper 2020-04-03 11:26:49 +02:00
Thomas Haller 962ad7f850 shared: accept empty buffer for nm_hash_update()
There is no need to reject empty buffers. c_siphash_append() handles
them gracefully.
2020-04-03 11:26:49 +02:00
Thomas Haller 7e49f4a199 all: use wrappers for g_ascii_strtoll(), g_ascii_strtoull(), g_ascii_strtod()
Sometimes these function may set errno to unexpected values like EAGAIN.
This causes confusion. Avoid that by using our own wrappers that retry
in that case. For example, in rhbz#1797915 we have failures like:

    errno = 0;
    v = g_ascii_strtoll ("10", 0, &end);
    if (errno != 0)
        g_assert_not_reached ();

as g_ascii_strtoll() would return 10, but also set errno to EAGAIN.

Work around that by using wrapper functions that retry. This certainly
should be fixed in glib (or glibc), but the issues are severe enough to
warrant a workaround.

Note that our workarounds are very defensive. We only retry 2 times, if
we get an unexpected errno value. This is in the hope to recover from
a spurious EAGAIN. It won't recover from other errors.

https://bugzilla.redhat.com/show_bug.cgi?id=1797915
2020-04-01 17:18:37 +02:00
Thomas Haller 3b58c5fef4 shared: add nm_g_ascii_strtoull() to workaround bug 2020-04-01 17:18:01 +02:00
Thomas Haller 35a9f632a8 shared: add nm_g_ascii_strtod() to workaround bug 2020-04-01 17:18:01 +02:00
Thomas Haller f4446e34c6 shared: add nm_g_ascii_strtoll() to workaround bug 2020-04-01 17:18:00 +02:00
Thomas Haller 87b0d4cd7c shared: add assertions to _parse_legacy_addr4() and _nm_utils_ascii_str_to_int64()
Add more assertion for hunting down assertion failure at [1].

[1] https://bugzilla.redhat.com/show_bug.cgi?id=1797915
2020-03-31 13:48:52 +02:00
Thomas Haller 46dd4d0fbf meson: merge branch 'inigomartinez/meson-license'
Add SPDX license headers for meson files.

As far as I can tell, according to RELICENSE.md file, almost everybody
who contributed to the meson files agreed to the LGPL-2.1+ licensing.
This entails the vast majority of code in question.

https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/397
2020-03-28 12:45:19 +01:00
Thomas Haller 6f9a478b7d tests: replace NMTST_SWAP() by new NM_SWAP() macro
NMTST_SWAP() used memcpy() for copying the value, while NM_SWAP() uses
a temporary variable with typeof(). I think the latter is preferable.

Also, the macro is essentially doing the same thing.
2020-03-26 21:28:56 +01:00
Thomas Haller cec06138f1 shared: add NM_SWAP() macro 2020-03-26 21:28:56 +01:00
Thomas Haller 999c569585 shared: add NM_ASCII_WHITESPACES macro
NM_ASCII_SPACES contains the ASCII characters according to
g_ascii_isspace().

Add NM_ASCII_WHITESPACES which differs from NM_ASCII_SPACES by not
including "\f". In some cases, that character shall be excluded.
For example, this is what systemd uses as "WHITESPACE" define at
various places.

Also, reorder the spaces string so that plain space comes first. It is
expected that ' ' is much more frequently than newlines or tabs. While
the order here shouldn't matter, it seems preferably to order frequent
characters in front.
2020-03-24 20:43:55 +01:00
Thomas Haller 0f15d5aa40 shared: allow nm_dbus_connection_call_finish_variant_cb() with D-Bus methods that have no return value 2020-03-23 09:32:04 +01:00
Thomas Haller d3e5eab734 shared: add nm_g_variant_is_of_type() helper 2020-03-17 08:02:54 +01:00
Thomas Haller 4087024a9b shared: move assertion in _NM_UTILS_STRING_TABLE_LOOKUP_DEFINE()
Move the assertion for valid LIST first. It only checks static data,
and regardless of the entry_cmd, it should be done first.

Fixes: f4d12f7b59 ('shared: add NM_UTILS_STRING_TABLE_LOOKUP_STRUCT_DEFINE() macro for lookup of structs')
2020-03-02 16:20:50 +01:00
Thomas Haller 8b63fd8cc0 shared: fix handling %NULL argument in nm_ref_string_equals_str()
Fixes: 190a8ed425 ('shared: add nm_ref_string_equals_str() helper')
2020-03-02 15:49:41 +01:00
Thomas Haller 294de8487e shared: add NMU_IFACE_OVS_OR_KERNEL for nm_utils_ifname_valid()
Depending on the type, OVS interfaces also have a corresponding netdev
in kernel (e.g. type "internal" does, type "patch" does not).

Such a case is neither NMU_IFACE_OVS nor NMU_IFACE_KERNEL (alone). There should
be a special type to represent those cases.

Add NMU_IFACE_OVS_OR_KERNEL for that.
2020-02-26 17:51:14 +01:00
Thomas Haller 807cddc754 shared: add NMU_IFACE_ANY for nm_utils_ifname_valid()
nm_utils_ifname_valid() is to validate "connection.interface-name"
property. But the exact validation depends on the connection type.

Add "NMU_IFACE_ANY" to validate the name to check whether it would be
valid for any connection type.

This is for completeness and for places where the caller might not know
the connection type.
2020-02-26 17:51:14 +01:00
Thomas Haller d4d9e9e7bb shared: reject reserved names from "connection.interface-name"
"all" and "default" never works.

"bonding_masters" works if you unload the bonding module. Well,
that should not really be called working...

Reject these names.
2020-02-26 17:51:13 +01:00
Thomas Haller ef567805bb shared: reject '%' from nm_utils_ifname_valid() for kernel names
Generally, it's dangerous to reject values that were accepted
previously. This will lead to NetworkManager being unable to load
a profile from disk, which was loadable previously.

On the other hand, kernel would not have treated this setting as
it was intended. So, I would argue that the such a setting was not
working (as intended) anyway.

We can only hope that users don't configure arbitrary interface names.
It generally isn't a good idea to do, so "breaking" such things is less
of a concern.
2020-02-26 17:51:13 +01:00
Thomas Haller 9f2014ac64 shared: fix suffix for NM_GOBJECT_PROPERTIES_DEFINE_BASE*() for multiple definitions
To really use multiple NM_GOBJECT_PROPERTIES_DEFINE_BASE*() defines in
the same source file, several fixes to the suffix handling are
necessary. This fixes commit f13c7e3bbd ('shared: extend
NM_GOBJECT_PROPERTIES_DEFINE*() macros to append suffix to defined
names') to really work.

Fixes: f13c7e3bbd ('shared: extend NM_GOBJECT_PROPERTIES_DEFINE*() macros to append suffix to defined names')
2020-02-24 13:13:34 +01:00
Beniamino Galvani cf6940665d shared: add more debug messages to nm_utils_parse_inaddr_bin_full()
Log the reason for the assertion failure to debug the crash in [1].

[1] https://bugzilla.redhat.com/show_bug.cgi?id=1797915
2020-02-21 16:54:53 +01:00
Thomas Haller f13c7e3bbd shared: extend NM_GOBJECT_PROPERTIES_DEFINE*() macros to append suffix to defined names
This way, we will be able to use the macro multiple times in the same
source file by using different suffixes.
2020-02-21 15:59:44 +01:00
Thomas Haller cba938f3ee shared: add nm_utils_named_values_from_str_dict_full() to allow different sort order (or none) 2020-02-19 16:24:55 +01:00
Thomas Haller f4d12f7b59 shared: add NM_UTILS_STRING_TABLE_LOOKUP_STRUCT_DEFINE() macro for lookup of structs 2020-02-19 15:35:07 +01:00
Thomas Haller 14461e7217 shared: add NM_MORE_ASSERT_ONCE() macro 2020-02-19 15:35:07 +01:00
Thomas Haller eb74d5f65f shared/trivial: add code comment to nm_utils_ifname_valid_kernel() 2020-02-18 13:23:50 +01:00
Thomas Haller 82fb8b00b4 shared: check for valid UTF-8 in nm_utils_ifname_valid()
The interface name might come from the command line or from a filename
(like during nm_vpn_wireguard_import()). It's not clear that this
is valid UTF-8. Asserting against that requires the caller to ensure
that the encoding is valid. That is cumbersome, especially since we anyway
check. Just report a regular error.
2020-02-18 13:23:50 +01:00
Antonio Cardace ed5a647ad1 nm-shared-utils: relax ovs ifname check to accept any (non-space) ASCII printable char
quoting 'man ovs-vswitchd.conf.db':
"The name must be alphanumeric and must not contain forward or backward
slashes."

OVS actually accepts a wider range of chars (all printable UTF-8 chars),
NetworkManager restricts this to ASCII char as it's a safer option for
now since OVS is not well documented on this matter.

https://bugzilla.redhat.com/show_bug.cgi?id=1788432

Fixes: e7d72a14f6 ('libnm-core: use different ifname validation function for OVS bridges, ports and interfaces')
2020-02-18 13:11:21 +01:00
Thomas Haller 037507f790 shared: fix returning out_len from nm_utils_hash_values_to_array()
The only affected caller is nm_modem_manager_get_modems(), which
is used by NMDeviceBt for DUN connections. This is rather bad.

Fixes: 4154d9618c ('bluetooth: refactor BlueZ handling and let NMBluezManager cache ObjectManager data')
Fixes: e688e70b37 ('shared: add nm_utils_hash_values_to_array() helper')
2020-02-17 17:54:10 +01:00
Antonio Cardace 550f538564 nm-shared-utils: add nm_utils_ifname_valid*() to shared utils
Move the body of nm_utils_is_valid_iface_name() to
nm_utils_ifname_valid_kernel() so that it's shared between NM and
clients.
2020-02-17 15:27:35 +01:00
Thomas Haller eae862e385 shared: add LOGD_DHCP_from_addr_family() helper 2020-02-17 14:45:09 +01:00
Iñigo Martínez 648155e4a1 license: Add license using SPDX identifiers to meson build files
License is missing in meson build files. This has been added using
SPDX identifiers and licensed under LGPL-2.1+.
2020-02-17 13:16:57 +01:00
Thomas Haller fee50e17b2 license: relicense "shared/nm-glib-aux/nm-jansson.h" under LGPL-2.1+
$ git shortlog -n -s a3e75f3294 -- shared/nm-glib-aux/nm-jansson.h shared/nm-utils/nm-jansson.h
       7    Thomas Haller
       1    Lubomir Rintel
       1    Beniamino Galvani
       1    Francesco Giudici

All contributors agreed to the relicensing according to "RELICENSE.md".
2020-02-16 15:41:40 +01:00
Thomas Haller e70ce4042c license: relicense "shared/nm-glib-aux/nm-glib.h" under LGPL-2.1+
$ git shortlog -n -s a3e75f3294 -- shared/nm-glib-aux/nm-glib.h shared/nm-utils/nm-glib.h shared/nm-glib.h include/nm-glib.h include/nm-glib-compat.h
      35    Thomas Haller
      12    Dan Winship
       5    Dan Williams
       3    Lubomir Rintel
       2    Beniamino Galvani
       1    Jan Kantert
       1    Thomas Bechtold

The last two contributions by Thomas and Jan are no longer present in any
form, because they were for an older version of glib which is no longer
supported. All other contributors agree to the licences change according
to "RELICENSE.md" file.
2020-02-16 15:41:36 +01:00
Thomas Haller d36df06c24 shared: don't require callback argument to nm_dbus_connection_call_set()
It's fine to call propery-set without caring about the result.
2020-02-14 09:48:37 +01:00
Thomas Haller 829f8e8314 shared: drop compat implementation for G_DEFINE_QUARK()
For one, we by now require glib >= 2.34.0, so this is not used.

Also, I think G_DEFINE_QUARK() is rather ugly because it constructs
the defined function name (so you cannot grep for it). We should use
NM_CACHED_QUARK_FCN() instead.
2020-02-13 17:17:07 +01:00
Thomas Haller cd31437024 shared: drop _STATIC variant of macros that define functions
Several macros are used to define function. They had a "_STATIC" variant,
to define the function as static.

I think those macros should not try to abstract entirely what they do.
They should not accept the function scope as argument (or have two
variants per scope). This also because it might make sense to add
additional __attribute__(()) to the function. That only works, if
the macro does not pretend to *not* define a plain function.

Instead, embrace what the function does and let the users place the
function scope as they see fit.

This also follows what is already done with

    static NM_CACHED_QUARK_FCN ("autoconnect-root", autoconnect_root_quark)
2020-02-13 17:17:07 +01:00
Thomas Haller 17d9b852c8 shared: explicitly implement binary search in NM_UTILS_STRING_TABLE_LOOKUP_DEFINE*()
When looking at nm_utils_array_find_binary_search(), we see that binary
search really isn't complicated. In nm_utils_array_find_binary_search()
it looks complicated, because that is our general purpose function which
accepts arbitrary lists, uses an opaque compare function, accepts a user
data argument, and returns the insertion position.

This is unnecessary for the narrow purpose in NM_UTILS_STRING_TABLE_LOOKUP_DEFINE*().
When we inline the binary search, it can be simplified, and the remaining
parts is simple enough to prefer this duplication of binary search over
using our general purpose function.

Also, this gives the compiler more chance for optimization. For
example, we can use "unsigned" as index type instead of gssize, because
we know (at compile time), that this type will always be large enough
for our LIST. Also, we can directly call strcmp().

The result is that the macro's implementation is also fast in the best
case (where the needle is found with only one strcmp()) and in the cases
where there is a small number of items to search.
It thus alleviates concerns that using the macro might be slower than
an optimized implementation.

The binary size of the defined function increases slightly (from 112
bytes to 192 bytes, on x86_64, GCC, -O2). But according to my tests it
is slightly and measurably faster.
2020-02-13 14:49:45 +01:00
Thomas Haller 760551e3fc shared/tests: add test for NM_UTILS_STRING_TABLE_LOOKUP_DEFINE*() 2020-02-13 14:20:26 +01:00
Thomas Haller 487141d4a8 shared: add entry_cmd argument to NM_UTILS_STRING_TABLE_LOOKUP_DEFINE*() macro
This extra argument allows to tweak whether to assert for the input argument name.
2020-02-13 10:46:34 +01:00
Thomas Haller 190a8ed425 shared: add nm_ref_string_equals_str() helper 2020-02-10 19:11:50 +01:00
Thomas Haller 333e6f66fb shared: rename local variable in _NM_GET_PRIVATE_PTR() macro
The _NM_GET_PRIVATE_PTR() macro is possibly used from other macros. And
"_self" is a pretty good name to use. Don't let the lower layer macro
use this name.
2020-02-10 19:11:50 +01:00
Thomas Haller 8c23586a77 shared: drop nm_utils_dbus_normalize_object_path() in favor of nm_dbus_path_not_empty()
They do the same thing. Unify and drop one.
2020-02-10 19:11:50 +01:00
Thomas Haller c7e6573eb4 shared: add nm_g_variant_lookup() and nm_g_variant_lookup_value() helpers
It's often convenient to accept %NULL as dictionary argument.
2020-02-10 19:11:50 +01:00
Thomas Haller 455cec9986 shared: add nm_utils_strdup_reset() helper 2020-02-10 19:11:50 +01:00