NetworkManager-VPN插件开发示例

Docker 阅读(20)

编译指令 :  
```bash
gcc myvpnplugin.c `pkg-config --cflags libnm --libs libnm`
```

插件示例源码 :  
```C
#include <stdio.h>

/* 使用libnm需要引入的头文件 */
#include <glib.h>
#include <NetworkManager.h>

/* 创建插件对象结构体 */
typedef struct {
    NMVpnServicePlugin parent;
} MyVpnPlugin;

/* 创建插件类的结构体 */
typedef struct {
    NMVpnServicePluginClass parent;
} MyVpnPluginClass;


/* 定义类型 */
G_DEFINE_TYPE (MyVpnPlugin, my_vpn_plugin, NM_TYPE_VPN_SERVICE_PLUGIN);

/* 这个函数是G_DEFINE_TYPE自动创建的 */
#define MY_VPN_PLUGIN_TYPE (my_vpn_plugin_get_type())


/* 销毁时调用 */
static void real_dispose (GObject *object)
{
    printf("invoke %s\n", __FUNCTION__);
}

/* 建立连接时调用 */
static gboolean real_connect (NMVpnServicePlugin *plugin, NMConnection *connection, GError **error)
{
    printf("invoke %s\n", __FUNCTION__);
}

/* 需要密钥时调用 */
static gboolean real_need_secrets (NMVpnServicePlugin *plugin, NMConnection *connection, const char **setting_name, GError **error)
{
    printf("invoke %s\n", __FUNCTION__);
}

/* 断开连接时调用 */
static gboolean real_disconnect (NMVpnServicePlugin *plugin, GError **err)
{
    printf("invoke %s\n", __FUNCTION__);
}

/* 对象的初始化函数,这个函数是G_DEFINE_TYPE自动绑定的,必须照此命名 */
static void my_vpn_plugin_init (MyVpnPlugin* plugin)
{

}

/* 类的初始化函数,这个函数是G_DEFINE_TYPE自动绑定的,必须照此命名 */
static void my_vpn_plugin_class_init (MyVpnPluginClass* plugin_class)
{
    GObjectClass *object_class = G_OBJECT_CLASS (plugin_class);
    NMVpnServicePluginClass *parent_class = NM_VPN_SERVICE_PLUGIN_CLASS (plugin_class);

    /* 绑定方法 */
    object_class->dispose = real_dispose;
    parent_class->connect    = real_connect;
    parent_class->need_secrets = real_need_secrets;
    parent_class->disconnect = real_disconnect;
}


/*lobal*/
static struct {
    gboolean debug;
    int log_level;
} gl;

/* 主程序 */
int main(int argc, char* argv[])
{
    /* 创建插件 */
    const char* bus_name = "org.hbc.demo";
    GError *error = NULL;
    MyVpnPlugin* plugin = g_initable_new (MY_VPN_PLUGIN_TYPE, NULL, &error,
                             NM_VPN_SERVICE_PLUGIN_DBUS_SERVICE_NAME, bus_name,
                             NM_VPN_SERVICE_PLUGIN_DBUS_WATCH_PEER, !gl.debug,
                             NULL);

    /* 创建mainloop并运行 */
    GMainLoop* main_loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (main_loop);

    /* 解除引用,释放内存 */
    g_main_loop_unref (main_loop);
    g_object_unref (plugin);

    return 0;
}
```