shared: move NM_UTILS_ERROR to shared-utils
[NetworkManager.git] / src / nm-core-utils.h
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* NetworkManager -- Network link manager
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *
18  * Copyright 2004 - 2016 Red Hat, Inc.
19  * Copyright 2005 - 2008 Novell, Inc.
20  */
21
22 #ifndef __NM_CORE_UTILS_H__
23 #define __NM_CORE_UTILS_H__
24
25 #include <stdio.h>
26 #include <arpa/inet.h>
27
28 #include "nm-default.h"
29 #include "nm-connection.h"
30
31 /*****************************************************************************/
32
33 #define NM_PLATFORM_LIFETIME_PERMANENT G_MAXUINT32
34
35 #define NM_DEFINE_SINGLETON_INSTANCE(TYPE) \
36 static TYPE *singleton_instance
37
38 #define NM_DEFINE_SINGLETON_REGISTER(TYPE) \
39 NM_DEFINE_SINGLETON_INSTANCE (TYPE); \
40 static void \
41 _singleton_instance_weak_ref_cb (gpointer data, \
42                                  GObject *where_the_object_was) \
43 { \
44         nm_log_dbg (LOGD_CORE, "disposing %s singleton (%p)", G_STRINGIFY (TYPE), singleton_instance); \
45         singleton_instance = NULL; \
46 } \
47 static inline void \
48 nm_singleton_instance_register (void) \
49 { \
50         g_object_weak_ref (G_OBJECT (singleton_instance), _singleton_instance_weak_ref_cb, NULL); \
51         _nm_singleton_instance_register_destruction (G_OBJECT (singleton_instance)); \
52 }
53
54 void _nm_singleton_instance_register_destruction (GObject *instance);
55
56 /* By default, the getter will assert that the singleton will be created only once. You can
57  * change this by redefining NM_DEFINE_SINGLETON_ALLOW_MULTIPLE. */
58 #ifndef NM_DEFINE_SINGLETON_ALLOW_MULTIPLE
59 #define NM_DEFINE_SINGLETON_ALLOW_MULTIPLE     FALSE
60 #endif
61
62 #define NM_DEFINE_SINGLETON_GETTER(TYPE, GETTER, GTYPE, ...) \
63 NM_DEFINE_SINGLETON_INSTANCE (TYPE); \
64 NM_DEFINE_SINGLETON_REGISTER (TYPE); \
65 TYPE * \
66 GETTER (void) \
67 { \
68         if (G_UNLIKELY (!singleton_instance)) { \
69                 static char _already_created = FALSE; \
70 \
71                 g_assert (!_already_created || (NM_DEFINE_SINGLETON_ALLOW_MULTIPLE)); \
72                 _already_created = TRUE;\
73                 singleton_instance = (g_object_new (GTYPE, ##__VA_ARGS__, NULL)); \
74                 g_assert (singleton_instance); \
75                 nm_singleton_instance_register (); \
76                 nm_log_dbg (LOGD_CORE, "create %s singleton (%p)", G_STRINGIFY (TYPE), singleton_instance); \
77         } \
78         return singleton_instance; \
79 }
80
81 /* attach @instance to the data or @owner. @owner owns a reference
82  * to @instance thus the lifetime of @instance is at least as long
83  * as that of @owner. Use this when @owner depends on @instance. */
84 #define NM_UTILS_KEEP_ALIVE(owner, instance, unique_token) \
85     G_STMT_START { \
86          g_object_set_data_full (G_OBJECT (owner), \
87                                  ".nm-utils-keep-alive-" unique_token "", \
88                                  g_object_ref (instance), \
89                                  g_object_unref); \
90     } G_STMT_END
91
92 /*****************************************************************************/
93
94 gint nm_utils_ascii_str_to_bool (const char *str,
95                                  gint default_value);
96
97 /*****************************************************************************/
98
99 gboolean nm_ethernet_address_is_valid (gconstpointer addr, gssize len);
100
101 in_addr_t nm_utils_ip4_address_clear_host_address (in_addr_t addr, guint8 plen);
102 const struct in6_addr *nm_utils_ip6_address_clear_host_address (struct in6_addr *dst, const struct in6_addr *src, guint8 plen);
103
104 /**
105  * nm_utils_ip6_route_metric_normalize:
106  * @metric: the route metric
107  *
108  * For IPv6 route, kernel treats the value 0 as IP6_RT_PRIO_USER (1024).
109  * Thus, when comparing metric (values), we want to treat zero as NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6.
110  *
111  * Returns: @metric, if @metric is not zero, otherwise 1024.
112  */
113 static inline guint32
114 nm_utils_ip6_route_metric_normalize (guint32 metric)
115 {
116         return metric ? metric : 1024 /*NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6*/;
117 }
118
119 int nm_spawn_process (const char *args, GError **error);
120
121 int nm_utils_modprobe (GError **error, gboolean suppress_error_loggin, const char *arg1, ...) G_GNUC_NULL_TERMINATED;
122
123 guint64 nm_utils_get_start_time_for_pid (pid_t pid, char *out_state, pid_t *out_ppid);
124
125 void nm_utils_kill_process_sync (pid_t pid, guint64 start_time, int sig, guint64 log_domain,
126                                  const char *log_name, guint32 wait_before_kill_msec,
127                                  guint32 sleep_duration_msec, guint32 max_wait_msec);
128
129 typedef void (*NMUtilsKillChildAsyncCb) (pid_t pid, gboolean success, int child_status, void *user_data);
130 void nm_utils_kill_child_async (pid_t pid, int sig, guint64 log_domain, const char *log_name,
131                                 guint32 wait_before_kill_msec,
132                                 NMUtilsKillChildAsyncCb callback, void *user_data);
133 gboolean nm_utils_kill_child_sync (pid_t pid, int sig, guint64 log_domain, const char *log_name,
134                                    int *child_status, guint32 wait_before_kill_msec,
135                                    guint32 sleep_duration_msec);
136
137 const char *nm_utils_find_helper (const char *progname,
138                                   const char *try_first,
139                                   GError **error);
140
141 typedef enum {
142         NM_MATCH_SPEC_NO_MATCH  = 0,
143         NM_MATCH_SPEC_MATCH     = 1,
144         NM_MATCH_SPEC_NEG_MATCH = 2,
145 } NMMatchSpecMatchType;
146
147 NMMatchSpecMatchType nm_match_spec_device_type (const GSList *specs, const char *device_type);
148 NMMatchSpecMatchType nm_match_spec_hwaddr (const GSList *specs, const char *hwaddr);
149 NMMatchSpecMatchType nm_match_spec_s390_subchannels (const GSList *specs, const char *subchannels);
150 NMMatchSpecMatchType nm_match_spec_interface_name (const GSList *specs, const char *interface_name);
151 NMMatchSpecMatchType nm_match_spec_match_config (const GSList *specs, guint nm_version, const char *env);
152 GSList *nm_match_spec_split (const char *value);
153 char *nm_match_spec_join (GSList *specs);
154
155 extern char _nm_utils_to_string_buffer[2096];
156
157 void     nm_utils_to_string_buffer_init (char **buf, gsize *len);
158 gboolean nm_utils_to_string_buffer_init_null (gconstpointer obj, char **buf, gsize *len);
159
160 /*****************************************************************************/
161
162 typedef struct {
163         unsigned flag;
164         const char *name;
165 } NMUtilsFlags2StrDesc;
166
167 #define NM_UTILS_FLAGS2STR(f, n) { .flag = f, .name = ""n, }
168
169 #define _NM_UTILS_FLAGS2STR_DEFINE(scope, fcn_name, flags_type, ...) \
170 scope const char * \
171 fcn_name (flags_type flags, char *buf, gsize len) \
172 { \
173         static const NMUtilsFlags2StrDesc descs[] = { \
174                 __VA_ARGS__ \
175         }; \
176         G_STATIC_ASSERT (sizeof (flags_type) <= sizeof (unsigned)); \
177         return nm_utils_flags2str (descs, G_N_ELEMENTS (descs), flags, buf, len); \
178 };
179
180 #define NM_UTILS_FLAGS2STR_DEFINE(fcn_name, flags_type, ...) \
181         _NM_UTILS_FLAGS2STR_DEFINE (, fcn_name, flags_type, __VA_ARGS__)
182 #define NM_UTILS_FLAGS2STR_DEFINE_STATIC(fcn_name, flags_type, ...) \
183         _NM_UTILS_FLAGS2STR_DEFINE (static, fcn_name, flags_type, __VA_ARGS__)
184
185 const char *nm_utils_flags2str (const NMUtilsFlags2StrDesc *descs,
186                                 gsize n_descs,
187                                 unsigned flags,
188                                 char *buf,
189                                 gsize len);
190
191 /*****************************************************************************/
192
193 #define NM_UTILS_ENUM2STR(v, n)     (void) 0; case v: s = ""n""; break; (void) 0
194 #define NM_UTILS_ENUM2STR_IGNORE(v) (void) 0; case v: break; (void) 0
195
196 #define _NM_UTILS_ENUM2STR_DEFINE(scope, fcn_name, lookup_type, int_fmt, ...) \
197 scope const char * \
198 fcn_name (lookup_type val, char *buf, gsize len) \
199 { \
200         nm_utils_to_string_buffer_init (&buf, &len); \
201         if (len) { \
202                 const char *s = NULL; \
203                 switch (val) { \
204                         (void) 0, \
205                         __VA_ARGS__ \
206                         (void) 0; \
207                 }; \
208                 if (s) \
209                         g_strlcpy (buf, s, len); \
210                 else \
211                         g_snprintf (buf, len, "(%"int_fmt")", val); \
212         } \
213         return buf; \
214 }
215
216 #define NM_UTILS_ENUM2STR_DEFINE(fcn_name, lookup_type, ...) \
217         _NM_UTILS_ENUM2STR_DEFINE (, fcn_name, lookup_type, "d", __VA_ARGS__)
218 #define NM_UTILS_ENUM2STR_DEFINE_STATIC(fcn_name, lookup_type, ...) \
219         _NM_UTILS_ENUM2STR_DEFINE (static, fcn_name, lookup_type, "d", __VA_ARGS__)
220
221 /*****************************************************************************/
222
223 #define NM_UTILS_LOOKUP_DEFAULT(v)      return (v)
224 #define NM_UTILS_LOOKUP_DEFAULT_WARN(v) g_return_val_if_reached (v)
225 #define NM_UTILS_LOOKUP_ITEM(v, n)     (void) 0; case v: return (n); (void) 0
226 #define NM_UTILS_LOOKUP_STR_ITEM(v, n) NM_UTILS_LOOKUP_ITEM(v, ""n"")
227 #define NM_UTILS_LOOKUP_ITEM_IGNORE(v) (void) 0; case v: break; (void) 0
228
229 #define _NM_UTILS_LOOKUP_DEFINE(scope, fcn_name, lookup_type, result_type, unknown_val, ...) \
230 scope result_type \
231 fcn_name (lookup_type val) \
232 { \
233         switch (val) { \
234                 (void) 0, \
235                 __VA_ARGS__ \
236                 (void) 0; \
237         }; \
238         { unknown_val; } \
239 }
240
241 #define NM_UTILS_LOOKUP_STR_DEFINE(fcn_name, lookup_type, unknown_val, ...) \
242         _NM_UTILS_LOOKUP_DEFINE (, fcn_name, lookup_type, const char *, unknown_val, __VA_ARGS__)
243 #define NM_UTILS_LOOKUP_STR_DEFINE_STATIC(fcn_name, lookup_type, unknown_val, ...) \
244         _NM_UTILS_LOOKUP_DEFINE (static, fcn_name, lookup_type, const char *, unknown_val, __VA_ARGS__)
245
246 /* Call the string-lookup-table function @fcn_name. If the function returns
247  * %NULL, the numeric index is converted to string using a alloca() buffer.
248  * Beware: this macro uses alloca(). */
249 #define NM_UTILS_LOOKUP_STR(fcn_name, idx) \
250         ({ \
251                 typeof (idx) _idx = (idx); \
252                 const char *_s; \
253                 \
254                 _s = fcn_name (_idx); \
255                 if (!_s) { \
256                         _s = g_alloca (30); \
257                         \
258                         g_snprintf ((char *) _s, 30, "(%lld)", (long long) _idx); \
259                 } \
260                 _s; \
261         })
262
263 /*****************************************************************************/
264
265 static inline void
266 _nm_utils_strbuf_init (char *buf, gsize len, char **p_buf_ptr, gsize *p_buf_len)
267 {
268         NM_SET_OUT (p_buf_len, len);
269         NM_SET_OUT (p_buf_ptr, buf);
270         buf[0] = '\0';
271 }
272
273 #define nm_utils_strbuf_init(buf, p_buf_ptr, p_buf_len) \
274         G_STMT_START { \
275                 G_STATIC_ASSERT (G_N_ELEMENTS (buf) == sizeof (buf) && sizeof (buf) > sizeof (char *)); \
276                 _nm_utils_strbuf_init ((buf), sizeof (buf), (p_buf_ptr), (p_buf_len)); \
277         } G_STMT_END
278 void nm_utils_strbuf_append (char **buf, gsize *len, const char *format, ...) __attribute__((__format__ (__printf__, 3, 4)));
279 void nm_utils_strbuf_append_c (char **buf, gsize *len, char c);
280 void nm_utils_strbuf_append_str (char **buf, gsize *len, const char *str);
281
282 const char *nm_utils_get_ip_config_method (NMConnection *connection,
283                                            GType         ip_setting_type);
284
285 char *nm_utils_new_vlan_name (const char *parent_iface, guint32 vlan_id);
286
287 GPtrArray *nm_utils_read_resolv_conf_nameservers (const char *rc_contents);
288 GPtrArray *nm_utils_read_resolv_conf_dns_options (const char *rc_contents);
289
290 int nm_utils_cmp_connection_by_autoconnect_priority (NMConnection **a, NMConnection **b);
291
292 void nm_utils_log_connection_diff (NMConnection *connection, NMConnection *diff_base, guint32 level, guint64 domain, const char *name, const char *prefix);
293
294 #define NM_UTILS_NS_PER_SECOND  ((gint64) 1000000000)
295 #define NM_UTILS_NS_PER_MSEC    ((gint64) 1000000)
296 #define NM_UTILS_NS_TO_MSEC_CEIL(nsec)      (((nsec) + (NM_UTILS_NS_PER_MSEC - 1)) / NM_UTILS_NS_PER_MSEC)
297
298 gint64 nm_utils_get_monotonic_timestamp_ns (void);
299 gint64 nm_utils_get_monotonic_timestamp_us (void);
300 gint64 nm_utils_get_monotonic_timestamp_ms (void);
301 gint32 nm_utils_get_monotonic_timestamp_s (void);
302 gint64 nm_utils_monotonic_timestamp_as_boottime (gint64 timestamp, gint64 timestamp_ticks_per_ns);
303
304 gboolean    nm_utils_is_valid_path_component (const char *name);
305 const char *NM_ASSERT_VALID_PATH_COMPONENT (const char *name);
306 const char *nm_utils_ip6_property_path (const char *ifname, const char *property);
307 const char *nm_utils_ip4_property_path (const char *ifname, const char *property);
308
309 gboolean nm_utils_is_specific_hostname (const char *name);
310
311 /* IPv6 Interface Identifer helpers */
312
313 /**
314  * NMUtilsIPv6IfaceId:
315  * @id: convenience member for validity checking; never use directly
316  * @id_u8: the 64-bit Interface Identifier
317  *
318  * Holds a 64-bit IPv6 Interface Identifier.  The IID is a sequence of bytes
319  * and should not normally be treated as a %guint64, but this is done for
320  * convenience of validity checking and initialization.
321  */
322 struct _NMUtilsIPv6IfaceId {
323         union {
324                 guint64 id;
325                 guint8  id_u8[8];
326         };
327 };
328
329 #define NM_UTILS_IPV6_IFACE_ID_INIT { { .id = 0 } }
330
331 gboolean nm_utils_get_ipv6_interface_identifier (NMLinkType link_type,
332                                                  const guint8 *hwaddr,
333                                                  guint len,
334                                                  guint dev_id,
335                                                  NMUtilsIPv6IfaceId *out_iid);
336
337 void nm_utils_ipv6_addr_set_interface_identfier (struct in6_addr *addr,
338                                                  const NMUtilsIPv6IfaceId iid);
339
340 gboolean nm_utils_ipv6_addr_set_stable_privacy (struct in6_addr *addr,
341                                                 const char *ifname,
342                                                 const char *uuid,
343                                                 guint dad_counter,
344                                                 GError **error);
345
346 void nm_utils_ipv6_interface_identfier_get_from_addr (NMUtilsIPv6IfaceId *iid,
347                                                       const struct in6_addr *addr);
348
349 void nm_utils_array_remove_at_indexes (GArray *array, const guint *indexes_to_delete, gsize len);
350
351 void nm_utils_setpgid (gpointer unused);
352
353 typedef enum {
354         NM_UTILS_TEST_NONE                              = 0,
355
356         /* Internal flag, marking that either nm_utils_get_testing() or _nm_utils_set_testing() was called. */
357         _NM_UTILS_TEST_INITIALIZED                      = (1LL << 0),
358
359         /* Indicate that test mode is enabled in general. Explicitly calling _nm_utils_set_testing() will always set this flag. */
360         _NM_UTILS_TEST_GENERAL                          = (1LL << 1),
361
362         /* Don't check the owner of keyfiles during testing. */
363         NM_UTILS_TEST_NO_KEYFILE_OWNER_CHECK            = (1LL << 2),
364
365         _NM_UTILS_TEST_LAST,
366         NM_UTILS_TEST_ALL                               = (((_NM_UTILS_TEST_LAST - 1) << 1) - 1) & ~(_NM_UTILS_TEST_INITIALIZED),
367 } NMUtilsTestFlags;
368
369 gboolean nm_utils_get_testing_initialized (void);
370 NMUtilsTestFlags nm_utils_get_testing (void);
371 void _nm_utils_set_testing (NMUtilsTestFlags flags);
372
373 void nm_utils_g_value_set_strv (GValue *value, GPtrArray *strings);
374
375 guint nm_utils_parse_debug_string (const char *string,
376                                    const GDebugKey *keys,
377                                    guint nkeys);
378
379 void nm_utils_ifname_cpy (char *dst, const char *name);
380
381 guint32 nm_utils_lifetime_rebase_relative_time_on_now (guint32 timestamp,
382                                                        guint32 duration,
383                                                        gint32 now);
384
385 gboolean nm_utils_lifetime_get (guint32 timestamp,
386                                 guint32 lifetime,
387                                 guint32 preferred,
388                                 gint32 now,
389                                 guint32 *out_lifetime,
390                                 guint32 *out_preferred);
391
392 gboolean nm_utils_ip4_address_is_link_local (in_addr_t addr);
393
394 #endif /* __NM_CORE_UTILS_H__ */