Copy openvpn project as base

This commit is contained in:
Max Moser committed 2017-11-06 13:02:05 +01:00
1 parent 1f8d30e878
commit 337d10e1e0
139 files changed
+84632

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
The files in the "shared/" directory are used by all components
inside the VPN plugin repository (src, properties, auth-dialog).
The files in shared/nm-utils are copied from NetworkManager
repository and used as is:
Do *not* modify these files locally so that they don't diverge
from their original. Fix/extend them in their respective origin
first, and re-import the files as a whole.
+123
View File
@@ -0,0 +1,123 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* (C) Copyright 2015 Red Hat, Inc.
*/
#ifndef __NM_DEFAULT_H__
#define __NM_DEFAULT_H__
/* makefiles define NETWORKMANAGER_COMPILATION for compiling NetworkManager.
* Depending on which parts are compiled, different values are set. */
#define NM_NETWORKMANAGER_COMPILATION_DEFAULT 0x0001
#define NM_NETWORKMANAGER_COMPILATION_LIB_BASE 0x0002
#define NM_NETWORKMANAGER_COMPILATION_LIB_EDITOR 0x0004
#define NM_NETWORKMANAGER_COMPILATION_LIB (0x0002 | 0x0004)
#ifndef NETWORKMANAGER_COMPILATION
/* For convenience, we don't require our Makefile.am to define
* -DNETWORKMANAGER_COMPILATION. As we now include this internal header,
* we know we do a NETWORKMANAGER_COMPILATION. */
#define NETWORKMANAGER_COMPILATION NM_NETWORKMANAGER_COMPILATION_DEFAULT
#endif
/*****************************************************************************/
#include <config.h>
/* always include these headers for our internal source files. */
#include "nm-utils/nm-glib.h"
#include "nm-utils/gsystem-local-alloc.h"
#include "nm-utils/nm-macros-internal.h"
#include "nm-version.h"
#include "nm-service-defines.h"
/*****************************************************************************/
#if ((NETWORKMANAGER_COMPILATION) & NM_NETWORKMANAGER_COMPILATION_LIB)
#include <glib/gi18n-lib.h>
#else
#include <glib/gi18n.h>
#endif /* NM_NETWORKMANAGER_COMPILATION_LIB */
/*****************************************************************************/
#ifdef NM_VPN_OLD
#define NM_VPN_LIBNM_COMPAT
#include <nm-connection.h>
#include <nm-setting-connection.h>
#include <nm-setting-8021x.h>
#include <nm-setting-ip4-config.h>
#include <nm-setting-vpn.h>
#include <nm-utils.h>
#include <nm-vpn-plugin-ui-interface.h>
#define nm_simple_connection_new nm_connection_new
#define NM_SETTING_IP_CONFIG NM_SETTING_IP4_CONFIG
#define NM_SETTING_IP_CONFIG_METHOD NM_SETTING_IP4_CONFIG_METHOD
#define NM_SETTING_IP_CONFIG_NEVER_DEFAULT NM_SETTING_IP4_CONFIG_NEVER_DEFAULT
#define NMSettingIPConfig NMSettingIP4Config
#define NMV_EDITOR_PLUGIN_ERROR NM_SETTING_VPN_ERROR
#define NMV_EDITOR_PLUGIN_ERROR_FAILED NM_SETTING_VPN_ERROR_UNKNOWN
#define NMV_EDITOR_PLUGIN_ERROR_INVALID_PROPERTY NM_SETTING_VPN_ERROR_INVALID_PROPERTY
#define NMV_EDITOR_PLUGIN_ERROR_MISSING_PROPERTY NM_SETTING_VPN_ERROR_MISSING_PROPERTY
#define NMV_EDITOR_PLUGIN_ERROR_FILE_NOT_VPN NM_SETTING_VPN_ERROR_UNKNOWN
#define NMV_EDITOR_PLUGIN_ERROR_FILE_NOT_READABLE NM_SETTING_VPN_ERROR_UNKNOWN
#define NMV_EDITOR_PLUGIN_ERROR_FILE_INVALID NM_SETTING_VPN_ERROR_UNKNOWN
#define _nm_utils_is_valid_iface_name(n) nm_utils_iface_valid_name(n)
#else /* !NM_VPN_OLD */
#include <NetworkManager.h>
#define NMV_EDITOR_PLUGIN_ERROR NM_CONNECTION_ERROR
#define NMV_EDITOR_PLUGIN_ERROR_FAILED NM_CONNECTION_ERROR_FAILED
#define NMV_EDITOR_PLUGIN_ERROR_INVALID_PROPERTY NM_CONNECTION_ERROR_INVALID_PROPERTY
#define NMV_EDITOR_PLUGIN_ERROR_MISSING_PROPERTY NM_CONNECTION_ERROR_MISSING_PROPERTY
#define NMV_EDITOR_PLUGIN_ERROR_FILE_NOT_VPN NM_CONNECTION_ERROR_FAILED
#define NMV_EDITOR_PLUGIN_ERROR_FILE_NOT_READABLE NM_CONNECTION_ERROR_FAILED
#define NMV_EDITOR_PLUGIN_ERROR_FILE_INVALID NM_CONNECTION_ERROR_FAILED
#define _nm_utils_is_valid_iface_name(n) nm_utils_is_valid_iface_name(n, NULL)
#endif /* NM_VPN_OLD */
/*****************************************************************************/
#if (NETWORKMANAGER_COMPILATION) & NM_NETWORKMANAGER_COMPILATION_LIB_EDITOR
#ifdef NM_VPN_OLD
#include <nm-ui-utils.h>
#else /* NM_VPN_OLD */
#include <nma-ui-utils.h>
#endif /* NM_VPN_OLD */
#endif /* NM_NETWORKMANAGER_COMPILATION_LIB_EDITOR */
/*****************************************************************************/
#endif /* __NM_DEFAULT_H__ */
+118
View File
@@ -0,0 +1,118 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* Copyright (C) 2005 - 2008 Tim Niemueller <tim@niemueller.de>
* Copyright (C) 2005 - 2008 Dan Williams <dcbw@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef __NM_SERVICE_DEFINES_H__
#define __NM_SERVICE_DEFINES_H__
#define NM_VPN_SERVICE_TYPE_OPENVPN "org.freedesktop.NetworkManager.openvpn"
#define NM_DBUS_SERVICE_OPENVPN "org.freedesktop.NetworkManager.openvpn"
#define NM_DBUS_INTERFACE_OPENVPN "org.freedesktop.NetworkManager.openvpn"
#define NM_DBUS_PATH_OPENVPN "/org/freedesktop/NetworkManager/openvpn"
#define NM_OPENVPN_KEY_AUTH "auth"
#define NM_OPENVPN_KEY_CA "ca"
#define NM_OPENVPN_KEY_CERT "cert"
#define NM_OPENVPN_KEY_CIPHER "cipher"
#define NM_OPENVPN_KEY_KEYSIZE "keysize"
#define NM_OPENVPN_KEY_COMP_LZO "comp-lzo"
#define NM_OPENVPN_KEY_CONNECTION_TYPE "connection-type"
#define NM_OPENVPN_KEY_FLOAT "float"
#define NM_OPENVPN_KEY_FRAGMENT_SIZE "fragment-size"
#define NM_OPENVPN_KEY_KEY "key"
#define NM_OPENVPN_KEY_LOCAL_IP "local-ip" /* ??? */
#define NM_OPENVPN_KEY_MSSFIX "mssfix"
#define NM_OPENVPN_KEY_MTU_DISC "mtu-disc"
#define NM_OPENVPN_KEY_NS_CERT_TYPE "ns-cert-type"
#define NM_OPENVPN_KEY_PING "ping"
#define NM_OPENVPN_KEY_PING_EXIT "ping-exit"
#define NM_OPENVPN_KEY_PING_RESTART "ping-restart"
#define NM_OPENVPN_KEY_PORT "port"
#define NM_OPENVPN_KEY_PROTO_TCP "proto-tcp"
#define NM_OPENVPN_KEY_PROXY_TYPE "proxy-type"
#define NM_OPENVPN_KEY_PROXY_SERVER "proxy-server"
#define NM_OPENVPN_KEY_PROXY_PORT "proxy-port"
#define NM_OPENVPN_KEY_PROXY_RETRY "proxy-retry"
#define NM_OPENVPN_KEY_HTTP_PROXY_USERNAME "http-proxy-username"
#define NM_OPENVPN_KEY_REMOTE "remote"
#define NM_OPENVPN_KEY_REMOTE_RANDOM "remote-random"
#define NM_OPENVPN_KEY_REMOTE_IP "remote-ip"
#define NM_OPENVPN_KEY_STATIC_KEY "static-key"
#define NM_OPENVPN_KEY_STATIC_KEY_DIRECTION "static-key-direction"
#define NM_OPENVPN_KEY_TA "ta"
#define NM_OPENVPN_KEY_TA_DIR "ta-dir"
#define NM_OPENVPN_KEY_TUNNEL_MTU "tunnel-mtu"
#define NM_OPENVPN_KEY_USERNAME "username"
#define NM_OPENVPN_KEY_TAP_DEV "tap-dev"
#define NM_OPENVPN_KEY_DEV "dev"
#define NM_OPENVPN_KEY_DEV_TYPE "dev-type"
#define NM_OPENVPN_KEY_TUN_IPV6 "tun-ipv6"
#define NM_OPENVPN_KEY_TLS_CIPHER "tls-cipher"
#define NM_OPENVPN_KEY_TLS_CRYPT "tls-crypt"
#define NM_OPENVPN_KEY_TLS_REMOTE "tls-remote"
#define NM_OPENVPN_KEY_VERIFY_X509_NAME "verify-x509-name"
#define NM_OPENVPN_KEY_REMOTE_CERT_TLS "remote-cert-tls"
#define NM_OPENVPN_KEY_MAX_ROUTES "max-routes"
#define NM_OPENVPN_KEY_PASSWORD "password"
#define NM_OPENVPN_KEY_CERTPASS "cert-pass"
#define NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD "http-proxy-password"
/* Internal auth-dialog -> service token indicating that no secrets are
* required for the connection.
*/
#define NM_OPENVPN_KEY_NOSECRET "no-secret"
#define NM_OPENVPN_KEY_RENEG_SECONDS "reneg-seconds"
#define NM_OPENVPN_AUTH_NONE "none"
#define NM_OPENVPN_AUTH_RSA_MD4 "RSA-MD4"
#define NM_OPENVPN_AUTH_MD5 "MD5"
#define NM_OPENVPN_AUTH_SHA1 "SHA1"
#define NM_OPENVPN_AUTH_SHA224 "SHA224"
#define NM_OPENVPN_AUTH_SHA256 "SHA256"
#define NM_OPENVPN_AUTH_SHA384 "SHA384"
#define NM_OPENVPN_AUTH_SHA512 "SHA512"
#define NM_OPENVPN_AUTH_RIPEMD160 "RIPEMD160"
#define NM_OPENVPN_CONTYPE_TLS "tls"
#define NM_OPENVPN_CONTYPE_STATIC_KEY "static-key"
#define NM_OPENVPN_CONTYPE_PASSWORD "password"
#define NM_OPENVPN_CONTYPE_PASSWORD_TLS "password-tls"
/* arguments of "--remote-cert-tls" */
#define NM_OPENVPN_REM_CERT_TLS_CLIENT "client"
#define NM_OPENVPN_REM_CERT_TLS_SERVER "server"
/* arguments of "--ns-cert-type" */
#define NM_OPENVPN_NS_CERT_TYPE_CLIENT "client"
#define NM_OPENVPN_NS_CERT_TYPE_SERVER "server"
/* possible types for verify-x509-name */
#define NM_OPENVPN_VERIFY_X509_NAME_TYPE_SUBJECT "subject"
#define NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME "name"
#define NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME_PREFIX "name-prefix"
/* User name and group to run nm-openvpn-service under */
#define NM_OPENVPN_USER "nm-openvpn"
#define NM_OPENVPN_GROUP "nm-openvpn"
#define NM_OPENVPN_CHROOT LOCALSTATEDIR "/lib/openvpn/chroot"
#endif /* __NM_SERVICE_DEFINES_H__ */
+208
View File
@@ -0,0 +1,208 @@
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2012 Colin Walters <walters@verbum.org>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GSYSTEM_LOCAL_ALLOC_H__
#define __GSYSTEM_LOCAL_ALLOC_H__
#include <gio/gio.h>
G_BEGIN_DECLS
#define GS_DEFINE_CLEANUP_FUNCTION(Type, name, func) \
static inline void name (void *v) \
{ \
func (*(Type*)v); \
}
#define GS_DEFINE_CLEANUP_FUNCTION0(Type, name, func) \
static inline void name (void *v) \
{ \
if (*(Type*)v) \
func (*(Type*)v); \
}
/* These functions shouldn't be invoked directly;
* they are stubs that:
* 1) Take a pointer to the location (typically itself a pointer).
* 2) Provide %NULL-safety where it doesn't exist already (e.g. g_object_unref)
*/
/**
* gs_free:
*
* Call g_free() on a variable location when it goes out of scope.
*/
#define gs_free __attribute__ ((cleanup(gs_local_free)))
GS_DEFINE_CLEANUP_FUNCTION(void*, gs_local_free, g_free)
/**
* gs_unref_object:
*
* Call g_object_unref() on a variable location when it goes out of
* scope. Note that unlike g_object_unref(), the variable may be
* %NULL.
*/
#define gs_unref_object __attribute__ ((cleanup(gs_local_obj_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GObject*, gs_local_obj_unref, g_object_unref)
/**
* gs_unref_variant:
*
* Call g_variant_unref() on a variable location when it goes out of
* scope. Note that unlike g_variant_unref(), the variable may be
* %NULL.
*/
#define gs_unref_variant __attribute__ ((cleanup(gs_local_variant_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GVariant*, gs_local_variant_unref, g_variant_unref)
/**
* gs_free_variant_iter:
*
* Call g_variant_iter_free() on a variable location when it goes out of
* scope.
*/
#define gs_free_variant_iter __attribute__ ((cleanup(gs_local_variant_iter_free)))
GS_DEFINE_CLEANUP_FUNCTION0(GVariantIter*, gs_local_variant_iter_free, g_variant_iter_free)
/**
* gs_free_variant_builder:
*
* Call g_variant_builder_unref() on a variable location when it goes out of
* scope.
*/
#define gs_unref_variant_builder __attribute__ ((cleanup(gs_local_variant_builder_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GVariantBuilder*, gs_local_variant_builder_unref, g_variant_builder_unref)
/**
* gs_unref_array:
*
* Call g_array_unref() on a variable location when it goes out of
* scope. Note that unlike g_array_unref(), the variable may be
* %NULL.
*/
#define gs_unref_array __attribute__ ((cleanup(gs_local_array_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GArray*, gs_local_array_unref, g_array_unref)
/**
* gs_unref_ptrarray:
*
* Call g_ptr_array_unref() on a variable location when it goes out of
* scope. Note that unlike g_ptr_array_unref(), the variable may be
* %NULL.
*/
#define gs_unref_ptrarray __attribute__ ((cleanup(gs_local_ptrarray_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GPtrArray*, gs_local_ptrarray_unref, g_ptr_array_unref)
/**
* gs_unref_hashtable:
*
* Call g_hash_table_unref() on a variable location when it goes out
* of scope. Note that unlike g_hash_table_unref(), the variable may
* be %NULL.
*/
#define gs_unref_hashtable __attribute__ ((cleanup(gs_local_hashtable_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GHashTable*, gs_local_hashtable_unref, g_hash_table_unref)
/**
* gs_free_list:
*
* Call g_list_free() on a variable location when it goes out
* of scope.
*/
#define gs_free_list __attribute__ ((cleanup(gs_local_free_list)))
GS_DEFINE_CLEANUP_FUNCTION(GList*, gs_local_free_list, g_list_free)
/**
* gs_free_slist:
*
* Call g_slist_free() on a variable location when it goes out
* of scope.
*/
#define gs_free_slist __attribute__ ((cleanup(gs_local_free_slist)))
GS_DEFINE_CLEANUP_FUNCTION(GSList*, gs_local_free_slist, g_slist_free)
/**
* gs_free_checksum:
*
* Call g_checksum_free() on a variable location when it goes out
* of scope. Note that unlike g_checksum_free(), the variable may
* be %NULL.
*/
#define gs_free_checksum __attribute__ ((cleanup(gs_local_checksum_free)))
GS_DEFINE_CLEANUP_FUNCTION0(GChecksum*, gs_local_checksum_free, g_checksum_free)
/**
* gs_unref_bytes:
*
* Call g_bytes_unref() on a variable location when it goes out
* of scope. Note that unlike g_bytes_unref(), the variable may
* be %NULL.
*/
#define gs_unref_bytes __attribute__ ((cleanup(gs_local_bytes_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GBytes*, gs_local_bytes_unref, g_bytes_unref)
/**
* gs_strfreev:
*
* Call g_strfreev() on a variable location when it goes out of scope.
*/
#define gs_strfreev __attribute__ ((cleanup(gs_local_strfreev)))
GS_DEFINE_CLEANUP_FUNCTION(char**, gs_local_strfreev, g_strfreev)
/**
* gs_free_error:
*
* Call g_error_free() on a variable location when it goes out of scope.
*/
#define gs_free_error __attribute__ ((cleanup(gs_local_free_error)))
GS_DEFINE_CLEANUP_FUNCTION0(GError*, gs_local_free_error, g_error_free)
/**
* gs_unref_keyfile:
*
* Call g_key_file_unref() on a variable location when it goes out of scope.
*/
#define gs_unref_keyfile __attribute__ ((cleanup(gs_local_keyfile_unref)))
GS_DEFINE_CLEANUP_FUNCTION0(GKeyFile*, gs_local_keyfile_unref, g_key_file_unref)
static inline void
gs_cleanup_close_fdp (int *fdp)
{
int fd;
g_assert (fdp);
fd = *fdp;
if (fd != -1)
(void) close (fd);
}
/**
* gs_fd_close:
*
* Call close() on a variable location when it goes out of scope.
*/
#define gs_fd_close __attribute__((cleanup(gs_cleanup_close_fdp)))
G_END_DECLS
#endif
+484
View File
@@ -0,0 +1,484 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Copyright 2008 - 2011 Red Hat, Inc.
*/
#ifndef __NM_GLIB_H__
#define __NM_GLIB_H__
#include <gio/gio.h>
#include <string.h>
#include "gsystem-local-alloc.h"
#ifdef __clang__
#undef G_GNUC_BEGIN_IGNORE_DEPRECATIONS
#undef G_GNUC_END_IGNORE_DEPRECATIONS
#define G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
#define G_GNUC_END_IGNORE_DEPRECATIONS \
_Pragma("clang diagnostic pop")
#endif
static inline void
__g_type_ensure (GType type)
{
#if !GLIB_CHECK_VERSION(2,34,0)
if (G_UNLIKELY (type == (GType)-1))
g_error ("can't happen");
#else
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
g_type_ensure (type);
G_GNUC_END_IGNORE_DEPRECATIONS;
#endif
}
#define g_type_ensure __g_type_ensure
#if !GLIB_CHECK_VERSION(2,34,0)
#define g_clear_pointer(pp, destroy) \
G_STMT_START { \
G_STATIC_ASSERT (sizeof *(pp) == sizeof (gpointer)); \
/* Only one access, please */ \
gpointer *_pp = (gpointer *) (pp); \
gpointer _p; \
/* This assignment is needed to avoid a gcc warning */ \
GDestroyNotify _destroy = (GDestroyNotify) (destroy); \
\
_p = *_pp; \
if (_p) \
{ \
*_pp = NULL; \
_destroy (_p); \
} \
} G_STMT_END
/* These are used to clean up the output of test programs; we can just let
* them no-op in older glib.
*/
#define g_test_expect_message(log_domain, log_level, pattern)
#define g_test_assert_expected_messages()
#else
/* We build with -DGLIB_MAX_ALLOWED_VERSION set to 2.32 to make sure we don't
* accidentally use new API that we shouldn't. But we don't want warnings for
* the APIs that we emulate above.
*/
#define g_test_expect_message(domain, level, format...) \
G_STMT_START { \
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
g_test_expect_message (domain, level, format); \
G_GNUC_END_IGNORE_DEPRECATIONS \
} G_STMT_END
#define g_test_assert_expected_messages_internal(domain, file, line, func) \
G_STMT_START { \
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
g_test_assert_expected_messages_internal (domain, file, line, func); \
G_GNUC_END_IGNORE_DEPRECATIONS \
} G_STMT_END
#endif
#if GLIB_CHECK_VERSION (2, 35, 0)
/* For glib >= 2.36, g_type_init() is deprecated.
* But since 2.35.1 (7c42ab23b55c43ab96d0ac2124b550bf1f49c1ec) this function
* does nothing. Replace the call with empty statement. */
#define nm_g_type_init() G_STMT_START { (void) 0; } G_STMT_END
#else
#define nm_g_type_init() G_STMT_START { g_type_init (); } G_STMT_END
#endif
/* g_test_initialized() is only available since glib 2.36. */
#if !GLIB_CHECK_VERSION (2, 36, 0)
#define g_test_initialized() (g_test_config_vars->test_initialized)
#endif
/* g_assert_cmpmem() is only available since glib 2.46. */
#if !GLIB_CHECK_VERSION (2, 45, 7)
#define g_assert_cmpmem(m1, l1, m2, l2) G_STMT_START {\
gconstpointer __m1 = m1, __m2 = m2; \
int __l1 = l1, __l2 = l2; \
if (__l1 != __l2) \
g_assertion_message_cmpnum (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
#l1 " (len(" #m1 ")) == " #l2 " (len(" #m2 "))", __l1, "==", __l2, 'i'); \
else if (memcmp (__m1, __m2, __l1) != 0) \
g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
"assertion failed (" #m1 " == " #m2 ")"); \
} G_STMT_END
#endif
/* Rumtime check for glib version. First do a compile time check which
* (if satisfied) shortcuts the runtime check. */
static inline gboolean
nm_glib_check_version (guint major, guint minor, guint micro)
{
return GLIB_CHECK_VERSION (major, minor, micro)
|| ( ( glib_major_version > major)
|| ( glib_major_version == major
&& glib_minor_version > minor)
|| ( glib_major_version == major
&& glib_minor_version == minor
&& glib_micro_version < micro));
}
/* g_test_skip() is only available since glib 2.38. Add a compatibility wrapper. */
static inline void
__nmtst_g_test_skip (const gchar *msg)
{
#if GLIB_CHECK_VERSION (2, 38, 0)
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
g_test_skip (msg);
G_GNUC_END_IGNORE_DEPRECATIONS
#else
g_debug ("%s", msg);
#endif
}
#define g_test_skip __nmtst_g_test_skip
/* g_test_add_data_func_full() is only available since glib 2.34. Add a compatibility wrapper. */
static inline void
__g_test_add_data_func_full (const char *testpath,
gpointer test_data,
GTestDataFunc test_func,
GDestroyNotify data_free_func)
{
#if GLIB_CHECK_VERSION (2, 34, 0)
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
g_test_add_data_func_full (testpath, test_data, test_func, data_free_func);
G_GNUC_END_IGNORE_DEPRECATIONS
#else
g_return_if_fail (testpath != NULL);
g_return_if_fail (testpath[0] == '/');
g_return_if_fail (test_func != NULL);
g_test_add_vtable (testpath, 0, test_data, NULL,
(GTestFixtureFunc) test_func,
(GTestFixtureFunc) data_free_func);
#endif
}
#define g_test_add_data_func_full __g_test_add_data_func_full
#if !GLIB_CHECK_VERSION (2, 34, 0)
#define G_DEFINE_QUARK(QN, q_n) \
GQuark \
q_n##_quark (void) \
{ \
static GQuark q; \
\
if G_UNLIKELY (q == 0) \
q = g_quark_from_static_string (#QN); \
\
return q; \
}
#endif
static inline gboolean
nm_g_hash_table_replace (GHashTable *hash, gpointer key, gpointer value)
{
/* glib 2.40 added a return value indicating whether the key already existed
* (910191597a6c2e5d5d460e9ce9efb4f47d9cc63c). */
#if GLIB_CHECK_VERSION(2, 40, 0)
return g_hash_table_replace (hash, key, value);
#else
gboolean contained = g_hash_table_contains (hash, key);
g_hash_table_replace (hash, key, value);
return !contained;
#endif
}
static inline gboolean
nm_g_hash_table_insert (GHashTable *hash, gpointer key, gpointer value)
{
/* glib 2.40 added a return value indicating whether the key already existed
* (910191597a6c2e5d5d460e9ce9efb4f47d9cc63c). */
#if GLIB_CHECK_VERSION(2, 40, 0)
return g_hash_table_insert (hash, key, value);
#else
gboolean contained = g_hash_table_contains (hash, key);
g_hash_table_insert (hash, key, value);
return !contained;
#endif
}
static inline gboolean
nm_g_hash_table_add (GHashTable *hash, gpointer key)
{
/* glib 2.40 added a return value indicating whether the key already existed
* (910191597a6c2e5d5d460e9ce9efb4f47d9cc63c). */
#if GLIB_CHECK_VERSION(2, 40, 0)
return g_hash_table_add (hash, key);
#else
gboolean contained = g_hash_table_contains (hash, key);
g_hash_table_add (hash, key);
return !contained;
#endif
}
#if !GLIB_CHECK_VERSION(2, 40, 0) || defined (NM_GLIB_COMPAT_H_TEST)
static inline void
_nm_g_ptr_array_insert (GPtrArray *array,
gint index_,
gpointer data)
{
g_return_if_fail (array);
g_return_if_fail (index_ >= -1);
g_return_if_fail (index_ <= (gint) array->len);
g_ptr_array_add (array, data);
if (index_ != -1 && index_ != (gint) (array->len - 1)) {
memmove (&(array->pdata[index_ + 1]),
&(array->pdata[index_]),
(array->len - index_ - 1) * sizeof (gpointer));
array->pdata[index_] = data;
}
}
#endif
#if !GLIB_CHECK_VERSION(2, 40, 0)
#define g_ptr_array_insert(array, index, data) G_STMT_START { _nm_g_ptr_array_insert (array, index, data); } G_STMT_END
#else
#define g_ptr_array_insert(array, index, data) \
G_STMT_START { \
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
g_ptr_array_insert (array, index, data); \
G_GNUC_END_IGNORE_DEPRECATIONS \
} G_STMT_END
#endif
#if !GLIB_CHECK_VERSION (2, 40, 0)
static inline gboolean
_g_key_file_save_to_file (GKeyFile *key_file,
const gchar *filename,
GError **error)
{
gchar *contents;
gboolean success;
gsize length;
g_return_val_if_fail (key_file != NULL, FALSE);
g_return_val_if_fail (filename != NULL, FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
contents = g_key_file_to_data (key_file, &length, NULL);
g_assert (contents != NULL);
success = g_file_set_contents (filename, contents, length, error);
g_free (contents);
return success;
}
#define g_key_file_save_to_file(key_file, filename, error) \
_g_key_file_save_to_file (key_file, filename, error)
#else
#define g_key_file_save_to_file(key_file, filename, error) \
({ \
gboolean _success; \
\
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
_success = g_key_file_save_to_file (key_file, filename, error); \
G_GNUC_END_IGNORE_DEPRECATIONS \
_success; \
})
#endif
#if GLIB_CHECK_VERSION (2, 36, 0)
#define g_credentials_get_unix_pid(creds, error) \
({ \
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
(g_credentials_get_unix_pid) ((creds), (error)); \
G_GNUC_END_IGNORE_DEPRECATIONS \
})
#else
#define g_credentials_get_unix_pid(creds, error) \
({ \
struct ucred *native_creds; \
\
native_creds = g_credentials_get_native ((creds), G_CREDENTIALS_TYPE_LINUX_UCRED); \
g_assert (native_creds); \
native_creds->pid; \
})
#endif
#if !GLIB_CHECK_VERSION(2, 40, 0) || defined (NM_GLIB_COMPAT_H_TEST)
static inline gpointer *
_nm_g_hash_table_get_keys_as_array (GHashTable *hash_table,
guint *length)
{
GHashTableIter iter;
gpointer key, *ret;
guint i = 0;
g_return_val_if_fail (hash_table, NULL);
ret = g_new0 (gpointer, g_hash_table_size (hash_table) + 1);
g_hash_table_iter_init (&iter, hash_table);
while (g_hash_table_iter_next (&iter, &key, NULL))
ret[i++] = key;
ret[i] = NULL;
if (length)
*length = i;
return ret;
}
#endif
#if !GLIB_CHECK_VERSION(2, 40, 0)
#define g_hash_table_get_keys_as_array(hash_table, length) \
({ \
_nm_g_hash_table_get_keys_as_array (hash_table, length); \
})
#else
#define g_hash_table_get_keys_as_array(hash_table, length) \
({ \
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
(g_hash_table_get_keys_as_array) ((hash_table), (length)); \
G_GNUC_END_IGNORE_DEPRECATIONS \
})
#endif
#ifndef g_info
/* g_info was only added with 2.39.2 */
#define g_info(...) g_log (G_LOG_DOMAIN, \
G_LOG_LEVEL_INFO, \
__VA_ARGS__)
#endif
#if !GLIB_CHECK_VERSION(2, 44, 0)
static inline gpointer
g_steal_pointer (gpointer pp)
{
gpointer *ptr = (gpointer *) pp;
gpointer ref;
ref = *ptr;
*ptr = NULL;
return ref;
}
/* type safety */
#define g_steal_pointer(pp) \
(0 ? (*(pp)) : (g_steal_pointer) (pp))
#endif
static inline gboolean
_nm_g_strv_contains (const gchar * const *strv,
const gchar *str)
{
#if !GLIB_CHECK_VERSION(2, 44, 0)
g_return_val_if_fail (strv != NULL, FALSE);
g_return_val_if_fail (str != NULL, FALSE);
for (; *strv != NULL; strv++) {
if (g_str_equal (str, *strv))
return TRUE;
}
return FALSE;
#else
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
return g_strv_contains (strv, str);
G_GNUC_END_IGNORE_DEPRECATIONS
#endif
}
#define g_strv_contains _nm_g_strv_contains
static inline GVariant *
_nm_g_variant_new_take_string (gchar *string)
{
#if !GLIB_CHECK_VERSION(2, 36, 0)
GVariant *value;
g_return_val_if_fail (string != NULL, NULL);
g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
value = g_variant_new_string (string);
g_free (string);
return value;
#elif !GLIB_CHECK_VERSION(2, 38, 0)
GVariant *value;
GBytes *bytes;
g_return_val_if_fail (string != NULL, NULL);
g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
bytes = g_bytes_new_take (string, strlen (string) + 1);
value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
g_bytes_unref (bytes);
return value;
#else
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
return g_variant_new_take_string (string);
G_GNUC_END_IGNORE_DEPRECATIONS
#endif
}
#define g_variant_new_take_string _nm_g_variant_new_take_string
#if !GLIB_CHECK_VERSION(2, 38, 0)
_nm_printf (1, 2)
static inline GVariant *
_nm_g_variant_new_printf (const char *format_string, ...)
{
char *string;
va_list ap;
g_return_val_if_fail (format_string, NULL);
va_start (ap, format_string);
string = g_strdup_vprintf (format_string, ap);
va_end (ap);
return g_variant_new_take_string (string);
}
#define g_variant_new_printf(...) _nm_g_variant_new_printf(__VA_ARGS__)
#else
#define g_variant_new_printf(...) \
({ \
GVariant *_v; \
\
G_GNUC_BEGIN_IGNORE_DEPRECATIONS \
_v = g_variant_new_printf (__VA_ARGS__); \
G_GNUC_END_IGNORE_DEPRECATIONS \
_v; \
})
#endif
#endif /* __NM_GLIB_H__ */
File diff suppressed because it is too large. Load diff
+821
View File
@@ -0,0 +1,821 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* (C) Copyright 2016 Red Hat, Inc.
*/
#include "nm-default.h"
#include "nm-shared-utils.h"
#include <errno.h>
#include <arpa/inet.h>
/*****************************************************************************/
const void *const _NM_PTRARRAY_EMPTY[1] = { NULL };
/*****************************************************************************/
const NMIPAddr nm_ip_addr_zero = { 0 };
/*****************************************************************************/
void
nm_utils_strbuf_append_c (char **buf, gsize *len, char c)
{
switch (*len) {
case 0:
return;
case 1:
(*buf)[0] = '\0';
*len = 0;
(*buf)++;
return;
default:
(*buf)[0] = c;
(*buf)[1] = '\0';
(*len)--;
(*buf)++;
return;
}
}
void
nm_utils_strbuf_append_str (char **buf, gsize *len, const char *str)
{
gsize src_len;
switch (*len) {
case 0:
return;
case 1:
if (!str || !*str) {
(*buf)[0] = '\0';
return;
}
(*buf)[0] = '\0';
*len = 0;
(*buf)++;
return;
default:
if (!str || !*str) {
(*buf)[0] = '\0';
return;
}
src_len = g_strlcpy (*buf, str, *len);
if (src_len >= *len) {
*buf = &(*buf)[*len];
*len = 0;
} else {
*buf = &(*buf)[src_len];
*len -= src_len;
}
return;
}
}
void
nm_utils_strbuf_append (char **buf, gsize *len, const char *format, ...)
{
char *p = *buf;
va_list args;
gint retval;
if (*len == 0)
return;
va_start (args, format);
retval = g_vsnprintf (p, *len, format, args);
va_end (args);
if (retval >= *len) {
*buf = &p[*len];
*len = 0;
} else {
*buf = &p[retval];
*len -= retval;
}
}
/*****************************************************************************/
/**
* _nm_utils_ip4_prefix_to_netmask:
* @prefix: a CIDR prefix
*
* Returns: the netmask represented by the prefix, in network byte order
**/
guint32
_nm_utils_ip4_prefix_to_netmask (guint32 prefix)
{
return prefix < 32 ? ~htonl(0xFFFFFFFF >> prefix) : 0xFFFFFFFF;
}
/**
* _nm_utils_ip4_get_default_prefix:
* @ip: an IPv4 address (in network byte order)
*
* When the Internet was originally set up, various ranges of IP addresses were
* segmented into three network classes: A, B, and C. This function will return
* a prefix that is associated with the IP address specified defining where it
* falls in the predefined classes.
*
* Returns: the default class prefix for the given IP
**/
/* The function is originally from ipcalc.c of Red Hat's initscripts. */
guint32
_nm_utils_ip4_get_default_prefix (guint32 ip)
{
if (((ntohl (ip) & 0xFF000000) >> 24) <= 127)
return 8; /* Class A - 255.0.0.0 */
else if (((ntohl (ip) & 0xFF000000) >> 24) <= 191)
return 16; /* Class B - 255.255.0.0 */
return 24; /* Class C - 255.255.255.0 */
}
gboolean
nm_utils_ip_is_site_local (int addr_family,
const void *address)
{
in_addr_t addr4;
switch (addr_family) {
case AF_INET:
/* RFC1918 private addresses
* 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 */
addr4 = ntohl (*((const in_addr_t *) address));
return (addr4 & 0xff000000) == 0x0a000000
|| (addr4 & 0xfff00000) == 0xac100000
|| (addr4 & 0xffff0000) == 0xc0a80000;
case AF_INET6:
return IN6_IS_ADDR_SITELOCAL (address);
default:
g_return_val_if_reached (FALSE);
}
}
/*****************************************************************************/
gboolean
nm_utils_parse_inaddr_bin (const char *text,
int family,
gpointer out_addr)
{
NMIPAddr addrbin;
g_return_val_if_fail (text, FALSE);
if (family == AF_UNSPEC)
family = strchr (text, ':') ? AF_INET6 : AF_INET;
else
g_return_val_if_fail (NM_IN_SET (family, AF_INET, AF_INET6), FALSE);
if (inet_pton (family, text, out_addr ?: &addrbin) != 1)
return FALSE;
return TRUE;
}
gboolean
nm_utils_parse_inaddr (const char *text,
int family,
char **out_addr)
{
NMIPAddr addrbin;
char addrstr_buf[MAX (INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
if (!nm_utils_parse_inaddr_bin (text, family, &addrbin))
return FALSE;
NM_SET_OUT (out_addr, g_strdup (inet_ntop (family, &addrbin, addrstr_buf, sizeof (addrstr_buf))));
return TRUE;
}
gboolean
nm_utils_parse_inaddr_prefix_bin (const char *text,
int family,
gpointer out_addr,
int *out_prefix)
{
gs_free char *addrstr_free = NULL;
int prefix = -1;
const char *slash;
const char *addrstr;
NMIPAddr addrbin;
int addr_len;
g_return_val_if_fail (text, FALSE);
if (family == AF_UNSPEC)
family = strchr (text, ':') ? AF_INET6 : AF_INET;
if (family == AF_INET)
addr_len = sizeof (in_addr_t);
else if (family == AF_INET6)
addr_len = sizeof (struct in6_addr);
else
g_return_val_if_reached (FALSE);
slash = strchr (text, '/');
if (slash)
addrstr = addrstr_free = g_strndup (text, slash - text);
else
addrstr = text;
if (inet_pton (family, addrstr, &addrbin) != 1)
return FALSE;
if (slash) {
prefix = _nm_utils_ascii_str_to_int64 (slash + 1, 10,
0,
family == AF_INET ? 32 : 128,
-1);
if (prefix == -1)
return FALSE;
}
if (out_addr)
memcpy (out_addr, &addrbin, addr_len);
NM_SET_OUT (out_prefix, prefix);
return TRUE;
}
gboolean
nm_utils_parse_inaddr_prefix (const char *text,
int family,
char **out_addr,
int *out_prefix)
{
NMIPAddr addrbin;
char addrstr_buf[MAX (INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
if (!nm_utils_parse_inaddr_prefix_bin (text, family, &addrbin, out_prefix))
return FALSE;
NM_SET_OUT (out_addr, g_strdup (inet_ntop (family, &addrbin, addrstr_buf, sizeof (addrstr_buf))));
return TRUE;
}
/*****************************************************************************/
/* _nm_utils_ascii_str_to_int64:
*
* A wrapper for g_ascii_strtoll, that checks whether the whole string
* can be successfully converted to a number and is within a given
* range. On any error, @fallback will be returned and %errno will be set
* to a non-zero value. On success, %errno will be set to zero, check %errno
* for errors. Any trailing or leading (ascii) white space is ignored and the
* functions is locale independent.
*
* The function is guaranteed to return a value between @min and @max
* (inclusive) or @fallback. Also, the parsing is rather strict, it does
* not allow for any unrecognized characters, except leading and trailing
* white space.
**/
gint64
_nm_utils_ascii_str_to_int64 (const char *str, guint base, gint64 min, gint64 max, gint64 fallback)
{
gint64 v;
const char *s = NULL;
if (str) {
while (g_ascii_isspace (str[0]))
str++;
}
if (!str || !str[0]) {
errno = EINVAL;
return fallback;
}
errno = 0;
v = g_ascii_strtoll (str, (char **) &s, base);
if (errno != 0)
return fallback;
if (s[0] != '\0') {
while (g_ascii_isspace (s[0]))
s++;
if (s[0] != '\0') {
errno = EINVAL;
return fallback;
}
}
if (v > max || v < min) {
errno = ERANGE;
return fallback;
}
return v;
}
/*****************************************************************************/
/**
* nm_utils_strsplit_set:
* @str: the string to split.
* @delimiters: the set of delimiters. If %NULL, defaults to " \t\n",
* like bash's $IFS.
*
* This is a replacement for g_strsplit_set() which avoids copying
* each word once (the entire strv array), but instead copies it once
* and all words point into that internal copy.
*
* Another difference from g_strsplit_set() is that this never returns
* empty words. Multiple delimiters are combined and treated as one.
*
* Returns: %NULL if @str is %NULL or contains only delimiters.
* Otherwise, a %NULL terminated strv array containing non-empty
* words, split at the delimiter characters (delimiter characters
* are removed).
* The strings to which the result strv array points to are allocated
* after the returned result itself. Don't free the strings themself,
* but free everything with g_free().
*/
const char **
nm_utils_strsplit_set (const char *str, const char *delimiters)
{
const char **ptr, **ptr0;
gsize alloc_size, plen, i;
gsize str_len;
char *s0;
char *s;
guint8 delimiters_table[256];
if (!str)
return NULL;
/* initialize lookup table for delimiter */
if (!delimiters)
delimiters = " \t\n";
memset (delimiters_table, 0, sizeof (delimiters_table));
for (i = 0; delimiters[i]; i++)
delimiters_table[(guint8) delimiters[i]] = 1;
#define _is_delimiter(ch, delimiters_table) \
((delimiters_table)[(guint8) (ch)] != 0)
/* skip initial delimiters, and return of the remaining string is
* empty. */
while (_is_delimiter (str[0], delimiters_table))
str++;
if (!str[0])
return NULL;
str_len = strlen (str) + 1;
alloc_size = 8;
/* we allocate the buffer larger, so to copy @str at the
* end of it as @s0. */
ptr0 = g_malloc ((sizeof (const char *) * (alloc_size + 1)) + str_len);
s0 = (char *) &ptr0[alloc_size + 1];
memcpy (s0, str, str_len);
plen = 0;
s = s0;
ptr = ptr0;
while (TRUE) {
if (plen >= alloc_size) {
const char **ptr_old = ptr;
/* reallocate the buffer. Note that for now the string
* continues to be in ptr0/s0. We fix that at the end. */
alloc_size += 2;
ptr = g_malloc ((sizeof (const char *) * (alloc_size + 1)) + str_len);
memcpy (ptr, ptr_old, sizeof (const char *) * plen);
if (ptr_old != ptr0)
g_free (ptr_old);
}
ptr[plen++] = s;
nm_assert (s[0] && !_is_delimiter (s[0], delimiters_table));
while (TRUE) {
s++;
if (_is_delimiter (s[0], delimiters_table))
break;
if (s[0] == '\0')
goto done;
}
s[0] = '\0';
s++;
while (_is_delimiter (s[0], delimiters_table))
s++;
if (s[0] == '\0')
break;
}
done:
ptr[plen] = NULL;
if (ptr != ptr0) {
/* we reallocated the buffer. We must copy over the
* string @s0 and adjust the pointers. */
s = (char *) &ptr[alloc_size + 1];
memcpy (s, s0, str_len);
for (i = 0; i < plen; i++)
ptr[i] = &s[ptr[i] - s0];
g_free (ptr0);
}
return ptr;
}
/**
* nm_utils_strv_find_first:
* @list: the strv list to search
* @len: the length of the list, or a negative value if @list is %NULL terminated.
* @needle: the value to search for. The search is done using strcmp().
*
* Searches @list for @needle and returns the index of the first match (based
* on strcmp()).
*
* For convenience, @list has type 'char**' instead of 'const char **'.
*
* Returns: index of first occurrence or -1 if @needle is not found in @list.
*/
gssize
nm_utils_strv_find_first (char **list, gssize len, const char *needle)
{
gssize i;
if (len > 0) {
g_return_val_if_fail (list, -1);
if (!needle) {
/* if we search a list with known length, %NULL is a valid @needle. */
for (i = 0; i < len; i++) {
if (!list[i])
return i;
}
} else {
for (i = 0; i < len; i++) {
if (list[i] && !strcmp (needle, list[i]))
return i;
}
}
} else if (len < 0) {
g_return_val_if_fail (needle, -1);
if (list) {
for (i = 0; list[i]; i++) {
if (strcmp (needle, list[i]) == 0)
return i;
}
}
}
return -1;
}
char **
_nm_utils_strv_cleanup (char **strv,
gboolean strip_whitespace,
gboolean skip_empty,
gboolean skip_repeated)
{
guint i, j;
if (!strv || !*strv)
return strv;
if (strip_whitespace) {
for (i = 0; strv[i]; i++)
g_strstrip (strv[i]);
}
if (!skip_empty && !skip_repeated)
return strv;
j = 0;
for (i = 0; strv[i]; i++) {
if ( (skip_empty && !*strv[i])
|| (skip_repeated && nm_utils_strv_find_first (strv, j, strv[i]) >= 0))
g_free (strv[i]);
else
strv[j++] = strv[i];
}
strv[j] = NULL;
return strv;
}
/*****************************************************************************/
gint
_nm_utils_ascii_str_to_bool (const char *str,
gint default_value)
{
gsize len;
char *s = NULL;
if (!str)
return default_value;
while (str[0] && g_ascii_isspace (str[0]))
str++;
if (!str[0])
return default_value;
len = strlen (str);
if (g_ascii_isspace (str[len - 1])) {
s = g_strdup (str);
g_strchomp (s);
str = s;
}
if (!g_ascii_strcasecmp (str, "true") || !g_ascii_strcasecmp (str, "yes") || !g_ascii_strcasecmp (str, "on") || !g_ascii_strcasecmp (str, "1"))
default_value = TRUE;
else if (!g_ascii_strcasecmp (str, "false") || !g_ascii_strcasecmp (str, "no") || !g_ascii_strcasecmp (str, "off") || !g_ascii_strcasecmp (str, "0"))
default_value = FALSE;
if (s)
g_free (s);
return default_value;
}
/*****************************************************************************/
NM_CACHED_QUARK_FCN ("nm-utils-error-quark", nm_utils_error_quark)
void
nm_utils_error_set_cancelled (GError **error,
gboolean is_disposing,
const char *instance_name)
{
if (is_disposing) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_CANCELLED_DISPOSING,
"Disposing %s instance",
instance_name && *instance_name ? instance_name : "source");
} else {
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CANCELLED,
"Request cancelled");
}
}
gboolean
nm_utils_error_is_cancelled (GError *error,
gboolean consider_is_disposing)
{
if (error) {
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
return TRUE;
if ( consider_is_disposing
&& g_error_matches (error, NM_UTILS_ERROR, NM_UTILS_ERROR_CANCELLED_DISPOSING))
return TRUE;
}
return FALSE;
}
/*****************************************************************************/
/**
* nm_g_object_set_property:
* @object: the target object
* @property_name: the property name
* @value: the #GValue to set
* @error: (allow-none): optional error argument
*
* A reimplementation of g_object_set_property(), but instead
* returning an error instead of logging a warning. All g_object_set*()
* versions in glib require you to not pass invalid types or they will
* log a g_warning() -- without reporting an error. We don't want that,
* so we need to hack error checking around it.
*
* Returns: whether the value was successfully set.
*/
gboolean
nm_g_object_set_property (GObject *object,
const gchar *property_name,
const GValue *value,
GError **error)
{
GParamSpec *pspec;
nm_auto_unset_gvalue GValue tmp_value = G_VALUE_INIT;
GObjectClass *klass;
g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
g_return_val_if_fail (property_name != NULL, FALSE);
g_return_val_if_fail (G_IS_VALUE (value), FALSE);
g_return_val_if_fail (!error || !*error, FALSE);
/* g_object_class_find_property() does g_param_spec_get_redirect_target(),
* where we differ from a plain g_object_set_property(). */
pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (object), property_name);
if (!pspec) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("object class '%s' has no property named '%s'"),
G_OBJECT_TYPE_NAME (object),
property_name);
return FALSE;
}
if (!(pspec->flags & G_PARAM_WRITABLE)) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("property '%s' of object class '%s' is not writable"),
pspec->name,
G_OBJECT_TYPE_NAME (object));
return FALSE;
}
if ((pspec->flags & G_PARAM_CONSTRUCT_ONLY)) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("construct property \"%s\" for object '%s' can't be set after construction"),
pspec->name, G_OBJECT_TYPE_NAME (object));
return FALSE;
}
klass = g_type_class_peek (pspec->owner_type);
if (klass == NULL) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("'%s::%s' is not a valid property name; '%s' is not a GObject subtype"),
g_type_name (pspec->owner_type), pspec->name, g_type_name (pspec->owner_type));
return FALSE;
}
/* provide a copy to work from, convert (if necessary) and validate */
g_value_init (&tmp_value, pspec->value_type);
if (!g_value_transform (value, &tmp_value)) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("unable to set property '%s' of type '%s' from value of type '%s'"),
pspec->name,
g_type_name (pspec->value_type),
G_VALUE_TYPE_NAME (value));
return FALSE;
}
if ( g_param_value_validate (pspec, &tmp_value)
&& !(pspec->flags & G_PARAM_LAX_VALIDATION)) {
gs_free char *contents = g_strdup_value_contents (value);
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("value \"%s\" of type '%s' is invalid or out of range for property '%s' of type '%s'"),
contents,
G_VALUE_TYPE_NAME (value),
pspec->name,
g_type_name (pspec->value_type));
return FALSE;
}
g_object_set_property (object, property_name, &tmp_value);
return TRUE;
}
GParamSpec *
nm_g_object_class_find_property_from_gtype (GType gtype,
const char *property_name)
{
nm_auto_unref_gtypeclass GObjectClass *gclass = NULL;
gclass = g_type_class_ref (gtype);
return g_object_class_find_property (gclass, property_name);
}
/*****************************************************************************/
static void
_str_append_escape (GString *s, char ch)
{
g_string_append_c (s, '\\');
g_string_append_c (s, '0' + ((((guchar) ch) >> 6) & 07));
g_string_append_c (s, '0' + ((((guchar) ch) >> 3) & 07));
g_string_append_c (s, '0' + ( ((guchar) ch) & 07));
}
/**
* nm_utils_str_utf8safe_escape:
* @str: NUL terminated input string, possibly in utf-8 encoding
* @flags: #NMUtilsStrUtf8SafeFlags flags
* @to_free: (out): return the pointer location of the string
* if a copying was necessary.
*
* Returns the possible non-UTF-8 NUL terminated string @str
* and uses backslash escaping (C escaping, like g_strescape())
* to sanitize non UTF-8 characters. The result is valid
* UTF-8.
*
* The operation can be reverted with g_strcompress() or
* nm_utils_str_utf8safe_unescape().
*
* Depending on @flags, valid UTF-8 characters are not escaped at all
* (except the escape character '\\'). This is the difference to g_strescape(),
* which escapes all non-ASCII characters. This allows to pass on
* valid UTF-8 characters as-is and can be directly shown to the user
* as UTF-8 -- with exception of the backslash escape character,
* invalid UTF-8 sequences, and other (depending on @flags).
*
* Returns: the escaped input string, as valid UTF-8. If no escaping
* is necessary, it returns the input @str. Otherwise, an allocated
* string @to_free is returned which must be freed by the caller
* with g_free. The escaping can be reverted by g_strcompress().
**/
const char *
nm_utils_str_utf8safe_escape (const char *str, NMUtilsStrUtf8SafeFlags flags, char **to_free)
{
const char *p = NULL;
GString *s;
g_return_val_if_fail (to_free, NULL);
*to_free = NULL;
if (!str || !str[0])
return str;
if ( g_utf8_validate (str, -1, &p)
&& !NM_STRCHAR_ANY (str, ch,
( ch == '\\' \
|| ( NM_FLAGS_HAS (flags, NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL) \
&& ch < ' ') \
|| ( NM_FLAGS_HAS (flags, NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_NON_ASCII) \
&& ((guchar) ch) >= 127))))
return str;
s = g_string_sized_new ((p - str) + strlen (p) + 5);
do {
for (; str < p; str++) {
char ch = str[0];
if (ch == '\\')
g_string_append (s, "\\\\");
else if ( ( NM_FLAGS_HAS (flags, NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL) \
&& ch < ' ') \
|| ( NM_FLAGS_HAS (flags, NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_NON_ASCII) \
&& ((guchar) ch) >= 127))
_str_append_escape (s, ch);
else
g_string_append_c (s, ch);
}
if (p[0] == '\0')
break;
_str_append_escape (s, p[0]);
str = &p[1];
g_utf8_validate (str, -1, &p);
} while (TRUE);
*to_free = g_string_free (s, FALSE);
return *to_free;
}
const char *
nm_utils_str_utf8safe_unescape (const char *str, char **to_free)
{
g_return_val_if_fail (to_free, NULL);
if (!str || !strchr (str, '\\')) {
*to_free = NULL;
return str;
}
return (*to_free = g_strcompress (str));
}
/**
* nm_utils_str_utf8safe_escape_cp:
* @str: NUL terminated input string, possibly in utf-8 encoding
* @flags: #NMUtilsStrUtf8SafeFlags flags
*
* Like nm_utils_str_utf8safe_escape(), except the returned value
* is always a copy of the input and must be freed by the caller.
*
* Returns: the escaped input string in UTF-8 encoding. The returned
* value should be freed with g_free().
* The escaping can be reverted by g_strcompress().
**/
char *
nm_utils_str_utf8safe_escape_cp (const char *str, NMUtilsStrUtf8SafeFlags flags)
{
char *s;
nm_utils_str_utf8safe_escape (str, flags, &s);
return s ?: g_strdup (str);
}
char *
nm_utils_str_utf8safe_unescape_cp (const char *str)
{
return str ? g_strcompress (str) : NULL;
}
char *
nm_utils_str_utf8safe_escape_take (char *str, NMUtilsStrUtf8SafeFlags flags)
{
char *str_to_free;
nm_utils_str_utf8safe_escape (str, flags, &str_to_free);
if (str_to_free) {
g_free (str);
return str_to_free;
}
return str;
}
+302
View File
@@ -0,0 +1,302 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* (C) Copyright 2016 Red Hat, Inc.
*/
#ifndef __NM_SHARED_UTILS_H__
#define __NM_SHARED_UTILS_H__
#include <netinet/in.h>
/*****************************************************************************/
typedef struct {
union {
guint8 addr_ptr[1];
in_addr_t addr4;
struct in6_addr addr6;
/* NMIPAddr is really a union for IP addresses.
* However, as ethernet addresses fit in here nicely, use
* it also for an ethernet MAC address. */
guint8 addr_eth[6 /*ETH_ALEN*/];
};
} NMIPAddr;
extern const NMIPAddr nm_ip_addr_zero;
/*****************************************************************************/
#define NM_CMP_RETURN(c) \
G_STMT_START { \
const int _cc = (c); \
if (_cc) \
return _cc < 0 ? -1 : 1; \
} G_STMT_END
#define NM_CMP_SELF(a, b) \
G_STMT_START { \
typeof (a) _a = (a); \
typeof (b) _b = (b); \
\
if (_a == _b) \
return 0; \
if (!_a) \
return -1; \
if (!_b) \
return 1; \
} G_STMT_END
#define NM_CMP_DIRECT(a, b) \
G_STMT_START { \
typeof (a) _a = (a); \
typeof (b) _b = (b); \
\
if (_a != _b) \
return (_a < _b) ? -1 : 1; \
} G_STMT_END
#define NM_CMP_DIRECT_MEMCMP(a, b, size) \
NM_CMP_RETURN (memcmp ((a), (b), (size)))
#define NM_CMP_DIRECT_IN6ADDR(a, b) \
G_STMT_START { \
const struct in6_addr *const _a = (a); \
const struct in6_addr *const _b = (b); \
NM_CMP_RETURN (memcmp (_a, _b, sizeof (struct in6_addr))); \
} G_STMT_END
#define NM_CMP_FIELD(a, b, field) \
NM_CMP_DIRECT (((a)->field), ((b)->field))
#define NM_CMP_FIELD_UNSAFE(a, b, field) \
G_STMT_START { \
/* it's unsafe, because it evaluates the arguments more then once.
* This is necessary for bitfields, for which typeof() doesn't work. */ \
if (((a)->field) != ((b)->field)) \
return ((a)->field < ((b)->field)) ? -1 : 1; \
} G_STMT_END
#define NM_CMP_FIELD_BOOL(a, b, field) \
NM_CMP_DIRECT (!!((a)->field), !!((b)->field))
#define NM_CMP_FIELD_STR(a, b, field) \
NM_CMP_RETURN (strcmp (((a)->field), ((b)->field)))
#define NM_CMP_FIELD_STR_INTERNED(a, b, field) \
G_STMT_START { \
const char *_a = ((a)->field); \
const char *_b = ((b)->field); \
\
if (_a != _b) { \
NM_CMP_RETURN (g_strcmp0 (_a, _b)); \
} \
} G_STMT_END
#define NM_CMP_FIELD_STR0(a, b, field) \
NM_CMP_RETURN (g_strcmp0 (((a)->field), ((b)->field)))
#define NM_CMP_FIELD_MEMCMP_LEN(a, b, field, len) \
NM_CMP_RETURN (memcmp (&((a)->field), &((b)->field), \
MIN (len, sizeof ((a)->field))))
#define NM_CMP_FIELD_MEMCMP(a, b, field) \
NM_CMP_RETURN (memcmp (&((a)->field), \
&((b)->field), \
sizeof ((a)->field)))
#define NM_CMP_FIELD_IN6ADDR(a, b, field) \
G_STMT_START { \
const struct in6_addr *const _a = &((a)->field); \
const struct in6_addr *const _b = &((b)->field); \
NM_CMP_RETURN (memcmp (_a, _b, sizeof (struct in6_addr))); \
} G_STMT_END
/*****************************************************************************/
extern const void *const _NM_PTRARRAY_EMPTY[1];
#define NM_PTRARRAY_EMPTY(type) ((type const*) _NM_PTRARRAY_EMPTY)
static inline void
_nm_utils_strbuf_init (char *buf, gsize len, char **p_buf_ptr, gsize *p_buf_len)
{
NM_SET_OUT (p_buf_len, len);
NM_SET_OUT (p_buf_ptr, buf);
buf[0] = '\0';
}
#define nm_utils_strbuf_init(buf, p_buf_ptr, p_buf_len) \
G_STMT_START { \
G_STATIC_ASSERT (G_N_ELEMENTS (buf) == sizeof (buf) && sizeof (buf) > sizeof (char *)); \
_nm_utils_strbuf_init ((buf), sizeof (buf), (p_buf_ptr), (p_buf_len)); \
} G_STMT_END
void nm_utils_strbuf_append (char **buf, gsize *len, const char *format, ...) _nm_printf (3, 4);
void nm_utils_strbuf_append_c (char **buf, gsize *len, char c);
void nm_utils_strbuf_append_str (char **buf, gsize *len, const char *str);
/*****************************************************************************/
const char **nm_utils_strsplit_set (const char *str, const char *delimiters);
gssize nm_utils_strv_find_first (char **list, gssize len, const char *needle);
char **_nm_utils_strv_cleanup (char **strv,
gboolean strip_whitespace,
gboolean skip_empty,
gboolean skip_repeated);
/*****************************************************************************/
guint32 _nm_utils_ip4_prefix_to_netmask (guint32 prefix);
guint32 _nm_utils_ip4_get_default_prefix (guint32 ip);
gboolean nm_utils_ip_is_site_local (int addr_family,
const void *address);
/*****************************************************************************/
gboolean nm_utils_parse_inaddr_bin (const char *text,
int family,
gpointer out_addr);
gboolean nm_utils_parse_inaddr (const char *text,
int family,
char **out_addr);
gboolean nm_utils_parse_inaddr_prefix_bin (const char *text,
int family,
gpointer out_addr,
int *out_prefix);
gboolean nm_utils_parse_inaddr_prefix (const char *text,
int family,
char **out_addr,
int *out_prefix);
gint64 _nm_utils_ascii_str_to_int64 (const char *str, guint base, gint64 min, gint64 max, gint64 fallback);
gint _nm_utils_ascii_str_to_bool (const char *str,
gint default_value);
/*****************************************************************************/
#define _nm_g_slice_free_fcn_define(mem_size) \
static inline void \
_nm_g_slice_free_fcn_##mem_size (gpointer mem_block) \
{ \
g_slice_free1 (mem_size, mem_block); \
}
_nm_g_slice_free_fcn_define (1)
_nm_g_slice_free_fcn_define (2)
_nm_g_slice_free_fcn_define (4)
_nm_g_slice_free_fcn_define (8)
_nm_g_slice_free_fcn_define (12)
_nm_g_slice_free_fcn_define (16)
#define _nm_g_slice_free_fcn1(mem_size) \
({ \
void (*_fcn) (gpointer); \
\
/* If mem_size is a compile time constant, the compiler
* will be able to optimize this. Hence, you don't want
* to call this with a non-constant size argument. */ \
switch (mem_size) { \
case 1: _fcn = _nm_g_slice_free_fcn_1; break; \
case 2: _fcn = _nm_g_slice_free_fcn_2; break; \
case 4: _fcn = _nm_g_slice_free_fcn_4; break; \
case 8: _fcn = _nm_g_slice_free_fcn_8; break; \
case 12: _fcn = _nm_g_slice_free_fcn_12; break; \
case 16: _fcn = _nm_g_slice_free_fcn_16; break; \
default: g_assert_not_reached (); _fcn = NULL; break; \
} \
_fcn; \
})
/**
* nm_g_slice_free_fcn:
* @type: type argument for sizeof() operator that you would
* pass to g_slice_new().
*
* Returns: a function pointer with GDestroyNotify signature
* for g_slice_free(type,*).
*
* Only certain types are implemented. You'll get an assertion
* using the wrong type. */
#define nm_g_slice_free_fcn(type) (_nm_g_slice_free_fcn1 (sizeof (type)))
#define nm_g_slice_free_fcn_gint64 (nm_g_slice_free_fcn (gint64))
/*****************************************************************************/
/**
* NMUtilsError:
* @NM_UTILS_ERROR_UNKNOWN: unknown or unclassified error
* @NM_UTILS_ERROR_CANCELLED_DISPOSING: when disposing an object that has
* pending aynchronous operations, the operation is cancelled with this
* error reason. Depending on the usage, this might indicate a bug because
* usually the target object should stay alive as long as there are pending
* operations.
* @NM_UTILS_ERROR_INVALID_ARGUMENT: invalid argument.
*/
typedef enum {
NM_UTILS_ERROR_UNKNOWN = 0, /*< nick=Unknown >*/
NM_UTILS_ERROR_CANCELLED_DISPOSING, /*< nick=CancelledDisposing >*/
NM_UTILS_ERROR_INVALID_ARGUMENT, /*< nick=InvalidArgument >*/
} NMUtilsError;
#define NM_UTILS_ERROR (nm_utils_error_quark ())
GQuark nm_utils_error_quark (void);
void nm_utils_error_set_cancelled (GError **error,
gboolean is_disposing,
const char *instance_name);
gboolean nm_utils_error_is_cancelled (GError *error,
gboolean consider_is_disposing);
/*****************************************************************************/
gboolean nm_g_object_set_property (GObject *object,
const gchar *property_name,
const GValue *value,
GError **error);
GParamSpec *nm_g_object_class_find_property_from_gtype (GType gtype,
const char *property_name);
/*****************************************************************************/
typedef enum {
NM_UTILS_STR_UTF8_SAFE_FLAG_NONE = 0,
NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL = 0x0001,
NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_NON_ASCII = 0x0002,
} NMUtilsStrUtf8SafeFlags;
const char *nm_utils_str_utf8safe_escape (const char *str, NMUtilsStrUtf8SafeFlags flags, char **to_free);
const char *nm_utils_str_utf8safe_unescape (const char *str, char **to_free);
char *nm_utils_str_utf8safe_escape_cp (const char *str, NMUtilsStrUtf8SafeFlags flags);
char *nm_utils_str_utf8safe_unescape_cp (const char *str);
char *nm_utils_str_utf8safe_escape_take (char *str, NMUtilsStrUtf8SafeFlags flags);
/*****************************************************************************/
#endif /* __NM_SHARED_UTILS_H__ */
File diff suppressed because it is too large. Load diff
+93
View File
@@ -0,0 +1,93 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* Copyright 2016 Red Hat, Inc.
*/
#ifndef __NM_VPN_PLUGIN_MACROS_H__
#define __NM_VPN_PLUGIN_MACROS_H__
#include <syslog.h>
static inline int
nm_utils_syslog_coerce_from_nm (int syslog_level)
{
/* NetworkManager uses internally NMLogLevel levels. When spawning
* the VPN plugin, it maps those levels to syslog levels as follows:
*
* LOGL_INFO = LOG_NOTICE,
* LOGL_DEBUG = LOG_INFO,
* LOGL_TRACE = LOG_DEBUG,
*
* However, when actually printing to syslog, we don't want to print messages
* with LOGL_INFO level as LOG_NOTICE, because they are *not* to be highlighted.
*
* In other words: NetworkManager has 3 levels that should not require highlighting:
* LOGL_INFO, LOGL_DEBUG, LOGL_TRACE. syslog on the other hand has only LOG_INFO and LOG_DEBUG.
*
* So, coerce those values before printing to syslog. When you receive the syslog_level
* from NetworkManager, instead of calling
* syslog(syslog_level, ...)
* you should call
* syslog(nm_utils_syslog_coerce_from_nm(syslog_level), ...)
*/
switch (syslog_level) {
case LOG_INFO:
return LOG_DEBUG;
case LOG_NOTICE:
return LOG_INFO;
default:
return syslog_level;
}
}
static inline const char *
nm_utils_syslog_to_str (int syslog_level)
{
/* Maps the levels the same way as NetworkManager's nm-logging.c does */
if (syslog_level >= LOG_DEBUG)
return "<trace>";
if (syslog_level >= LOG_INFO)
return "<debug>";
if (syslog_level >= LOG_NOTICE)
return "<info>";
if (syslog_level >= LOG_WARNING)
return "<warn>";
return "<error>";
}
/*****************************************************************************/
/* possibly missing defines from newer libnm API. */
#ifndef NM_VPN_PLUGIN_CONFIG_PROXY_PAC
#define NM_VPN_PLUGIN_CONFIG_PROXY_PAC "pac"
#endif
#ifndef NM_VPN_PLUGIN_IP4_CONFIG_PRESERVE_ROUTES
#define NM_VPN_PLUGIN_IP4_CONFIG_PRESERVE_ROUTES "preserve-routes"
#endif
#ifndef NM_VPN_PLUGIN_IP6_CONFIG_PRESERVE_ROUTES
#define NM_VPN_PLUGIN_IP6_CONFIG_PRESERVE_ROUTES "preserve-routes"
#endif
/*****************************************************************************/
#endif /* __NM_VPN_PLUGIN_MACROS_H__ */
+130
View File
@@ -0,0 +1,130 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* Copyright 2016 Red Hat, Inc.
*/
#include "nm-default.h"
#include "nm-vpn-plugin-utils.h"
#include <dlfcn.h>
/*****************************************************************************/
NMVpnEditor *
nm_vpn_plugin_utils_load_editor (const char *module_name,
const char *factory_name,
NMVpnPluginUtilsEditorFactory editor_factory,
NMVpnEditorPlugin *editor_plugin,
NMConnection *connection,
gpointer user_data,
GError **error)
{
static struct {
gpointer factory;
void *dl_module;
char *module_name;
char *factory_name;
} cached = { 0 };
NMVpnEditor *editor;
g_return_val_if_fail (module_name && g_path_is_absolute (module_name), NULL);
g_return_val_if_fail (factory_name && factory_name[0], NULL);
g_return_val_if_fail (editor_factory, NULL);
g_return_val_if_fail (NM_IS_VPN_EDITOR_PLUGIN (editor_plugin), NULL);
g_return_val_if_fail (NM_IS_CONNECTION (connection), NULL);
g_return_val_if_fail (!error || !*error, NULL);
/* we really expect this function to be called with unchanging @module_name
* and @factory_name. And we only want to load the module once, hence it would
* be more complicated to accept changing @module_name/@factory_name arguments.
*
* The reason for only loading once is that due to glib types, we cannot create a
* certain type-name more then once, so loading the same module or another version
* of the same module will fail horribly as both try to create a GType with the same
* name.
*
* Only support loading once, any future calls will reuse the handle. To simplify
* that, we enforce that the @factory_name and @module_name is the same. */
if (cached.factory) {
g_return_val_if_fail (cached.dl_module, NULL);
g_return_val_if_fail (cached.factory_name && nm_streq0 (cached.factory_name, factory_name), NULL);
g_return_val_if_fail (cached.module_name && nm_streq0 (cached.module_name, module_name), NULL);
} else {
gpointer factory;
void *dl_module;
dl_module = dlopen (module_name, RTLD_LAZY | RTLD_LOCAL);
if (!dl_module) {
if (!g_file_test (module_name, G_FILE_TEST_EXISTS)) {
g_set_error (error,
G_FILE_ERROR,
G_FILE_ERROR_NOENT,
_("missing plugin file \"%s\""), module_name);
return NULL;
}
g_set_error (error,
NM_CONNECTION_ERROR,
NM_CONNECTION_ERROR_FAILED,
_("cannot load editor plugin: %s"), dlerror ());
return NULL;
}
factory = dlsym (dl_module, factory_name);
if (!factory) {
g_set_error (error,
NM_CONNECTION_ERROR,
NM_CONNECTION_ERROR_FAILED,
_("cannot load factory %s from plugin: %s"),
factory_name, dlerror ());
dlclose (dl_module);
return NULL;
}
/* we cannot ever unload the module because it creates glib types, which
* cannot be unregistered.
*
* Thus we just leak the dl_module handle indefinitely. */
cached.factory = factory;
cached.dl_module = dl_module;
cached.module_name = g_strdup (module_name);
cached.factory_name = g_strdup (factory_name);
}
editor = editor_factory (cached.factory,
editor_plugin,
connection,
user_data,
error);
if (!editor) {
if (error && !*error ) {
g_set_error_literal (error,
NM_CONNECTION_ERROR,
NM_CONNECTION_ERROR_FAILED,
_("unknown error creating editor instance"));
g_return_val_if_reached (NULL);
}
return NULL;
}
g_return_val_if_fail (NM_IS_VPN_EDITOR (editor), NULL);
return editor;
}
+42
View File
@@ -0,0 +1,42 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* Copyright 2016 Red Hat, Inc.
*/
#ifndef __NM_VPN_PLUGIN_UTILS_H__
#define __NM_VPN_PLUGIN_UTILS_H__
#include <NetworkManager.h>
typedef NMVpnEditor *(NMVpnPluginUtilsEditorFactory) (gpointer factory,
NMVpnEditorPlugin *editor_plugin,
NMConnection *connection,
gpointer user_data,
GError **error);
NMVpnEditor *nm_vpn_plugin_utils_load_editor (const char *module_name,
const char *factory_name,
NMVpnPluginUtilsEditorFactory editor_factory,
NMVpnEditorPlugin *editor_plugin,
NMConnection *connection,
gpointer user_data,
GError **error);
#endif /* __NM_VPN_PLUGIN_UTILS_H__ */
+250
View File
@@ -0,0 +1,250 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* Dan Williams <dcbw@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* (C) Copyright 2010 Red Hat, Inc.
*/
#include "nm-default.h"
#include "utils.h"
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include "nm-utils/nm-shared-utils.h"
gboolean
is_pkcs12 (const char *filepath)
{
NMSetting8021xCKFormat ck_format = NM_SETTING_802_1X_CK_FORMAT_UNKNOWN;
NMSetting8021x *s_8021x;
if (!filepath || !strlen (filepath))
return FALSE;
if (!g_file_test (filepath, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
return FALSE;
s_8021x = (NMSetting8021x *) nm_setting_802_1x_new ();
g_return_val_if_fail (s_8021x != NULL, FALSE);
nm_setting_802_1x_set_private_key (s_8021x,
filepath,
NULL,
NM_SETTING_802_1X_CK_SCHEME_PATH,
&ck_format,
NULL);
g_object_unref (s_8021x);
return (ck_format == NM_SETTING_802_1X_CK_FORMAT_PKCS12);
}
#define PROC_TYPE_TAG "Proc-Type: 4,ENCRYPTED"
#define PKCS8_TAG "-----BEGIN ENCRYPTED PRIVATE KEY-----"
/** Checks if a file appears to be an encrypted private key.
* @param filename the path to the file
* @return returns true if the key is encrypted, false otherwise
*/
gboolean
is_encrypted (const char *filename)
{
GIOChannel *pem_chan;
char *str = NULL;
gboolean encrypted = FALSE;
if (!filename || !strlen (filename))
return FALSE;
if (is_pkcs12 (filename))
return TRUE;
pem_chan = g_io_channel_new_file (filename, "r", NULL);
if (!pem_chan)
return FALSE;
while (g_io_channel_read_line (pem_chan, &str, NULL, NULL, NULL) != G_IO_STATUS_EOF) {
if (str) {
if (g_str_has_prefix (str, PROC_TYPE_TAG) || g_str_has_prefix (str, PKCS8_TAG)) {
encrypted = TRUE;
break;
}
g_free (str);
}
}
g_io_channel_shutdown (pem_chan, FALSE, NULL);
g_io_channel_unref (pem_chan);
return encrypted;
}
static gboolean
_is_inet6_addr (const char *str, gboolean with_square_brackets)
{
struct in6_addr a;
gsize l;
if ( with_square_brackets
&& str[0] == '[') {
l = strlen (str);
if (str[l - 1] == ']') {
gs_free char *s = g_strndup (&str[1], l - 2);
return inet_pton (AF_INET6, s, &a) == 1;
}
}
return inet_pton (AF_INET6, str, &a) == 1;
}
/**
* nmovpn_remote_parse:
* @str: the input string to be split. It is modified inplace.
* @out_buf: an allocated string, to which the other arguments
* point to. Must be freeded by caller.
* @out_host: pointer to the host out argument.
* @out_port: pointer to the port out argument.
* @out_proto: pointer to the proto out argument.
* @error:
*
* Splits @str in three parts host, port and proto.
*
* Returns: -1 on success or index in @str of first invalid character.
* Note that the error index can be at strlen(str), if some data is missing.
**/
gssize
nmovpn_remote_parse (const char *str,
char **out_buf,
const char **out_host,
const char **out_port,
const char **out_proto,
GError **error)
{
gs_free char *str_copy = NULL;
char *t;
char *host = NULL;
char *port = NULL;
char *proto = NULL;
gssize idx_fail;
g_return_val_if_fail (str, 0);
if (!out_buf) {
/* one can omit @out_buf only if also no other out-arguments
* are requested. */
if (out_host || out_port || out_proto)
g_return_val_if_reached (0);
}
g_return_val_if_fail (!error || !*error, 0);
t = strchr (str, ' ');
if (!t)
t = strchr (str, ',');
if (t) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("invalid delimiter character '%c'"), t[0]);
idx_fail = t - str;
goto out_fail;
}
if (!g_utf8_validate (str, -1, (const char **) &t)) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("invalid non-utf-8 character"));
idx_fail = t - str;
goto out_fail;
}
str_copy = g_strdup (str);
/* we already checked that there is no space above.
* Strip tabs nonetheless. */
host = nm_str_skip_leading_spaces (str_copy);
g_strchomp (host);
t = strrchr (host, ':');
if ( t
&& !_is_inet6_addr (host, TRUE)) {
t[0] = '\0';
port = &t[1];
t = strrchr (host, ':');
if ( t
&& !_is_inet6_addr (host, TRUE)) {
t[0] = '\0';
proto = port;
port = &t[1];
}
}
if (!host[0]) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("empty host"));
idx_fail = host - str;
goto out_fail;
}
if (port) {
if (!port[0]) {
/* allow empty port like "host::udp". */
port = NULL;
} else if (_nm_utils_ascii_str_to_int64 (port, 10, 1, 0xFFFF, 0) == 0) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("invalid port"));
idx_fail = port - str;
goto out_fail;
}
}
if (proto) {
if (!proto[0]) {
/* allow empty proto, so that host can contain ':'. */
proto = NULL;
} else if (!NM_IN_STRSET (proto, NMOVPN_PROTCOL_TYPES)) {
g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
_("invalid protocol"));
idx_fail = proto - str;
goto out_fail;
}
}
if (out_buf) {
*out_buf = g_steal_pointer (&str_copy);
if ( host[0] == '['
&& _is_inet6_addr (host, TRUE)
&& !_is_inet6_addr (host, FALSE)) {
gsize l;
host++;
l = strlen (host);
nm_assert (l > 0 && host[l - 1] == ']');
host[l - 1] = '\0';
nm_assert (_is_inet6_addr (host, FALSE));
}
NM_SET_OUT (out_host, host);
NM_SET_OUT (out_port, port);
NM_SET_OUT (out_proto, proto);
}
return -1;
out_fail:
if (out_buf) {
*out_buf = NULL;
NM_SET_OUT (out_host, NULL);
NM_SET_OUT (out_port, NULL);
NM_SET_OUT (out_proto, NULL);
}
return idx_fail;
}
/*****************************************************************************/
+101
View File
@@ -0,0 +1,101 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
* Dan Williams <dcbw@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* (C) Copyright 2010 Red Hat, Inc.
*/
#ifndef UTILS_H
#define UTILS_H
#define NMV_OVPN_TAG_AUTH "auth"
#define NMV_OVPN_TAG_AUTH_NOCACHE "auth-nocache"
#define NMV_OVPN_TAG_AUTH_USER_PASS "auth-user-pass"
#define NMV_OVPN_TAG_CA "ca"
#define NMV_OVPN_TAG_CERT "cert"
#define NMV_OVPN_TAG_CIPHER "cipher"
#define NMV_OVPN_TAG_CLIENT "client"
#define NMV_OVPN_TAG_COMP_LZO "comp-lzo"
#define NMV_OVPN_TAG_DEV "dev"
#define NMV_OVPN_TAG_DEV_TYPE "dev-type"
#define NMV_OVPN_TAG_FLOAT "float"
#define NMV_OVPN_TAG_FRAGMENT "fragment"
#define NMV_OVPN_TAG_GROUP "group"
#define NMV_OVPN_TAG_HTTP_PROXY "http-proxy"
#define NMV_OVPN_TAG_HTTP_PROXY_RETRY "http-proxy-retry"
#define NMV_OVPN_TAG_IFCONFIG "ifconfig"
#define NMV_OVPN_TAG_KEEPALIVE "keepalive"
#define NMV_OVPN_TAG_KEY_DIRECTION "key-direction"
#define NMV_OVPN_TAG_KEY "key"
#define NMV_OVPN_TAG_KEYSIZE "keysize"
#define NMV_OVPN_TAG_MAX_ROUTES "max-routes"
#define NMV_OVPN_TAG_MSSFIX "mssfix"
#define NMV_OVPN_TAG_MTU_DISC "mtu-disc"
#define NMV_OVPN_TAG_NOBIND "nobind"
#define NMV_OVPN_TAG_NS_CERT_TYPE "ns-cert-type"
#define NMV_OVPN_TAG_PERSIST_KEY "persist-key"
#define NMV_OVPN_TAG_PERSIST_TUN "persist-tun"
#define NMV_OVPN_TAG_PING_EXIT "ping-exit"
#define NMV_OVPN_TAG_PING "ping"
#define NMV_OVPN_TAG_PING_RESTART "ping-restart"
#define NMV_OVPN_TAG_PKCS12 "pkcs12"
#define NMV_OVPN_TAG_PORT "port"
#define NMV_OVPN_TAG_PROTO "proto"
#define NMV_OVPN_TAG_REMOTE_CERT_TLS "remote-cert-tls"
#define NMV_OVPN_TAG_REMOTE_RANDOM "remote-random"
#define NMV_OVPN_TAG_REMOTE "remote"
#define NMV_OVPN_TAG_RENEG_SEC "reneg-sec"
#define NMV_OVPN_TAG_ROUTE "route"
#define NMV_OVPN_TAG_RPORT "rport"
#define NMV_OVPN_TAG_SCRIPT_SECURITY "script-security"
#define NMV_OVPN_TAG_SECRET "secret"
#define NMV_OVPN_TAG_SOCKS_PROXY_RETRY "socks-proxy-retry"
#define NMV_OVPN_TAG_SOCKS_PROXY "socks-proxy"
#define NMV_OVPN_TAG_TLS_AUTH "tls-auth"
#define NMV_OVPN_TAG_TLS_CIPHER "tls-cipher"
#define NMV_OVPN_TAG_TLS_CLIENT "tls-client"
#define NMV_OVPN_TAG_TLS_CRYPT "tls-crypt"
#define NMV_OVPN_TAG_TLS_REMOTE "tls-remote"
#define NMV_OVPN_TAG_TOPOLOGY "topology"
#define NMV_OVPN_TAG_TUN_IPV6 "tun-ipv6"
#define NMV_OVPN_TAG_TUN_MTU "tun-mtu"
#define NMV_OVPN_TAG_USER "user"
#define NMV_OVPN_TAG_VERIFY_X509_NAME "verify-x509-name"
gboolean is_pkcs12 (const char *filepath);
gboolean is_encrypted (const char *filename);
#define NMOVPN_PROTCOL_TYPES \
"udp", \
"udp4", \
"udp6", \
"tcp", \
"tcp4", \
"tcp6", \
"tcp-client", \
"tcp4-client", \
"tcp6-client"
gssize nmovpn_remote_parse (const char *str,
char **out_buf,
const char **out_host,
const char **out_port,
const char **out_proto,
GError **error);
#endif /* UTILS_H */