## Using libnm

### When to use libnm

libnm is fairly simple to use from C. It's based on glib and GObject. If your project uses these already you'll find integration libnm with your project rather convenient. In fact, the nmcli tool shipped with NetworkManager is based on libnm.

libnm should be also the way to go if your project does something non-trivial with NetworkManager, such as manipulating the connection profiles. That is, if you're writing a specialized networking control tool or a desktop environment, libnm is probably the right choice. The popular desktop environments in fact all use libnm directly or with nm-applet and nm-connection-editor that are all based on libnm.

An alternative to use of libnm is the use of the D-Bus API, directly. This gives you larger flexibility and reduces the overhead of linking with the libnm library. This makes sense if your task is simple and you have a good D-Bus library at your disposal. Activating a particular connection profile from a Python script is a good example of a task that is perfectly simple without using libnm.

### How to use libnm

You can use the libnm's C API directly. To do so, all libnm programs need to include `NetworkManager.h` that provides necessary definitions. The rest of the API is documented in the reference manual.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    #include <glib.h>
    #include <NetworkManager.h>

    int
    main (int argc, char *argv[])
    {
    	NMClient *client;

    	client = nm_client_new (NULL, NULL);
    	if (client)
    		g_print ("NetworkManager version: %s\n", nm_client_get_version (client));
    }

Use pkg-config for `libnm` to discover the necessary compiler flags.

    $ cc $(pkg-config --libs --cflags libnm) -o hello-nm hello-nm.c
      $ ./hello-nm
      NetworkManager version: 1.58.0

      $

Utilize the `PKG_CHECK_MODULES` macro to integrate with an autoconf-based build system. It's also recommended to use `NM_VERSION_MIN_REQUIRED` and `NM_VERSION_MAX_ALLOWED` macros to tell libnm headers which API version does your application need to work with. If you use them, the compiler will warn you when you use functionality that is not available in the versions you specified.

    1
    2
    3

    PKG_CHECK_MODULES(LIBNM, libnm >= 1.8)
    LIBNM_CFLAGS="$LIBNM_CFLAGS -DNM_VERSION_MIN_REQUIRED=NM_VERSION_1_8"
    LIBNM_CFLAGS="$LIBNM_CFLAGS -DNM_VERSION_MAX_ALLOWED=NM_VERSION_1_8"

You can use libnm from other languages than C with the use of GObject introspection. This includes Perl, Python, Javascript, Lua, Ruby and more. The example below shows what the typical libnm use in Python would look like.

    1
    2
    3
    4
    5
    6

    import gi
    gi.require_version('NM', '1.0')
    from gi.repository import NM

    client = NM.Client.new(None)
    print ("NetworkManager version " + client.get_version())

There's NM-1.0 Python API Reference maintained a third party that is generated from the introspection metadata.

In general, the C API documentation applies to the use GObject introspection from other languages, with the calling convention respecting the language's customs. Consult the source tree for some examples.

### Synchronous API in libnm

Libnm contains some synchronous API. This API basically makes a blocking D-Bus call (g_dbus_connection_call_sync()) and is now deprecated.

Note that D-Bus is fundamentally asynchronous. Doing blocking calls on top of D-Bus is odd, especially for libnm's NMClient. That is because NMClient essentially is a client-side cache of the objects of the D-Bus interface. This cache should be filled exclusively by (asynchronous) D-Bus events. So, making a blocking D-Bus call means to wait for a response and return it, while queuing everything that happens in between. Basically, there are three options how a synchronous API on NMClient could behave:

1. The call basically calls g_dbus_connection_call_sync(). This means that libnm sends a D-Bus request via GDBusConnection, and blockingly waits for the response. All D-Bus messages that get received in the meantime are queued in the GMainContext that belongs to NMClient. That means, none of these D-Bus events are processed until we iterate the GMainContext after the call returns. The effect is, that NMClient (and all cached objects in there) are unaffected by the D-Bus request. Most of the synchronous API calls in libnm are of this kind. The problem is that the strict ordering of D-Bus events gets violated. For some API this is not an immediate problem. Take for example nm_device_wifi_request_scan(). The call merely blockingly tells NetworkManager to start scanning, but since NetworkManager's D-Bus API does not directly expose any state that tells whether we are currently scanning, this out of order processing of the D-Bus request is a small issue. The problem is more obvious for nm_client_networking_set_enabled(). After calling it, NM_CLIENT_NETWORKING_ENABLED is still unaffected and unchanged, because the PropertiesChanged signal from D-Bus is not yet processed. This means, while you make such a blocking call, NMClient's state does not change. But usually you perform the synchronous call to change some state. In this form, the blocking call is not useful, because NMClient only changes the state after iterating the GMainContext, and not after the blocking call returns.

2. Like 1), but after making the blocking g_dbus_connection_call_sync(), update the NMClient cache artificially. This is what nm_manager_check_connectivity() does, to "fix" bgo#784629. This also has the problem of out-of-order events, but it kinda solves the problem of not changing the state during the blocking call. But it does so by hacking the state of the cache. I think this is really wrong because the state should only be updated from the ordered stream of D-Bus messages. When libnm decides to modify the state, there are already D-Bus messages queued that affect this very state.

3. Instead of calling g_dbus_connection_call_sync(), use the asynchronous g_dbus_connection_call(). If we would use a separate GMainContext for all D-Bus related calls, we could ensure that while we block for the response, we iterate the internal main context. This might be nice, because all events are processed in order and after the blocking call returns, the NMClient state is up to date. The are problems however: current blocking API does not do this, so it's a significant change in behavior. Also, it might be unexpected to the user that during the blocking call the entire content of NMClient's cache might change and all pointers to the cache might be invalidated. Also, of course NMClient would invoke signals for all the changes that happen. Another problem is that this would be more effort to implement and it involves a small performance overhead for all D-Bus related calls (because we have to serialize all events in an internal GMainContext first and then invoke them on the caller's context). Also, if the users wants this, they could implement it themself using their own extra GMainContext and the asynchronous API.

See also this blog for why blocking calls are wrong.

All possible behaviors for synchronous API have severe behavioural issues and thus such API is deprecated. Note that "deprecated" here does not mean that the API is going to be removed. Libnm does not break API. The user may:

- Continue to use this API. It's deprecated, awkward and discouraged, but if it works for you, that's fine.

- Use asynchronous API. That's the only sensible way to use D-Bus. If libnm lacks a certain asynchronous counterpart, it should be added.

- Use GDBusConnection directly. There really isn't anything wrong with D-Bus or GDBusConnection. This deprecated API is just a wrapper around g_dbus_connection_call_sync(). You may call it directly without feeling dirty.