| 1 |
/*
|
| 2 |
librc-plugin.c
|
| 3 |
Simple plugin handler
|
| 4 |
Copyright 2007 Gentoo Foundation
|
| 5 |
Released under the GPLv2
|
| 6 |
*/
|
| 7 |
|
| 8 |
#include <dlfcn.h>
|
| 9 |
#include <stdio.h>
|
| 10 |
#include <stdlib.h>
|
| 11 |
#include <string.h>
|
| 12 |
#include <unistd.h>
|
| 13 |
|
| 14 |
#include "einfo.h"
|
| 15 |
#include "rc.h"
|
| 16 |
#include "rc-misc.h"
|
| 17 |
#include "rc-plugin.h"
|
| 18 |
#include "strlist.h"
|
| 19 |
|
| 20 |
typedef struct plugin
|
| 21 |
{
|
| 22 |
char *name;
|
| 23 |
void *handle;
|
| 24 |
int (*hook) (rc_hook_t hook, const char *name);
|
| 25 |
struct plugin *next;
|
| 26 |
} plugin_t;
|
| 27 |
|
| 28 |
static plugin_t *plugins = NULL;
|
| 29 |
|
| 30 |
void rc_plugin_load (void)
|
| 31 |
{
|
| 32 |
char **files;
|
| 33 |
char *file;
|
| 34 |
int i;
|
| 35 |
plugin_t *plugin = plugins;
|
| 36 |
|
| 37 |
/* Ensure some sanity here */
|
| 38 |
rc_plugin_unload ();
|
| 39 |
|
| 40 |
if (! rc_exists (RC_PLUGINDIR))
|
| 41 |
return;
|
| 42 |
|
| 43 |
files = rc_ls_dir (NULL, RC_PLUGINDIR, 0);
|
| 44 |
STRLIST_FOREACH (files, file, i)
|
| 45 |
{
|
| 46 |
char *p = rc_strcatpaths (RC_PLUGINDIR, file, NULL);
|
| 47 |
void *h = dlopen (p, RTLD_LAZY);
|
| 48 |
char *func;
|
| 49 |
void *f;
|
| 50 |
int len;
|
| 51 |
|
| 52 |
if (! h)
|
| 53 |
{
|
| 54 |
eerror ("dlopen `%s': %s", p, dlerror ());
|
| 55 |
free (p);
|
| 56 |
continue;
|
| 57 |
}
|
| 58 |
|
| 59 |
func = file;
|
| 60 |
file = strsep (&func, ".");
|
| 61 |
len = strlen (file) + 7;
|
| 62 |
func = rc_xmalloc (sizeof (char *) * len);
|
| 63 |
snprintf (func, len, "_%s_hook", file);
|
| 64 |
|
| 65 |
f = dlsym (h, func);
|
| 66 |
if (! f)
|
| 67 |
{
|
| 68 |
eerror ("`%s' does not expose the symbol `%s'", p, func);
|
| 69 |
dlclose (h);
|
| 70 |
}
|
| 71 |
else
|
| 72 |
{
|
| 73 |
if (plugin)
|
| 74 |
{
|
| 75 |
plugin->next = rc_xmalloc (sizeof (plugin_t));
|
| 76 |
plugin = plugin->next;
|
| 77 |
}
|
| 78 |
else
|
| 79 |
plugin = plugins = rc_xmalloc (sizeof (plugin_t));
|
| 80 |
|
| 81 |
memset (plugin, 0, sizeof (plugin_t));
|
| 82 |
plugin->name = strdup (file);
|
| 83 |
plugin->handle = h;
|
| 84 |
plugin->hook = f;
|
| 85 |
}
|
| 86 |
|
| 87 |
free (func);
|
| 88 |
free (p);
|
| 89 |
}
|
| 90 |
|
| 91 |
rc_strlist_free (files);
|
| 92 |
}
|
| 93 |
|
| 94 |
void rc_plugin_run (rc_hook_t hook, const char *value)
|
| 95 |
{
|
| 96 |
plugin_t *plugin = plugins;
|
| 97 |
|
| 98 |
while (plugin)
|
| 99 |
{
|
| 100 |
if (plugin->hook)
|
| 101 |
plugin->hook (hook, value);
|
| 102 |
|
| 103 |
plugin = plugin->next;
|
| 104 |
}
|
| 105 |
}
|
| 106 |
|
| 107 |
void rc_plugin_unload (void)
|
| 108 |
{
|
| 109 |
plugin_t *plugin = plugins;
|
| 110 |
plugin_t *next;
|
| 111 |
|
| 112 |
while (plugin)
|
| 113 |
{
|
| 114 |
next = plugin->next;
|
| 115 |
dlclose (plugin->handle);
|
| 116 |
free (plugin->name);
|
| 117 |
free (plugin);
|
| 118 |
plugin = next;
|
| 119 |
}
|
| 120 |
plugins = NULL;
|
| 121 |
}
|