Merge branch 'ag/apache'
authorFlorian Forster <octo@leeloo.lan.home.verplant.org>
Fri, 1 May 2009 13:07:04 +0000 (15:07 +0200)
committerFlorian Forster <octo@leeloo.lan.home.verplant.org>
Fri, 1 May 2009 13:07:04 +0000 (15:07 +0200)
21 files changed:
configure.in
contrib/php-collection/browser.js
contrib/php-collection/definitions.php
contrib/php-collection/functions.php
contrib/php-collection/graph.php
contrib/php-collection/index.php
src/Makefile.am
src/collectd.conf.pod
src/filter_chain.c
src/irq.c
src/libcollectdclient/client.c
src/meta_data.c
src/mysql.c
src/network.c
src/target_notification.c
src/target_replace.c
src/target_set.c
src/types.db
src/utils_fbhash.c [new file with mode: 0644]
src/utils_fbhash.h [new file with mode: 0644]
src/utils_match.h

index 7c4e417..c585390 100644 (file)
@@ -1341,6 +1341,11 @@ fi
 CPPFLAGS="$SAVE_CPPFLAGS"
 LDFLAGS="$SAVE_LDFLAGS"
 
+if test "x$with_libgcrypt" = "xyes"
+then
+       AC_DEFINE(HAVE_LIBGCRYPT, 1, [Define to 1 if you have the gcrypt library (-lgcrypt).])
+fi
+
 AC_SUBST(GCRYPT_CPPFLAGS)
 AC_SUBST(GCRYPT_LDFLAGS)
 AC_SUBST(GCRYPT_LIBS)
@@ -3613,6 +3618,7 @@ Configuration:
     libcurl . . . . . . . $with_libcurl
     libdbi  . . . . . . . $with_libdbi
     libesmtp  . . . . . . $with_libesmtp
+    libgcrypt . . . . . . $with_libgcrypt
     libiokit  . . . . . . $with_libiokit
     libiptc . . . . . . . $with_libiptc
     libjvm  . . . . . . . $with_java
index a343cba..4ddc424 100644 (file)
@@ -35,6 +35,7 @@ function toggleDiv(divID) {
                        label.removeChild(label.childNodes[--childCnt]);
                label.appendChild(document.createTextNode(label_txt));
        }
+       GraphPositionToolbox(null);
 }
 
 var req = null;
@@ -110,9 +111,22 @@ function refillSelect(options, select) {
                        newOption.value = options[i].firstChild ? options[i].firstChild.data : '';
                        if (keepSelection && newOption.value == oldValue)
                                newOption.setAttribute('selected', 'selected');
-                       if (keepSelection && optCnt == 1 && newOption.value == '@') {
+                       if (newOption.value[0] == '@') {
                                newOption.setAttribute('style', 'font-style: italic');
-                               newOption.appendChild(document.createTextNode('Meta graph'));
+                               if (newOption.value == '@' || newOption.value == '@merge')
+                                       newOption.appendChild(document.createTextNode('Meta graph'));
+                               else if (newOption.value == '@all')
+                                       newOption.appendChild(document.createTextNode('All entries'));
+                               else if (newOption.value == '@merge_sum')
+                                       newOption.appendChild(document.createTextNode('Meta summed graph'));
+                               else if (newOption.value == '@merge_avg')
+                                       newOption.appendChild(document.createTextNode('Meta averaged graph'));
+                               else if (newOption.value == '@merge_stack')
+                                       newOption.appendChild(document.createTextNode('Meta stacked graph'));
+                               else if (newOption.value == '@merge_line')
+                                       newOption.appendChild(document.createTextNode('Meta lines graph'));
+                               else
+                                       newOption.appendChild(document.createTextNode(newOption.value));
                        } else
                                newOption.appendChild(document.createTextNode(newOption.value));
                        select.appendChild(newOption);
@@ -284,8 +298,25 @@ function GraphAppend() {
        var time_list   = document.getElementById('timespan');
        var timespan    = time_list.selectedIndex >= 0 ? time_list.options[time_list.selectedIndex].value : '';
        var tinyLegend  = document.getElementById('tinylegend').checked;
-       var logarithmic = document.getElementById('logarithmic').checked
-       GraphDoAppend(host, plugin, pinst, type, tinst, timespan, tinyLegend, logarithmic);
+       var logarithmic = document.getElementById('logarithmic').checked;
+       if (host[0] == '@' || plugin[0] == '@' || pinst[0] == '@' || type[0] == '@' || (tinst[0] == '@' && tinst.substr(0, 5) != '@merge')) {
+               var query = 'action=list_graphs&host='+encodeURIComponent(host)+'&plugin='+encodeURIComponent(plugin)+'&plugin_instance='+encodeURIComponent(pinst);
+               query = query+'&type='+encodeURIComponent(type)+'&type_instance='+encodeURIComponent(tinst)+'&timespan='+encodeURIComponent(timespan);
+               query = query+(logarithmic ? '&logarithmic=1' : '')+(tinyLegend ? '&tinylegend=1' : '');
+               loadXMLDoc(dhtml_url, query);
+       } else
+               GraphDoAppend(host, plugin, pinst, type, tinst, timespan, tinyLegend, logarithmic);
+}
+
+function ListOfGraph(response) {
+       var graphs = response ? response.getElementsByTagName('graph') : null;
+       if (graphs && graphs.length > 0) {
+               for (i = 0; i < graphs.length; i++)
+                       GraphDoAppend(graphs[i].getAttribute('host'), graphs[i].getAttribute('plugin'), graphs[i].getAttribute('plugin_instance'),
+                                     graphs[i].getAttribute('type'), graphs[i].getAttribute('type_instance'), graphs[i].getAttribute('timespan'),
+                                     graphs[i].getAttribute('tinyLegend') == '1', graphs[i].getAttribute('logarithmic') == '1');
+       } else
+               alert('No graph found for adding');
 }
 
 function GraphDoAppend(host, plugin, pinst, type, tinst, timespan, tinyLegend, logarithmic) {
@@ -319,58 +350,12 @@ function GraphDoAppend(host, plugin, pinst, type, tinst, timespan, tinyLegend, l
                newGraph.setAttribute('class', 'graph');
                newGraph.setAttribute('id', graph_id);
                // Graph cell + graph
-               newDiv = document.createElement('div');
-               newDiv.setAttribute('class', 'graph_img');
                newImg = document.createElement('img');
                newImg.setAttribute('src', graph_src);
                newImg.setAttribute('alt', graph_alt);
                newImg.setAttribute('title', graph_title);
-               newDiv.appendChild(newImg);
-               newGraph.appendChild(newDiv);
-               // Graph tools
-               newDiv = document.createElement('div');
-               newDiv.setAttribute('class', 'graph_opts');
-               // - move up
-               newImg = document.createElement('img');
-               newImg.setAttribute('src', 'move-up.png');
-               newImg.setAttribute('alt', 'UP');
-               newImg.setAttribute('title', 'Move graph up');
-               newA = document.createElement('a');
-               newA.setAttribute('href', 'javascript:GraphMoveUp("'+graph_id+'")');
-               newA.appendChild(newImg);
-               newDiv.appendChild(newA);
-               newDiv.appendChild(document.createElement('br'));
-               // - refresh
-               newImg = document.createElement('img');
-               newImg.setAttribute('src', 'refresh.png');
-               newImg.setAttribute('alt', 'R');
-               newImg.setAttribute('title', 'Refresh graph');
-               newA = document.createElement('a');
-               newA.setAttribute('href', 'javascript:GraphRefresh("'+graph_id+'")');
-               newA.appendChild(newImg);
-               newDiv.appendChild(newA);
-               newDiv.appendChild(document.createElement('br'));
-               // - remove
-               newImg = document.createElement('img');
-               newImg.setAttribute('src', 'delete.png');
-               newImg.setAttribute('alt', 'RM');
-               newImg.setAttribute('title', 'Remove graph');
-               newA = document.createElement('a');
-               newA.setAttribute('href', 'javascript:GraphRemove("'+graph_id+'")');
-               newA.appendChild(newImg);
-               newDiv.appendChild(newA);
-               newDiv.appendChild(document.createElement('br'));
-               // - move down
-               newImg = document.createElement('img');
-               newImg.setAttribute('src', 'move-down.png');
-               newImg.setAttribute('alt', 'DN');
-               newImg.setAttribute('title', 'Move graph down');
-               newA = document.createElement('a');
-               newA.setAttribute('href', 'javascript:GraphMoveDown("'+graph_id+'")');
-               newA.appendChild(newImg);
-               newDiv.appendChild(newA);
-               newGraph.appendChild(newDiv);
-
+               newImg.setAttribute('onclick', 'GraphToggleTools("'+graph_id+'")');
+               newGraph.appendChild(newImg);
                graphs.appendChild(newGraph);
        }
        document.getElementById('nograph').style.display = 'none';
@@ -389,32 +374,159 @@ function GraphDropAll() {
        RefreshButtons();
 }
 
+function GraphToggleTools(graph) {
+       var graphId = document.getElementById('ge_graphid').value;
+       var ref_img = null;
+       if (graphId == graph || graph == '') {
+               ref_img = null;
+       } else {
+               var graphDiv = document.getElementById(graph);
+               var imgs     = graphDiv ? graphDiv.getElementsByTagName('img') : null;
+               var imgCnt   = imgs ? imgs.length : 0;
+               while (imgCnt > 0)
+                       if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph')
+                               ref_img = imgs[imgCnt];
+       }
+       if (ref_img) {
+               var ts_sel  =  document.getElementById('ge_timespan');
+               var src_url = ref_img.src;
+               var ge      = document.getElementById('ge');
+               // Fix field values
+               var ts = src_url.match(/&timespan=[^&]*/);
+               ts = ts ? ts[0].substr(10) : '';
+               document.getElementById('ge_graphid').value = graph;
+               document.getElementById('ge_tinylegend').checked = src_url.match(/&tinylegend=1/);
+               document.getElementById('ge_logarithmic').checked = src_url.match(/&logarithmic=1/);
+               for (i = 0; i < ts_sel.options.length; i++)
+                       if (ts_sel.options[i].value == ts) {
+                               ts_sel.selectedIndex = i;
+                               break;
+                       }
+               // show tools box and position it properly
+               ge.style.display = 'table';
+               GraphPositionToolbox(ref_img);
+       } else {
+               // hide tools box
+               document.getElementById('ge').style.display = 'none';
+               document.getElementById('ge_graphid').value = '';
+       }
+}
+
+function GraphPositionToolbox(ref_img) {
+       var ge      = document.getElementById('ge');
+       if (ge.style.display != 'none') {
+               var wl = 0; var wt = 0;
+               var x = ref_img;
+               if (ref_img == null) {
+                       var graphDiv = document.getElementById(document.getElementById('ge_graphid').value);
+                       var imgs     = graphDiv ? graphDiv.getElementsByTagName('img') : null;
+                       var imgCnt   = imgs ? imgs.length : 0;
+                       while (imgCnt > 0)
+                               if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph')
+                                       ref_img = imgs[imgCnt];
+
+                       if (ref_img == null) {
+                               document.getElementById('ge_graphid').value = '';
+                               ge.style.display = 'none';
+                               return;
+                       } else
+                               x = ref_img;
+               }
+               while (x != null) {
+                       wl += x.offsetLeft;
+                       wt += x.offsetTop;
+                       x = x.offsetParent;
+               }
+               ge.style.left    = (wl + (ref_img.offsetWidth - ge.offsetWidth) / 2)+'px';
+               ge.style.top     = (wt + (ref_img.offsetHeight - ge.offsetHeight) / 2)+'px';
+       }
+}
+
+function GraphRefreshAll() {
+       var imgs   = document.getElementById('graphs').getElementsByTagName('img');
+       var imgCnt = imgs.length;
+       var now    = new Date();
+       var newTS  = '&ts='+now.getTime();
+       while (imgCnt > 0)
+               if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph') {
+                       var oldSrc = imgs[imgCnt].src;
+                       var newSrc = oldSrc.replace(/&ts=[0-9]+/, newTS);
+                       if (newSrc == oldSrc)
+                               newSrc = newSrc + newTS;
+                       imgs[imgCnt].setAttribute('src', newSrc);
+               }
+}
+
 function GraphRefresh(graph) {
+       var graphElement = null;
        if (graph == null) {
-               var imgs   = document.getElementById('graphs').getElementsByTagName('img');
+               var graphId = document.getElementById('ge_graphid').value;
+               if (graphId != '')
+                       graphElement = document.getElementById(graphId);
+       } else 
+               graphElement = document.getElementById(graph);
+       if (graphElement != null) {
+               var imgs = graphElement.getElementsByTagName('img');
                var imgCnt = imgs.length;
-               var now    = new Date();
-               var newTS  = '&ts='+now.getTime();
                while (imgCnt > 0)
-                       if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph_img') {
+                       if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph') {
+                               var now    = new Date();
+                               var newTS  = '&ts='+now.getTime();
                                var oldSrc = imgs[imgCnt].src;
                                var newSrc = oldSrc.replace(/&ts=[0-9]+/, newTS);
                                if (newSrc == oldSrc)
-                                       newSrc = newSrc + newTS;
+                                       newSrc = newSrc+newTS;
                                imgs[imgCnt].setAttribute('src', newSrc);
+                               break;
                        }
-       } else if (document.getElementById(graph)) {
-               var imgs = document.getElementById(graph).getElementsByTagName('img');
+       }
+}
+
+function GraphAdjust(graph) {
+       var graphId = graph == null ? document.getElementById('ge_graphid').value : graph;
+       var graphElement = document.getElementById(graphId);
+       if (graphElement != null) {
+               var time_list   = document.getElementById('ge_timespan');
+               var timespan    = time_list.selectedIndex >= 0 ? time_list.options[time_list.selectedIndex].value : '';
+               var tinyLegend  = document.getElementById('ge_tinylegend').checked;
+               var logarithmic = document.getElementById('ge_logarithmic').checked
+               var imgs = graphElement.getElementsByTagName('img');
                var imgCnt = imgs.length;
+               var ref_img     = null;
                while (imgCnt > 0)
-                       if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph_img') {
+                       if (imgs[--imgCnt].parentNode.getAttribute('class') == 'graph') {
                                var now    = new Date();
                                var newTS  = '&ts='+now.getTime();
                                var oldSrc = imgs[imgCnt].src;
-                               var newSrc = oldSrc.replace(/&ts=[0-9]+/, newTS);
+                               var newSrc = oldSrc.replace(/&ts=[^&]*/, newTS);
                                if (newSrc == oldSrc)
                                        newSrc = newSrc+newTS;
+                               newSrc     = newSrc.replace(/&logarithmic=[^&]*/, '');
+                               if (logarithmic)
+                                       newSrc += '&logarithmic=1';
+                               newSrc     = newSrc.replace(/&tinylegend=[^&]*/, '');
+                               if (tinyLegend)
+                                       newSrc += '&tinylegend=1';
+                               newSrc     = newSrc.replace(/&timespan=[^&]*/, '');
+                               if (timespan)
+                                       newSrc += '&timespan='+encodeURIComponent(timespan);
                                imgs[imgCnt].setAttribute('src', newSrc);
+
+                               var myList = Array();
+                               for (i = 0; i < graphList.length; i++)
+                                       if (graphList[i].substring(0, graphId.length) == graphId && graphList[i].charAt(graphId.length) == ' ') {
+                                               newSrc = graphList[i];
+                                               newSrc = newSrc.replace(/&logarithmic=[^&]*/, '');
+                                               newSrc = newSrc.replace(/&tinylegend=[^&]*/, '');
+                                               newSrc = newSrc.replace(/&timespan=[^&]*/, '');
+                                               newSrc = newSrc+(logarithmic ? '&logarithmic=1' : '')+(tinyLegend ? '&tinylegend=1' : '')+'&timespan='+encodeURIComponent(timespan);
+                                               myList.push(newSrc);
+                                               continue;
+                                       } else
+                                               myList.push(graphList[i]);
+                               graphList = myList;
+                               window.setTimeout("GraphPositionToolbox(null)", 10);
+                               // GraphPositionToolbox(imgs[imgCnt]);
                                break;
                        }
        }
@@ -422,15 +534,18 @@ function GraphRefresh(graph) {
 
 function GraphRemove(graph) {
        var graphs = document.getElementById('graphs');
-       if (document.getElementById(graph)) {
-               graphs.removeChild(document.getElementById(graph));
+       var graphId = graph == null ? document.getElementById('ge_graphid').value : graph;
+       var graphElement = document.getElementById(graphId);
+       if (graphElement) {
+               GraphToggleTools('');
+               graphs.removeChild(graphElement);
                RefreshButtons();
                if (graphs.getElementsByTagName('div').length == 1)
                        document.getElementById('nograph').style.display = 'block';
 
                var myList = Array();
                for (i = 0; i < graphList.length; i++)
-                       if (graphList[i].substring(0, graph.length) == graph && graphList[i].charAt(graph.length) == ' ')
+                       if (graphList[i].substring(0, graphId.length) == graphId && graphList[i].charAt(graphId.length) == ' ')
                                continue;
                        else
                                myList.push(graphList[i]);
@@ -440,13 +555,14 @@ function GraphRemove(graph) {
 
 function GraphMoveUp(graph) {
        var graphs    = document.getElementById('graphs');
+       var graphId   = graph == null ? document.getElementById('ge_graphid').value : graph;
        var childCnt  = graphs.childNodes.length;
        var prevGraph = null;
        for (i = 0; i < childCnt; i++)
                if (graphs.childNodes[i].nodeName == 'div' || graphs.childNodes[i].nodeName == 'DIV') {
                        if (graphs.childNodes[i].id == 'nograph') {
                                // Skip
-                       } else if (graphs.childNodes[i].id == graph) {
+                       } else if (graphs.childNodes[i].id == graphId) {
                                var myGraph = graphs.childNodes[i];
                                if (prevGraph) {
                                        graphs.removeChild(myGraph);
@@ -457,7 +573,7 @@ function GraphMoveUp(graph) {
                                prevGraph = graphs.childNodes[i];
                }
        for (i = 0; i < graphList.length; i++)
-               if (graphList[i].substring(0, graph.length) == graph && graphList[i].charAt(graph.length) == ' ') {
+               if (graphList[i].substring(0, graphId.length) == graphId && graphList[i].charAt(graphId.length) == ' ') {
                        if (i > 0) {
                                var tmp = graphList[i-1];
                                graphList[i-1] = graphList[i];
@@ -465,10 +581,12 @@ function GraphMoveUp(graph) {
                        }
                        break;
                }
+       GraphPositionToolbox(null);
 }
 
 function GraphMoveDown(graph) {
        var graphs    = document.getElementById('graphs');
+       var graphId   = graph == null ? document.getElementById('ge_graphid').value : graph;
        var childCnt  = graphs.childNodes.length;
        var nextGraph = null;
        var myGraph   = null;
@@ -476,7 +594,7 @@ function GraphMoveDown(graph) {
                if (graphs.childNodes[i].nodeName == 'div' || graphs.childNodes[i].nodeName == 'DIV') {
                        if (graphs.childNodes[i].id == 'nograph') {
                                // Skip
-                       } else if (graphs.childNodes[i].id == graph) {
+                       } else if (graphs.childNodes[i].id == graphId) {
                                myGraph = graphs.childNodes[i];
                        } else if (myGraph) {
                                nextGraph = graphs.childNodes[i];
@@ -486,7 +604,7 @@ function GraphMoveDown(graph) {
                        }
                }
        for (i = 0; i < graphList.length; i++)
-               if (graphList[i].substring(0, graph.length) == graph && graphList[i].charAt(graph.length) == ' ') {
+               if (graphList[i].substring(0, graphId.length) == graphId && graphList[i].charAt(graphId.length) == ' ') {
                        if (i+1 < graphList.length) {
                                var tmp = graphList[i+1];
                                graphList[i+1] = graphList[i];
@@ -494,6 +612,7 @@ function GraphMoveDown(graph) {
                        }
                        break;
                }
+       GraphPositionToolbox(null);
 }
 
 function GraphListFromCookie(lname) {
index a0f3818..c84aabe 100644 (file)
@@ -1590,6 +1590,7 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) {
        $MetaGraphDefs['tcp_connections']   = 'meta_graph_tcp_connections';
        $MetaGraphDefs['dns_opcode']        = 'meta_graph_dns_event';
        $MetaGraphDefs['dns_qtype']         = 'meta_graph_dns_event';
+       $MetaGraphDefs['dns_qtype_cached']  = 'meta_graph_dns_event';
        $MetaGraphDefs['dns_rcode']         = 'meta_graph_dns_event';
        $MetaGraphDefs['dns_request']       = 'meta_graph_dns_event';
        $MetaGraphDefs['dns_resolver']      = 'meta_graph_dns_event';
@@ -1757,7 +1758,10 @@ function meta_graph_memory($host, $plugin, $plugin_instance, $type, $type_instan
                $sources[] = array('name'=>$inst, 'file'=>$file);
        }
 
-       return collectd_draw_meta_stack($opts, $sources);
+       if ($plugin == 'bind')
+               return collectd_draw_meta_line($opts, $sources);
+       else
+               return collectd_draw_meta_stack($opts, $sources);
 }
 
 function meta_graph_vs_threads($host, $plugin, $plugin_instance, $type, $type_instances, $opts = array()) {
index f555751..fa2badc 100644 (file)
@@ -61,23 +61,173 @@ function collectd_compare_host($a, $b) {
        return 0;
 }
 
-/**
- * Fetch list of hosts found in collectd's datadirs.
- * @return Sorted list of hosts (sorted by label from rigth to left)
- */
-function collectd_list_hosts() {
+function collectd_walk(&$options) {
        global $config;
 
-       $hosts = array();
        foreach($config['datadirs'] as $datadir)
-               if ($d = @opendir($datadir)) {
-                       while (($dent = readdir($d)) !== false)
-                               if ($dent != '.' && $dent != '..' && is_dir($datadir.'/'.$dent) && preg_match(REGEXP_HOST, $dent))
-                                       $hosts[] = $dent;
-                       closedir($d);
+               if ($dh = @opendir($datadir)) {
+                       while (($hdent = readdir($dh)) !== false) {
+                               if ($hdent == '.' || $hdent == '..' || !is_dir($datadir.'/'.$hdent))
+                                       continue;
+                               if (!preg_match(REGEXP_HOST, $hdent))
+                                       continue;
+                               if (isset($options['cb_host']) && ($options['cb_host'] === false || !$options['cb_host']($options, $hdent)))
+                                       continue;
+
+                               if ($dp = @opendir($datadir.'/'.$hdent)) {
+                                       while (($pdent = readdir($dp)) !== false) {
+                                               if ($pdent == '.' || $pdent == '..' || !is_dir($datadir.'/'.$hdent.'/'.$pdent))
+                                                       continue;
+                                               if ($i = strpos($pdent, '-')) {
+                                                       $plugin = substr($pdent, 0, $i);
+                                                       $pinst  = substr($pdent, $i+1);
+                                               } else {
+                                                       $plugin = $pdent;
+                                                       $pinst  = '';
+                                               }
+                                               if (isset($options['cb_plugin']) && ($options['cb_plugin'] === false || !$options['cb_plugin']($options, $hdent, $plugin)))
+                                                       continue;
+                                               if (isset($options['cb_pinst']) && ($options['cb_pinst'] === false || !$options['cb_pinst']($options, $hdent, $plugin, $pinst)))
+                                                       continue;
+
+                                               if ($dt = @opendir($datadir.'/'.$hdent.'/'.$pdent)) {
+                                                       while (($tdent = readdir($dt)) !== false) {
+                                                               if ($tdent == '.' || $tdent == '..' || !is_file($datadir.'/'.$hdent.'/'.$pdent.'/'.$tdent))
+                                                                       continue;
+                                                               if (substr($tdent, strlen($tdent)-4) != '.rrd')
+                                                                       continue;
+                                                               $tdent = substr($tdent, 0, strlen($tdent)-4);
+                                                               if ($i = strpos($tdent, '-')) {
+                                                                       $type  = substr($tdent, 0, $i);
+                                                                       $tinst = substr($tdent, $i+1);
+                                                               } else {
+                                                                       $type  = $tdent;
+                                                                       $tinst = '';
+                                                               }
+                                                               if (isset($options['cb_type']) && ($options['cb_type'] === false || !$options['cb_type']($options, $hdent, $plugin, $pinst, $type)))
+                                                                       continue;
+                                                               if (isset($options['cb_tinst']) && ($options['cb_tinst'] === false || !$options['cb_tinst']($options, $hdent, $plugin, $pinst, $type, $tinst)))
+                                                                       continue;
+                                                       }
+                                                       closedir($dt);
+                                               }
+                                       }
+                                       closedir($dp);
+                               }
+                       }
+                       closedir($dh);
                } else
                        error_log('Failed to open datadir: '.$datadir);
-       $hosts = array_unique($hosts);
+               return true;
+}
+
+function _collectd_list_cb_host(&$options, $host) {
+       if ($options['cb_plugin'] === false) {
+               $options['result'][] = $host;
+               return false;
+       } else if (isset($options['filter_host'])) {
+               if ($options['filter_host'] == '@all') {
+                       return true; // We take anything
+               } else if (substr($options['filter_host'], 0, 2) == '@.') {
+                       if ($host == substr($options['filter_host'], 2) || substr($host, 0, 1-strlen($options['filter_host'])) == substr($options['filter_host'], 1))
+                               return true; // Host part of domain
+                       else
+                               return false;
+               } else if ($options['filter_host'] == $host) {
+                       return true;
+               } else
+                       return false;
+       } else
+               return true;
+}
+
+function _collectd_list_cb_plugin(&$options, $host, $plugin) {
+       if ($options['cb_pinst'] === false) {
+               $options['result'][] = $plugin;
+               return false;
+       } else if (isset($options['filter_plugin'])) {
+               if ($options['filter_plugin'] == '@all')
+                       return true;
+               else if ($options['filter_plugin'] == $plugin)
+                       return true;
+               else
+                       return false;
+       } else
+               return true;
+}
+
+function _collectd_list_cb_pinst(&$options, $host, $plugin, $pinst) {
+       if ($options['cb_type'] === false) {
+               $options['result'][] = $pinst;
+               return false;
+       } else if (isset($options['filter_pinst'])) {
+               if ($options['filter_pinst'] == '@all')
+                       return true;
+               else if (strncmp($options['filter_pinst'], '@merge_', 7) == 0)
+                       return true;
+               else if ($options['filter_pinst'] == $pinst)
+                       return true;
+               else
+                       return false;
+       } else
+               return true;
+}
+
+function _collectd_list_cb_type(&$options, $host, $plugin, $pinst, $type) {
+       if ($options['cb_tinst'] === false) {
+               $options['result'][] = $type;
+               return false;
+       } else if (isset($options['filter_type'])) {
+               if ($options['filter_type'] == '@all')
+                       return true;
+               else if ($options['filter_type'] == $type)
+                       return true;
+               else
+                       return false;
+       } else
+               return true;
+}
+
+function _collectd_list_cb_tinst(&$options, $host, $plugin, $pinst, $type, $tinst) {
+       $options['result'][] = $tinst;
+       return false;
+}
+
+function _collectd_list_cb_graph(&$options, $host, $plugin, $pinst, $type, $tinst) {
+       if (isset($options['filter_tinst'])) {
+               if ($options['filter_tinst'] == '@all') {
+               } else if ($options['filter_tinst'] == $tinst) {
+               } else if (strncmp($options['filter_tinst'], '@merge', 6) == 0) {
+                       // Need to exclude @merge with non-existent meta graph
+               } else
+                       return false;
+       }
+       if (isset($options['filter_pinst']) && strncmp($options['filter_pinst'], '@merge', 6) == 0)
+               $pinst = $options['filter_pinst'];
+       if (isset($options['filter_tinst']) && strncmp($options['filter_tinst'], '@merge', 6) == 0)
+               $tinst = $options['filter_tinst'];
+       $ident = collectd_identifier($host, $plugin, $pinst, $type, $tinst);
+       if (!in_array($ident, $options['ridentifiers'])) {
+               $options['ridentifiers'][] = $ident;
+               $options['result'][] = array('host'=>$host, 'plugin'=>$plugin, 'pinst'=>$pinst, 'type'=>$type, 'tinst'=>$tinst);
+       }
+}
+
+/**
+ * Fetch list of hosts found in collectd's datadirs.
+ * @return Sorted list of hosts (sorted by label from rigth to left)
+ */
+function collectd_list_hosts() {
+       $options = array(
+               'result' => array(),
+               'cb_host' => '_collectd_list_cb_host',
+               'cb_plugin' => false,
+               'cb_pinst' => false,
+               'cb_type' => false,
+               'cb_tinst' => false
+       );
+       collectd_walk($options);
+       $hosts = array_unique($options['result']);
        usort($hosts, 'collectd_compare_host');
        return $hosts;
 }
@@ -87,123 +237,66 @@ function collectd_list_hosts() {
  * @arg_host Name of host for which to return plugins
  * @return Sorted list of plugins (sorted alphabetically)
  */
-function collectd_list_plugins($arg_host) {
-       global $config;
-
-       $plugins = array();
-       foreach ($config['datadirs'] as $datadir)
-               if (preg_match(REGEXP_HOST, $arg_host) && ($d = @opendir($datadir.'/'.$arg_host))) {
-                       while (($dent = readdir($d)) !== false)
-                               if ($dent != '.' && $dent != '..' && is_dir($datadir.'/'.$arg_host.'/'.$dent)) {
-                                       if ($i = strpos($dent, '-'))
-                                               $plugins[] = substr($dent, 0, $i);
-                                       else
-                                               $plugins[] = $dent;
-                               }
-                       closedir($d);
-               }
-       $plugins = array_unique($plugins);
+function collectd_list_plugins($arg_host, $arg_plugin = null) {
+       $options = array(
+               'result' => array(),
+               'cb_host' => '_collectd_list_cb_host',
+               'cb_plugin' => '_collectd_list_cb_plugin',
+               'cb_pinst' => is_null($arg_plugin) ? false : '_collectd_list_cb_pinst',
+               'cb_type' => false,
+               'cb_tinst' => false,
+               'filter_host' => $arg_host,
+               'filter_plugin' => $arg_plugin
+       );
+       collectd_walk($options);
+       $plugins = array_unique($options['result']);
        sort($plugins);
        return $plugins;
 }
 
 /**
- * Fetch list of plugin instances found in collectd's datadirs for given host+plugin
- * @arg_host Name of host
- * @arg_plugin Name of plugin
- * @return Sorted list of plugin instances (sorted alphabetically)
- */
-function collectd_list_pinsts($arg_host, $arg_plugin) {
-       global $config;
-
-       $pinsts = array();
-       foreach ($config['datadirs'] as $datadir)
-               if (preg_match(REGEXP_HOST, $arg_host) && ($d = opendir($datadir.'/'.$arg_host))) {
-                       while (($dent = readdir($d)) !== false)
-                               if ($dent != '.' && $dent != '..' && is_dir($datadir.'/'.$arg_host.'/'.$dent)) {
-                                       if ($i = strpos($dent, '-')) {
-                                               $plugin = substr($dent, 0, $i);
-                                               $pinst  = substr($dent, $i+1);
-                                       } else {
-                                               $plugin = $dent;
-                                               $pinst  = '';
-                                       }
-                                       if ($plugin == $arg_plugin)
-                                               $pinsts[] = $pinst;
-                               }
-                       closedir($d);
-               }
-       $pinsts = array_unique($pinsts);
-       sort($pinsts);
-       return $pinsts;
-}
-
-/**
  * Fetch list of types found in collectd's datadirs for given host+plugin+instance
  * @arg_host Name of host
  * @arg_plugin Name of plugin
  * @arg_pinst Plugin instance
  * @return Sorted list of types (sorted alphabetically)
  */
-function collectd_list_types($arg_host, $arg_plugin, $arg_pinst) {
-       global $config;
-
-       $types = array();
-       $my_plugin = $arg_plugin . (strlen($arg_pinst) ? '-'.$arg_pinst : '');
-       if (!preg_match(REGEXP_PLUGIN, $my_plugin))
-               return $types;
-       foreach ($config['datadirs'] as $datadir)
-               if (preg_match(REGEXP_HOST, $arg_host) && ($d = @opendir($datadir.'/'.$arg_host.'/'.$my_plugin))) {
-                       while (($dent = readdir($d)) !== false)
-                               if ($dent != '.' && $dent != '..' && is_file($datadir.'/'.$arg_host.'/'.$my_plugin.'/'.$dent) && substr($dent, strlen($dent)-4) == '.rrd') {
-                                       $dent = substr($dent, 0, strlen($dent)-4);
-                                       if ($i = strpos($dent, '-'))
-                                               $types[] = substr($dent, 0, $i);
-                                       else
-                                               $types[] = $dent;
-                               }
-                       closedir($d);
-               }
-       $types = array_unique($types);
+function collectd_list_types($arg_host, $arg_plugin, $arg_pinst, $arg_type = null) {
+       $options = array(
+               'result' => array(),
+               'cb_host' => '_collectd_list_cb_host',
+               'cb_plugin' => '_collectd_list_cb_plugin',
+               'cb_pinst' => '_collectd_list_cb_pinst',
+               'cb_type' => '_collectd_list_cb_type',
+               'cb_tinst' => is_null($arg_type) ? false : '_collectd_list_cb_tinst',
+               'filter_host' => $arg_host,
+               'filter_plugin' => $arg_plugin,
+               'filter_pinst' => $arg_pinst,
+               'filter_type' => $arg_type
+       );
+       collectd_walk($options);
+       $types = array_unique($options['result']);
        sort($types);
        return $types;
 }
 
-/**
- * Fetch list of type instances found in collectd's datadirs for given host+plugin+instance+type
- * @arg_host Name of host
- * @arg_plugin Name of plugin
- * @arg_pinst Plugin instance
- * @arg_type Type
- * @return Sorted list of type instances (sorted alphabetically)
- */
-function collectd_list_tinsts($arg_host, $arg_plugin, $arg_pinst, $arg_type) {
-       global $config;
-
-       $tinsts = array();
-       $my_plugin = $arg_plugin . (strlen($arg_pinst) ? '-'.$arg_pinst : '');
-       if (!preg_match(REGEXP_PLUGIN, $my_plugin))
-               return $types;
-       foreach ($config['datadirs'] as $datadir)
-               if (preg_match(REGEXP_HOST, $arg_host) && ($d = @opendir($datadir.'/'.$arg_host.'/'.$my_plugin))) {
-                       while (($dent = readdir($d)) !== false)
-                               if ($dent != '.' && $dent != '..' && is_file($datadir.'/'.$arg_host.'/'.$my_plugin.'/'.$dent) && substr($dent, strlen($dent)-4) == '.rrd') {
-                                       $dent = substr($dent, 0, strlen($dent)-4);
-                                       if ($i = strpos($dent, '-')) {
-                                               $type  = substr($dent, 0, $i);
-                                               $tinst = substr($dent, $i+1);
-                                       } else {
-                                               $type  = $dent;
-                                               $tinst = '';
-                                       }
-                                       if ($type == $arg_type)
-                                               $tinsts[] = $tinst;
-                               }
-                       closedir($d);
-               }
-       $tinsts = array_unique($tinsts);
-       sort($tinsts);
-       return $tinsts;
+function collectd_list_graphs($arg_host, $arg_plugin, $arg_pinst, $arg_type, $arg_tinst) {
+       $options = array(
+               'result' => array(),
+               'ridentifiers' => array(),
+               'cb_host' => '_collectd_list_cb_host',
+               'cb_plugin' => '_collectd_list_cb_plugin',
+               'cb_pinst' => '_collectd_list_cb_pinst',
+               'cb_type' => '_collectd_list_cb_type',
+               'cb_tinst' => '_collectd_list_cb_graph',
+               'filter_host' => $arg_host,
+               'filter_plugin' => $arg_plugin,
+               'filter_pinst' => $arg_pinst,
+               'filter_type' => $arg_type,
+               'filter_tinst' => $arg_tinst == '@' ? '@merge' : $arg_tinst
+       );
+       collectd_walk($options);
+       return $options['result'];
 }
 
 /**
index 17749e0..b9fefa6 100644 (file)
@@ -164,7 +164,7 @@ $logscale   = (boolean)read_var('logarithmic', $_GET, false);
 $tinylegend = (boolean)read_var('tinylegend', $_GET, false);
 
 // Check that at least 1 RRD exists for the specified request
-$all_tinst = collectd_list_tinsts($host, $plugin, $pinst, $type);
+$all_tinst = collectd_list_types($host, $plugin, $pinst, $type);
 if (count($all_tinst) == 0)
        return error404($graph_identifier, "No rrd file found for graphing");
 
@@ -182,7 +182,7 @@ if ($tinylegend)
        $opts['tinylegend']  = 1;
 
 $rrd_cmd = false;
-if (isset($MetaGraphDefs[$type])) {
+if ((is_null($tinst) || $tinst == '@merge') && isset($MetaGraphDefs[$type])) {
        $identifiers = array();
        foreach ($all_tinst as &$atinst)
                $identifiers[] = collectd_identifier($host, $plugin, is_null($pinst) ? '' : $pinst, $type, $atinst);
index 1abf40d..5953fbd 100644 (file)
@@ -39,6 +39,22 @@ function dhtml_response_list(&$items, $method) {
        print("</response>");
 }
 
+function dhtml_response_graphs(&$graphs, $method) {
+       header("Content-Type: text/xml");
+
+       print('<?xml version="1.0" encoding="utf-8" ?>'."\n");
+       print("<response>\n");
+       printf(" <method>%s</method>\n", htmlspecialchars($method));
+       print(" <result>\n");
+       foreach ($graphs as &$graph)
+               printf('  <graph host="%s" plugin="%s" plugin_instance="%s" type="%s" type_instance="%s" timespan="%s" logarithmic="%d" tinyLegend="%d" />'."\n",
+                      htmlspecialchars($graph['host']), htmlspecialchars($graph['plugin']), htmlspecialchars($graph['pinst']),
+                      htmlspecialchars($graph['type']), htmlspecialchars($graph['tinst']), htmlspecialchars($graph['timespan']),
+                      htmlspecialchars($graph['logarithmic']), htmlspecialchars($graph['tinyLegend']));
+       print(" </result>\n");
+       print("</response>");
+}
+
 /**
  * Product page body with selection fields
  */
@@ -66,7 +82,7 @@ function build_page() {
                <style type="text/css">
                        body, html { background-color: #EEEEEE; color: #000000; }
                        h1 { text-align: center; }
-                       div.body { margin: auto; width: <?php echo isset($config['rrd_width']) ? 125+(int)$config['rrd_width'] : 600; ?>px; background: #FFFFFF; border: 1px solid #DDDDDD; }
+                       div.body { margin: auto; width: <?php echo isset($config['rrd_width']) ? 110+(int)$config['rrd_width'] : 600; ?>px; background: #FFFFFF; border: 1px solid #DDDDDD; }
                        p.error { color: #CC0000; margin: 0em; }
                        div.selector { margin: 0.5em 2em; }
                        div.selectorbox { padding: 5px; border: 1px solid #CCCCCC; background-color: #F8F8F8; }
@@ -77,11 +93,12 @@ function build_page() {
                        div.selectorbox table td.sc { padding: 0.5em 2em; text-align: center; }
                        a img { border: none; }
                        div.graphs { border-top: 1px solid #DDDDDD; padding: 5px; overflow: auto; }
-                       div.graphs_t { display: table; }
-                       div.graph { display: table-row; }
-                       div.graph_img { display: table-cell; vertical-align: middle; text-align: right; }
-                       div.graph_opts { display: table-cell; vertical-align: middle; text-align: center; line-height: 2em; }
-                       select { width: 100%; }
+                       div.graphs_t { position: relative; }
+                       div.graph { text-align: right; }
+                       div.selector select { width: 100%; }
+                       table.toolbox { border: 1px solid #5500dd; padding: 0px; margin: 0px; background: #ffffff;}
+                       table.toolbox td.c1 { vertical-align: middle; text-align: left; padding-left: 0.3em; padding-right: 1em; border-right: 1px solid #5500dd; }
+                       table.toolbox td.c2 { vertical-align: middle; text-align: center; padding-left: 5px; padding-right: 5px; }
                </style>
                <script type="text/javascript">// <![CDATA[
 var dhtml_url = '<?php echo addslashes($url_base.basename($_SERVER['PHP_SELF'])); ?>';
@@ -137,7 +154,7 @@ var graph_url = '<?php echo addslashes($url_base.'graph.php'); ?>';
                                <tr>
                                        <td class="sc" colspan="3"><input id="btnAdd"     name="btnAdd"     type="button" disabled="disabled" onclick="GraphAppend()" value="Add graph" />
                                        <input id="btnClear"   name="btnClear"   type="button" disabled="disabled" onclick="GraphDropAll()" value="Remove all graphs" />
-                                       <input id="btnRefresh" name="btnRefresh" type="button" disabled="disabled" onclick="GraphRefresh(null)" value="Refresh all graphs" /></td>
+                                       <input id="btnRefresh" name="btnRefresh" type="button" disabled="disabled" onclick="GraphRefreshAll()" value="Refresh all graphs" /></td>
                                </tr>
                                <tr>
                                        <td class="s1" rowspan="2">Graph list favorites:</td>
@@ -193,6 +210,24 @@ var graph_url = '<?php echo addslashes($url_base.'graph.php'); ?>';
                                echo '<p class="error">Config error: RRDTOOL ('.htmlspecialchars(RRDTOOL).') is not executable</p>';
                        ?></div>
                </div></div>
+               <input type="hidden" name="ge_graphid" id="ge_graphid" value="" />
+               <table id="ge" class="toolbox" style="position: absolute; display: none; " cellspacing="1" cellpadding="0">
+                       <tr>
+                               <td class="c1" rowspan="3"><select id="ge_timespan" name="ge_timespan" onchange="GraphAdjust(null)"><?php
+                               foreach ($config['timespan'] as &$timespan)
+                                       printf("\t\t\t\t\t\t<option value=\"%s\">%s</option>\n", htmlspecialchars($timespan['name']), htmlspecialchars($timespan['label']));
+                               ?></select><br />
+                               <label><input id="ge_logarithmic"  name="ge_logarithmic" type="checkbox" value="1" onchange="GraphAdjust(null)" /> Logarithmic scale</label><br />
+                               <label><input id="ge_tinylegend"  name="ge_tinylegend" type="checkbox" value="1" onchange="GraphAdjust(null)" /> Minimal legend</label></td>
+                               <td class="c2"><a href="javascript:GraphMoveUp(null)"><img src="move-up.png" alt="UP" title="Move graph up"/></a></td>
+                       </tr>
+                       <tr>
+                               <td class="c2"><a href="javascript:GraphRefresh(null)"><img src="refresh.png" alt="R" title="Refresh graph"/></a>&nbsp;<a href="javascript:GraphRemove(null)"><img src="delete.png" alt="RM" title="Remove graph"/></a></td>
+                       </tr>
+                       <tr>
+                               <td class="c2"><a href="javascript:GraphMoveDown(null)"><img src="move-down.png" alt="DN" title="Move graph down"/></a></td>
+                       </tr>
+               </table>
        </div></body>
 </html><?php
 }
@@ -206,54 +241,87 @@ switch ($action) {
        case 'list_hosts':
                // Generate a list of hosts
                $hosts = collectd_list_hosts();
+               if (count($hosts) > 1)
+                       array_unshift($hosts, '@all');
                return dhtml_response_list($hosts, 'ListOfHost');
 
        case 'list_plugins':
                // Generate list of plugins for selected hosts
-               $arg_hosts = read_var('host', $_POST, array());
-               if (!is_array($arg_hosts))
-                       $arg_hosts = array($arg_hosts);
-               $plugins = collectd_list_plugins(reset($arg_hosts));
+               $arg_hosts = read_var('host', $_POST, '');
+               if (is_array($arg_hosts))
+                       $arg_hosts = reset($arg_hosts);
+               $plugins = collectd_list_plugins($arg_hosts);
+               if (count($plugins) > 1)
+                       array_unshift($plugins, '@all');
                return dhtml_response_list($plugins, 'ListOfPlugin');
 
        case 'list_pinsts':
                // Generate list of plugin_instances for selected hosts and plugin
-               $arg_hosts = read_var('host', $_POST, array());
-               if (!is_array($arg_hosts))
-                       $arg_hosts = array($arg_hosts);
+               $arg_hosts = read_var('host', $_POST, '');
+               if (is_array($arg_hosts))
+                       $arg_hosts = reset($arg_hosts);
                $arg_plugin = read_var('plugin', $_POST, '');
-               $pinsts = collectd_list_pinsts(reset($arg_hosts), $arg_plugin);
+               $pinsts = collectd_list_plugins($arg_hosts, $arg_plugin);
+               if (count($pinsts) > 1)
+                       array_unshift($pinsts, '@all' /* , '@merge_sum', '@merge_avg', '@merge_stack', '@merge_line' */);
                return dhtml_response_list($pinsts, 'ListOfPluginInstance');
 
        case 'list_types':
                // Generate list of types for selected hosts, plugin and plugin-instance
-               $arg_hosts  = read_var('host', $_POST, array());
-               if (!is_array($arg_hosts))
-                       $arg_hosts = array($arg_hosts);
+               $arg_hosts  = read_var('host', $_POST, '');
+               if (is_array($arg_hosts))
+                       $arg_hosts = reset($arg_hosts);
                $arg_plugin = read_var('plugin', $_POST, '');
                $arg_pinst  = read_var('plugin_instance', $_POST, '');
-               $types = collectd_list_types(reset($arg_hosts), $arg_plugin, $arg_pinst);
+               $types = collectd_list_types($arg_hosts, $arg_plugin, $arg_pinst);
+               if (count($types) > 1)
+                       array_unshift($types, '@all');
                return dhtml_response_list($types, 'ListOfType');
 
        case 'list_tinsts':
                // Generate list of types for selected hosts, plugin and plugin-instance
-               $arg_hosts  = read_var('host', $_POST, array());
-               if (!is_array($arg_hosts))
-                       $arg_hosts = array($arg_hosts);
+               $arg_hosts  = read_var('host', $_POST, '');
+               if (is_array($arg_hosts))
+                       $arg_hosts = reset($arg_hosts);
                $arg_plugin = read_var('plugin', $_POST, '');
                $arg_pinst  = read_var('plugin_instance', $_POST, '');
                $arg_type   = read_var('type', $_POST, '');
-               $tinsts = collectd_list_tinsts(reset($arg_hosts), $arg_plugin, $arg_pinst, $arg_type);
-               if (count($tinsts)) {
-                       require('definitions.php');
-                       load_graph_definitions();
-                       if (isset($MetaGraphDefs[$arg_type])) {
-                               $meta_tinsts = array('@');
-                               return dhtml_response_list($meta_tinsts, 'ListOfTypeInstance');
+               $tinsts = collectd_list_types($arg_hosts, $arg_plugin, $arg_pinst, $arg_type);
+               if (count($tinsts))
+                       if ($arg_type != '@all') {
+                               require('definitions.php');
+                               load_graph_definitions();
+                               if (isset($MetaGraphDefs[$arg_type]))
+                                       array_unshift($tinsts, '@merge');
+                               if (count($tinsts) > 1)
+                                       array_unshift($tinsts, '@all');
+                       } else {
+                               array_unshift($tinsts, /* '@merge_sum', '@merge_avg', '@merge_stack', '@merge_line', */ '@merge');
+                               if (count($tinsts) > 1)
+                                       array_unshift($tinsts, '@all');
                        }
-               }
                return dhtml_response_list($tinsts, 'ListOfTypeInstance');
 
+       case 'list_graphs':
+               // Generate list of types for selected hosts, plugin and plugin-instance
+               $arg_hosts  = read_var('host', $_POST, '');
+               if (is_array($arg_hosts))
+                       $arg_hosts = reset($arg_hosts);
+               $arg_plugin = read_var('plugin', $_POST, '');
+               $arg_pinst  = read_var('plugin_instance', $_POST, '');
+               $arg_type   = read_var('type', $_POST, '');
+               $arg_tinst  = read_var('type_instance', $_POST, '');
+               $arg_log    = (int)read_var('logarithmic', $_POST, '0');
+               $arg_legend = (int)read_var('tinyLegend', $_POST, '0');
+               $arg_period = read_var('timespan', $_POST, '');
+               $graphs = collectd_list_graphs($arg_hosts, $arg_plugin, $arg_pinst, $arg_type, $arg_tinst);
+               foreach ($graphs as &$graph) {
+                       $graph['logarithmic'] = $arg_log;
+                       $graph['tinyLegend']  = $arg_legend;
+                       $graph['timespan']    = $arg_period;
+               }
+               return dhtml_response_graphs($graphs, 'ListOfGraph');
+
        case 'overview':
        default:
                return build_page();
index 8f94b01..c1cc9df 100644 (file)
@@ -551,7 +551,8 @@ endif
 
 if BUILD_PLUGIN_NETWORK
 pkglib_LTLIBRARIES += network.la
-network_la_SOURCES = network.c network.h
+network_la_SOURCES = network.c network.h \
+                    utils_fbhash.c utils_fbhash.h
 network_la_CPPFLAGS = $(AM_CPPFLAGS)
 network_la_LDFLAGS = -module -avoid-version
 network_la_LIBADD = -lpthread
index b335488..ad7cc21 100644 (file)
@@ -1550,45 +1550,39 @@ specified statistics will not be collected.
 
 =head2 Plugin C<network>
 
-=over 4
-
-=item B<Listen> I<Host> [I<Port>]
-
-=item B<Server> I<Host> [I<Port>]
-
-The B<Server> statement sets the server to send datagrams B<to>.  The statement
-may occur multiple times to send each datagram to multiple destinations.
-
-The B<Listen> statement sets the interfaces to bind to. When multiple
-statements are found the daemon will bind to multiple interfaces.
-
-The argument I<Host> may be a hostname, an IPv4 address or an IPv6 address. If
-the argument is a multicast address the daemon will join that multicast group.
-
-If no B<Listen> statement is found the server tries join both, the default IPv6
-multicast group and the default IPv4 multicast group. If no B<Server> statement
-is found the client will try to send data to the IPv6 multicast group first. If
-that fails the client will try the IPv4 multicast group.
+The Network plugin sends data to a remote instance of collectd, receives data
+from a remote instance, or both at the same time. Data which has been received
+from the network is usually not transmitted again, but this can be actived, see
+the B<Forward> option below.
 
 The default IPv6 multicast group is C<ff18::efc0:4a42>. The default IPv4
-multicast group is C<239.192.74.66>.
-
-The optional I<Port> argument sets the port to use. It can either be given
-using a numeric port number or a service name. If the argument is omitted the
-default port B<25826> is assumed.
+multicast group is C<239.192.74.66>. The default I<UDP> port is B<25826>.
 
-Both, B<Server> and B<Listen> can be used as block, too, to provide
-configuration options for this socket only. For example:
+Both, B<Server> and B<Listen> can be used as single option or as block. When
+used as block, given options are valid for this socket only. For example:
 
  <Plugin "network">
-   <Server "my.server.tld">
+   Server "collectd.internal.tld"
+   <Server "collectd.external.tld">
      SecurityLevel "sign"
-     Secret "ohl0eQue"
+     Username "myhostname"
+     Password "ohl0eQue"
    </Server>
  </Plugin>
 
-The following options are understood within B<E<lt>ServerE<gt>> and
-B<E<lt>ListenE<gt>> blocks:
+=over 4
+
+=item B<E<lt>Server> I<Host> [I<Port>]B<E<gt>>
+
+The B<Server> statement/block sets the server to send datagrams to. The
+statement may occur multiple times to send each datagram to multiple
+destinations.
+
+The argument I<Host> may be a hostname, an IPv4 address or an IPv6 address. The
+optional second argument specifies a port number or a service name. If not
+given, the default, B<25826>, is used.
+
+The following options are recognized within B<Server> blocks:
 
 =over 4
 
@@ -1596,26 +1590,78 @@ B<E<lt>ListenE<gt>> blocks:
 
 Set the security you require for network communication. When the security level
 has been set to B<Encrypt>, data sent over the network will be encrypted using
-I<AES-256> and only encrypted data will be accepted when receiving. The
-integrity of encrypted packets is ensures using I<SHA-1>. When set to B<Sign>,
-transmitted data is signed using the I<HMAC-SHA-256> message authentication
-code and only signed and encrypted data is accepted when receiving. When set to
-B<None>, data is sent without any security and all data is accepted when
-receiving.
+I<AES-256>. The integrity of encrypted packets is ensured using I<SHA-1>. When
+set to B<Sign>, transmitted data is signed using the I<HMAC-SHA-256> message
+authentication code. When set to B<None>, data is sent without any security.
+
+This feature is only available if the I<network> plugin was linked with
+I<libgcrypt>.
+
+=item B<Username> I<Username>
+
+Sets the username to transmit. This is used by the server to lookup the
+password. See B<AuthFile> below. All security levels except B<None> require
+this setting.
+
+This feature is only available if the I<network> plugin was linked with
+I<libgcrypt>.
+
+=item B<Password> I<Password>
+
+Sets a password (shared secret) for this socket. All security levels except
+B<None> require this setting.
 
 This feature is only available if the I<network> plugin was linked with
 I<libgcrypt>.
 
-=item B<Secret> I<Secret>
+=back
+
+=item B<E<lt>Listen> I<Host> [I<Port>]B<E<gt>>
+
+The B<Listen> statement sets the interfaces to bind to. When multiple
+statements are found the daemon will bind to multiple interfaces.
+
+The argument I<Host> may be a hostname, an IPv4 address or an IPv6 address. If
+the argument is a multicast address the daemon will join that multicast group.
+The optional second argument specifies a port number or a service name. If not
+given, the default, B<25826>, is used.
+
+The following options are recognized within C<E<lt>ListenE<gt>> blocks:
+
+=over 4
+
+=item B<SecurityLevel> B<Encrypt>|B<Sign>|B<None>
 
-Sets a shared secret for this socket. All security levels except B<None>
-require this setting. For B<None> this setting is only required if you want to
-be able to decrypt encrypted data (B<SecurityLevel> is set to B<Encrypt> on the
-client).
+Set the security you require for network communication. When the security level
+has been set to B<Encrypt>, only encrypted data will be accepted. The integrity
+of encrypted packets is ensured using I<SHA-1>. When set to B<Sign>, only
+signed and encrypted data is accepted. When set to B<None>, all data will be
+accepted. If an B<AuthFile> option was given (see below), encrypted data is
+decrypted if possible.
 
 This feature is only available if the I<network> plugin was linked with
 I<libgcrypt>.
 
+=item B<AuthFile> I<Filename>
+
+Sets a file in which usernames are mapped to passwords. These passwords are
+used to verify signatures and to decrypt encrypted network packets. If
+B<SecurityLevel> is set to B<None>, this is optional. If given, signed data is
+verified and encrypted packets are decrypted. Otherwise, signed data is
+accepted without checking the signature and encrypted data cannot be decrypted.
+For the other security levels this option is mandatory.
+
+The file format is very simple: Each line consists of a username followed by a
+colon and any number of spaces followed by the password. To demonstrate, an
+example file could look like this:
+
+  user0: foo
+  user1: bar
+
+Each time a packet is received, the modification time of the file is checked
+using L<stat(2)>. If the file has been changed, the contents is re-read. While
+the file is being read, it is locked using L<fcntl(2)>.
+
 =back
 
 =item B<TimeToLive> I<1-255>
index 01688ee..713a354 100644 (file)
 #endif
 #define _POSIX_C_SOURCE 200112L
 
-#if 0
-/* Single UNIX needed for strdup. */
 #ifdef _XOPEN_SOURCE
 # undef _XOPEN_SOURCE
 #endif
-#define _XOPEN_SOURCE 500
-#endif
+#define _XOPEN_SOURCE 600
 
 #ifndef _REENTRANT
 # define _REENTRANT
index 986efaf..0492c81 100644 (file)
--- a/src/irq.c
+++ b/src/irq.c
@@ -151,8 +151,8 @@ static int irq_read (void)
        FILE *fh;
        char buffer[BUFSIZE];
        unsigned int irq;
-       unsigned int irq_value;
-       long value;
+       unsigned long long irq_value;
+       unsigned long long value;
        char *endptr;
        int i;
 
@@ -182,7 +182,7 @@ static int irq_read (void)
                for (i = 1; i < fields_num; i++)
                {
                        errno = 0;
-                       value = strtol (fields[i], &endptr, 10);
+                       value = strtoull (fields[i], &endptr, 10);
 
                        if ((*endptr != '\0') || (errno != 0))
                                break;
index f62994c..1c67ab7 100644 (file)
@@ -29,6 +29,9 @@
 #ifndef _POSIX_C_SOURCE
 # define _POSIX_C_SOURCE 200112L
 #endif
+#ifndef _XOPEN_SOURCE
+# define _XOPEN_SOURCE 600
+#endif
 #ifndef _REENTRANT
 # define _REENTRANT
 #endif
index 1412f7e..0c0d8db 100644 (file)
 #endif
 #define _POSIX_C_SOURCE 200112L
 
-#if 0
-/* Single UNIX needed for strdup. */
 #ifdef _XOPEN_SOURCE
 # undef _XOPEN_SOURCE
 #endif
-#define _XOPEN_SOURCE 500
-#endif
+#define _XOPEN_SOURCE 600
 
 #ifndef _REENTRANT
 # define _REENTRANT
index ca5c525..f243c50 100644 (file)
@@ -4,6 +4,7 @@
  * Copyright (C) 2008       Mirko Buffoni
  * Copyright (C) 2009       Doug MacEachern
  * Copyright (C) 2009       Sebastian tokkee Harl
+ * Copyright (C) 2009       Rodolphe Quiédeville
  *
  * 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
@@ -23,6 +24,7 @@
  *   Mirko Buffoni <briareos at eswat.org>
  *   Doug MacEachern <dougm at hyperic.com>
  *   Sebastian tokkee Harl <sh at tokkee.org>
+ *   Rodolphe Quiédeville <rquiedeville at bearstech.com>
  **/
 
 #include "collectd.h"
@@ -745,23 +747,30 @@ static int mysql_read (user_data_t *ud)
                key = row[0];
                val = atoll (row[1]);
 
-               if (strncmp (key, "Com_", 4) == 0)
+               if (strncmp (key, "Com_", 
+                                 strlen ("Com_")) == 0)
                {
                        if (val == 0ULL)
                                continue;
 
                        /* Ignore `prepared statements' */
-                       if (strncmp (key, "Com_stmt_", 9) != 0)
-                               counter_submit ("mysql_commands", key + 4, val, db);
+                       if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
+                               counter_submit ("mysql_commands", 
+                                               key + strlen ("Com_"), 
+                                               val, db);
                }
-               else if (strncmp (key, "Handler_", 8) == 0)
+               else if (strncmp (key, "Handler_", 
+                                       strlen ("Handler_")) == 0)
                {
                        if (val == 0ULL)
                                continue;
 
-                       counter_submit ("mysql_handler", key + 8, val, db);
+                       counter_submit ("mysql_handler", 
+                                       key + strlen ("Handler_"), 
+                                       val, db);
                }
-               else if (strncmp (key, "Qcache_", 7) == 0)
+               else if (strncmp (key, "Qcache_",
+                                               strlen ("Qcache_")) == 0)
                {
                        if (strcmp (key, "Qcache_hits") == 0)
                                qcache_hits = val;
@@ -774,14 +783,16 @@ static int mysql_read (user_data_t *ud)
                        else if (strcmp (key, "Qcache_queries_in_cache") == 0)
                                qcache_queries_in_cache = (int) val;
                }
-               else if (strncmp (key, "Bytes_", 6) == 0)
+               else if (strncmp (key, "Bytes_", 
+                                       strlen ("Bytes_")) == 0)
                {
                        if (strcmp (key, "Bytes_received") == 0)
                                traffic_incoming += val;
                        else if (strcmp (key, "Bytes_sent") == 0)
                                traffic_outgoing += val;
                }
-               else if (strncmp (key, "Threads_", 8) == 0)
+               else if (strncmp (key, "Threads_", 
+                                               strlen ("Threads_")) == 0)
                {
                        if (strcmp (key, "Threads_running") == 0)
                                threads_running = (int) val;
@@ -792,6 +803,13 @@ static int mysql_read (user_data_t *ud)
                        else if (strcmp (key, "Threads_created") == 0)
                                threads_created = val;
                }
+               else if (strncmp (key, "Table_locks_",
+                                       strlen ("Table_locks_")) == 0)
+               {
+                       counter_submit ("mysql_locks",
+                                       key + strlen ("Table_locks_"),
+                                       val, db);
+               }
        }
        mysql_free_result (res); res = NULL;
 
index 7023eaa..67a7c3c 100644 (file)
@@ -23,6 +23,7 @@
 #include "plugin.h"
 #include "common.h"
 #include "configfile.h"
+#include "utils_fbhash.h"
 #include "utils_avltree.h"
 
 #include "network.h"
@@ -46,7 +47,7 @@
 # include <poll.h>
 #endif
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
 # include <gcrypt.h>
 #endif
 
 
 /*
  * Maximum size required for encryption / signing:
- * Type/length:       4
- * IV                16
- * Hash/orig length: 22
- * Padding (up to):  15
- * --------------------
- *                   57
+ *
+ *    42 bytes for the encryption header
+ * +  64 bytes for the username
+ * -----------
+ * = 106 bytes
  */
-#define BUFF_SIG_SIZE 57
+#define BUFF_SIG_SIZE 106
 
 /*
  * Private data types
  */
-typedef struct sockent
+#define SECURITY_LEVEL_NONE     0
+#if HAVE_LIBGCRYPT
+# define SECURITY_LEVEL_SIGN    1
+# define SECURITY_LEVEL_ENCRYPT 2
+#endif
+struct sockent_client
 {
-       int                      fd;
+       int fd;
        struct sockaddr_storage *addr;
        socklen_t                addrlen;
+#if HAVE_LIBGCRYPT
+       int security_level;
+       char *username;
+       char *password;
+       gcry_cipher_hd_t cypher;
+       unsigned char password_hash[32];
+#endif
+};
 
-#define SECURITY_LEVEL_NONE     0
-#if HAVE_GCRYPT_H
-# define SECURITY_LEVEL_SIGN    1
-# define SECURITY_LEVEL_ENCRYPT 2
+struct sockent_server
+{
+       int *fd;
+       size_t fd_num;
+#if HAVE_LIBGCRYPT
        int security_level;
-       char *shared_secret;
-       unsigned char shared_secret_hash[32];
+       char *auth_file;
+       fbhash_t *userdb;
        gcry_cipher_hd_t cypher;
-#endif /* HAVE_GCRYPT_H */
+#endif
+};
+
+typedef struct sockent
+{
+#define SOCKENT_TYPE_CLIENT 1
+#define SOCKENT_TYPE_SERVER 2
+       int type;
+
+       char *node;
+       char *service;
+
+       union
+       {
+               struct sockent_client client;
+               struct sockent_server server;
+       } data;
 
-       struct sockent          *next;
+       struct sockent *next;
 } sockent_t;
 
 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
@@ -173,11 +203,13 @@ typedef struct part_values_s part_values_t;
  * ! Hash (Bits 224 - 255)                                         !
  * +---------------------------------------------------------------+
  */
+/* Minimum size */
 #define PART_SIGNATURE_SHA256_SIZE 36
 struct part_signature_sha256_s
 {
   part_header_t head;
   unsigned char hash[32];
+  char *username;
 };
 typedef struct part_signature_sha256_s part_signature_sha256_t;
 
@@ -193,16 +225,18 @@ typedef struct part_signature_sha256_s part_signature_sha256_t;
  * ! Hash (Bits 128 - 159)                                         !
  * +---------------------------------------------------------------+
  */
-/* Size without padding */
+/* Minimum size */
 #define PART_ENCRYPTION_AES256_SIZE 42
-#define PART_ENCRYPTION_AES256_UNENCR_SIZE 20
 struct part_encryption_aes256_s
 {
   part_header_t head;
+  uint16_t username_length;
+  char *username;
   unsigned char iv[16];
-  uint16_t orig_length;
+  /* <encrypted> */
   unsigned char hash[20];
-  unsigned char padding[15];
+  /*   <payload /> */
+  /* </encrypted> */
 };
 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
 
@@ -230,7 +264,7 @@ static pthread_cond_t        receive_list_cond = PTHREAD_COND_INITIALIZER;
 
 static sockent_t     *listen_sockets = NULL;
 static struct pollfd *listen_sockets_pollfd = NULL;
-static int            listen_sockets_num = 0;
+static size_t         listen_sockets_num = 0;
 
 /* The receive and dispatch threads will run as long as `listen_loop' is set to
  * zero. */
@@ -369,54 +403,82 @@ static int cache_check (const value_list_t *vl)
        return (retval);
 } /* int cache_check */
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
-    const void *iv, size_t iv_size)
+    const void *iv, size_t iv_size, const char *username)
 {
   gcry_error_t err;
+  gcry_cipher_hd_t *cyper_ptr;
+  unsigned char password_hash[32];
+
+  if (se->type == SOCKENT_TYPE_CLIENT)
+  {
+         cyper_ptr = &se->data.client.cypher;
+         memcpy (password_hash, se->data.client.password_hash,
+                         sizeof (password_hash));
+  }
+  else
+  {
+         char *secret;
+
+         cyper_ptr = &se->data.server.cypher;
+
+         if (username == NULL)
+                 return (NULL);
+
+         secret = fbh_get (se->data.server.userdb, username);
+         if (secret == NULL)
+                 return (NULL);
 
-  if (se->cypher == NULL)
+         gcry_md_hash_buffer (GCRY_MD_SHA256,
+                         password_hash,
+                         secret, strlen (secret));
+
+         sfree (secret);
+  }
+
+  if (*cyper_ptr == NULL)
   {
-    err = gcry_cipher_open (&se->cypher,
-        GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, /* flags = */ 0);
+    err = gcry_cipher_open (cyper_ptr,
+        GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
     if (err != 0)
     {
       ERROR ("network plugin: gcry_cipher_open returned: %s",
           gcry_strerror (err));
-      se->cypher = NULL;
+      *cyper_ptr = NULL;
       return (NULL);
     }
   }
   else
   {
-    gcry_cipher_reset (se->cypher);
+    gcry_cipher_reset (*cyper_ptr);
   }
-  assert (se->cypher != NULL);
+  assert (*cyper_ptr != NULL);
 
-  err = gcry_cipher_setkey (se->cypher,
-      se->shared_secret_hash, sizeof (se->shared_secret_hash));
+  err = gcry_cipher_setkey (*cyper_ptr,
+      password_hash, sizeof (password_hash));
   if (err != 0)
   {
     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
         gcry_strerror (err));
-    gcry_cipher_close (se->cypher);
-    se->cypher = NULL;
+    gcry_cipher_close (*cyper_ptr);
+    *cyper_ptr = NULL;
     return (NULL);
   }
 
-  err = gcry_cipher_setiv (se->cypher, iv, iv_size);
+  err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
   if (err != 0)
   {
     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
         gcry_strerror (err));
-    gcry_cipher_close (se->cypher);
-    se->cypher = NULL;
+    gcry_cipher_close (*cyper_ptr);
+    *cyper_ptr = NULL;
     return (NULL);
   }
 
-  return (se->cypher);
+  return (*cyper_ptr);
 } /* }}} int network_get_aes256_cypher */
-#endif /* HAVE_GCRYPT_H */
+#endif /* HAVE_LIBGCRYPT */
 
 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
                const data_set_t *ds, const value_list_t *vl)
@@ -801,7 +863,7 @@ static int parse_packet (sockent_t *se,
   buffer_offset += (s); \
 } while (0)
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
     void **ret_buffer, size_t *ret_buffer_len, int flags)
 {
@@ -809,7 +871,11 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
   size_t buffer_len;
   size_t buffer_offset;
 
+  size_t username_len;
+  char *secret;
+
   part_signature_sha256_t pss;
+  uint16_t pss_head_length;
   char hash[sizeof (pss.hash)];
 
   gcry_md_hd_t hd;
@@ -820,60 +886,95 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
   buffer_len = *ret_buffer_len;
   buffer_offset = 0;
 
-  if (se->shared_secret == NULL)
+  if (se->data.server.userdb == NULL)
   {
     NOTICE ("network plugin: Received signed network packet but can't verify "
-        "it because no shared secret has been configured. Will accept it.");
+        "it because no user DB has been configured. Will accept it.");
     return (0);
   }
 
-  if (buffer_len < PART_SIGNATURE_SHA256_SIZE)
+  /* Check if the buffer has enough data for this structure. */
+  if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
     return (-ENOMEM);
 
+  /* Read type and length header */
   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
-  BUFFER_READ (pss.hash, sizeof (pss.hash));
-
-  assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
+  pss_head_length = ntohs (pss.head.length);
 
-  if (ntohs (pss.head.length) != PART_SIGNATURE_SHA256_SIZE)
+  /* Check if the `pss_head_length' is within bounds. */
+  if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
+      || (pss_head_length > buffer_len))
   {
     ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
     return (-1);
   }
 
+  /* Copy the hash. */
+  BUFFER_READ (pss.hash, sizeof (pss.hash));
+
+  /* Calculate username length (without null byte) and allocate memory */
+  username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
+  pss.username = malloc (username_len + 1);
+  if (pss.username == NULL)
+    return (-ENOMEM);
+
+  /* Read the username */
+  BUFFER_READ (pss.username, username_len);
+  pss.username[username_len] = 0;
+
+  assert (buffer_offset == pss_head_length);
+
+  /* Query the password */
+  secret = fbh_get (se->data.server.userdb, pss.username);
+  if (secret == NULL)
+  {
+    ERROR ("network plugin: Unknown user: %s", pss.username);
+    sfree (pss.username);
+    return (-ENOENT);
+  }
+
+  /* Create a hash device and check the HMAC */
   hd = NULL;
   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
   if (err != 0)
   {
     ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
         gcry_strerror (err));
+    sfree (secret);
+    sfree (pss.username);
     return (-1);
   }
 
-  err = gcry_md_setkey (hd, se->shared_secret,
-      strlen (se->shared_secret));
+  err = gcry_md_setkey (hd, secret, strlen (secret));
   if (err != 0)
   {
-    ERROR ("network plugin: gcry_md_setkey failed: %s",
-        gcry_strerror (err));
+    ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
     gcry_md_close (hd);
     return (-1);
   }
 
-  gcry_md_write (hd, buffer + buffer_offset, buffer_len - buffer_offset);
+  gcry_md_write (hd,
+      buffer     + PART_SIGNATURE_SHA256_SIZE,
+      buffer_len - PART_SIGNATURE_SHA256_SIZE);
   hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
   if (hash_ptr == NULL)
   {
     ERROR ("network plugin: gcry_md_read failed.");
     gcry_md_close (hd);
+    sfree (secret);
+    sfree (pss.username);
     return (-1);
   }
   memcpy (hash, hash_ptr, sizeof (hash));
 
+  /* Clean up */
   gcry_md_close (hd);
   hd = NULL;
 
+  sfree (secret);
+  sfree (pss.username);
+
   if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
   {
     WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
@@ -890,9 +991,9 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
 
   return (0);
 } /* }}} int parse_part_sign_sha256 */
-/* #endif HAVE_GCRYPT_H */
+/* #endif HAVE_LIBGCRYPT */
 
-#else /* if !HAVE_GCRYPT_H */
+#else /* if !HAVE_LIBGCRYPT */
 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
     void **ret_buffer, size_t *ret_buffer_size, int flags)
 {
@@ -901,6 +1002,7 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
   char *buffer;
   size_t buffer_size;
   size_t buffer_offset;
+  uint16_t part_len;
 
   part_signature_sha256_t pss;
 
@@ -908,20 +1010,16 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
   buffer_size = *ret_buffer_size;
   buffer_offset = 0;
 
-  if (buffer_size < PART_SIGNATURE_SHA256_SIZE)
+  if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
     return (-ENOMEM);
 
   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
-  BUFFER_READ (pss.hash, sizeof (pss.hash));
-
-  assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
+  part_len = ntohs (pss.head.length);
 
-  if (ntohs (pss.head.length) != PART_SIGNATURE_SHA256_SIZE)
-  {
-    ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
-    return (-1);
-  }
+  if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
+      || (part_len > buffer_size))
+    return (-EINVAL);
 
   if (warning_has_been_printed == 0)
   {
@@ -931,27 +1029,26 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
     warning_has_been_printed = 1;
   }
 
-  parse_packet (se, buffer + buffer_offset, buffer_size - buffer_offset,
-      flags);
+  parse_packet (se, buffer + part_len, buffer_size - part_len, flags);
 
   *ret_buffer = buffer + buffer_size;
   *ret_buffer_size = 0;
 
   return (0);
 } /* }}} int parse_part_sign_sha256 */
-#endif /* !HAVE_GCRYPT_H */
+#endif /* !HAVE_LIBGCRYPT */
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
                void **ret_buffer, size_t *ret_buffer_len,
                int flags)
 {
   char  *buffer = *ret_buffer;
   size_t buffer_len = *ret_buffer_len;
-  size_t orig_buffer_len;
+  size_t payload_len;
   size_t part_size;
   size_t buffer_offset;
-  size_t padding_size;
+  uint16_t username_len;
   part_encryption_aes256_t pea;
   unsigned char hash[sizeof (pea.hash)];
 
@@ -959,7 +1056,7 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
   gcry_error_t err;
 
   /* Make sure at least the header if available. */
-  if (buffer_len < sizeof (pea))
+  if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
   {
     NOTICE ("network plugin: parse_part_encr_aes256: "
         "Discarding short packet.");
@@ -971,25 +1068,55 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
   /* Copy the unencrypted information into `pea'. */
   BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
   BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
-  BUFFER_READ (pea.iv, sizeof (pea.iv));
 
   /* Check the `part size'. */
   part_size = ntohs (pea.head.length);
-  if (part_size > buffer_len)
+  if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
+      || (part_size > buffer_len))
+  {
+    NOTICE ("network plugin: parse_part_encr_aes256: "
+        "Discarding part with invalid size.");
+    return (-1);
+  }
+
+  /* Read the username */
+  BUFFER_READ (&username_len, sizeof (username_len));
+  username_len = ntohs (username_len);
+
+  if ((username_len <= 0)
+      || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
   {
     NOTICE ("network plugin: parse_part_encr_aes256: "
-        "Discarding large part.");
+        "Discarding part with invalid username length.");
     return (-1);
   }
 
-  cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv));
+  assert (username_len > 0);
+  pea.username = malloc (username_len + 1);
+  if (pea.username == NULL)
+    return (-ENOMEM);
+  BUFFER_READ (pea.username, username_len);
+  pea.username[username_len] = 0;
+
+  /* Last but not least, the initialization vector */
+  BUFFER_READ (pea.iv, sizeof (pea.iv));
+
+  /* Make sure we are at the right position */
+  assert (buffer_offset == (username_len +
+        PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
+
+  cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
+      pea.username);
   if (cypher == NULL)
     return (-1);
 
+  payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
+  assert (payload_len > 0);
+
   /* Decrypt the packet in-place */
   err = gcry_cipher_decrypt (cypher,
-      buffer    + PART_ENCRYPTION_AES256_UNENCR_SIZE,
-      part_size - PART_ENCRYPTION_AES256_UNENCR_SIZE,
+      buffer    + buffer_offset,
+      part_size - buffer_offset,
       /* in = */ NULL, /* in len = */ 0);
   if (err != 0)
   {
@@ -998,46 +1125,25 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
     return (-1);
   }
 
-  /* Figure out the length of the payload and the length of the padding. */
-  BUFFER_READ (&pea.orig_length, sizeof (pea.orig_length));
-
-  orig_buffer_len = ntohs (pea.orig_length);
-  if (orig_buffer_len > (part_size - PART_ENCRYPTION_AES256_SIZE))
-  {
-    ERROR ("network plugin: Decryption failed: Invalid original length.");
-    return (-1);
-  }
-
-  /* Calculate the size of the `padding' field. */
-  padding_size = part_size - (orig_buffer_len + PART_ENCRYPTION_AES256_SIZE);
-  if (padding_size > sizeof (pea.padding))
-  {
-    ERROR ("network plugin: Part- and original length "
-        "differ more than %zu bytes.", sizeof (pea.padding));
-    return (-1);
-  }
-
+  /* Read the hash */
   BUFFER_READ (pea.hash, sizeof (pea.hash));
 
-  /* Read the padding. */
-  BUFFER_READ (pea.padding, padding_size);
+  /* Make sure we're at the right position - again */
+  assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
+  assert (buffer_offset == (part_size - payload_len));
 
   /* Check hash sum */
   memset (hash, 0, sizeof (hash));
   gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
-      buffer + buffer_offset, orig_buffer_len);
-  
+      buffer + buffer_offset, payload_len);
   if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
   {
     ERROR ("network plugin: Decryption failed: Checksum mismatch.");
     return (-1);
   }
 
-  assert ((PART_ENCRYPTION_AES256_SIZE + padding_size + orig_buffer_len)
-                 == part_size);
-
-  parse_packet (se, buffer + PART_ENCRYPTION_AES256_SIZE + padding_size,
-                 orig_buffer_len, flags | PP_ENCRYPTED);
+  parse_packet (se, buffer + buffer_offset, payload_len,
+      flags | PP_ENCRYPTED);
 
   /* Update return values */
   *ret_buffer =     buffer     + part_size;
@@ -1045,9 +1151,9 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
 
   return (0);
 } /* }}} int parse_part_encr_aes256 */
-/* #endif HAVE_GCRYPT_H */
+/* #endif HAVE_LIBGCRYPT */
 
-#else /* if !HAVE_GCRYPT_H */
+#else /* if !HAVE_LIBGCRYPT */
 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
     void **ret_buffer, size_t *ret_buffer_size, int flags)
 {
@@ -1071,7 +1177,7 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
   BUFFER_READ (&ph.length, sizeof (ph.length));
   ph_length = ntohs (ph.length);
 
-  if ((ph_length < PART_ENCRYPTION_AES256_SIZE)
+  if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
       || (ph_length > buffer_size))
   {
     ERROR ("network plugin: AES-256 encrypted part "
@@ -1092,7 +1198,7 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
 
   return (0);
 } /* }}} int parse_part_encr_aes256 */
-#endif /* !HAVE_GCRYPT_H */
+#endif /* !HAVE_LIBGCRYPT */
 
 #undef BUFFER_READ
 
@@ -1104,11 +1210,11 @@ static int parse_packet (sockent_t *se, /* {{{ */
        value_list_t vl = VALUE_LIST_INIT;
        notification_t n;
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
        int packet_was_signed = (flags & PP_SIGNED);
         int packet_was_encrypted = (flags & PP_ENCRYPTED);
        int printed_ignore_warning = 0;
-#endif /* HAVE_GCRYPT_H */
+#endif /* HAVE_LIBGCRYPT */
 
 
        memset (&vl, '\0', sizeof (vl));
@@ -1149,8 +1255,8 @@ static int parse_packet (sockent_t *se, /* {{{ */
                                break;
                        }
                }
-#if HAVE_GCRYPT_H
-               else if ((se->security_level == SECURITY_LEVEL_ENCRYPT)
+#if HAVE_LIBGCRYPT
+               else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
                                && (packet_was_encrypted == 0))
                {
                        if (printed_ignore_warning == 0)
@@ -1162,7 +1268,7 @@ static int parse_packet (sockent_t *se, /* {{{ */
                        buffer = ((char *) buffer) + pkg_length;
                        continue;
                }
-#endif /* HAVE_GCRYPT_H */
+#endif /* HAVE_LIBGCRYPT */
                else if (pkg_type == TYPE_SIGN_SHA256)
                {
                        status = parse_part_sign_sha256 (se,
@@ -1175,8 +1281,8 @@ static int parse_packet (sockent_t *se, /* {{{ */
                                break;
                        }
                }
-#if HAVE_GCRYPT_H
-               else if ((se->security_level == SECURITY_LEVEL_SIGN)
+#if HAVE_LIBGCRYPT
+               else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
                                && (packet_was_encrypted == 0)
                                && (packet_was_signed == 0))
                {
@@ -1189,7 +1295,7 @@ static int parse_packet (sockent_t *se, /* {{{ */
                        buffer = ((char *) buffer) + pkg_length;
                        continue;
                }
-#endif /* HAVE_GCRYPT_H */
+#endif /* HAVE_LIBGCRYPT */
                else if (pkg_type == TYPE_VALUES)
                {
                        status = parse_part_values (&buffer, &buffer_size,
@@ -1328,28 +1434,66 @@ static int parse_packet (sockent_t *se, /* {{{ */
        return (status);
 } /* }}} int parse_packet */
 
-static void free_sockent (sockent_t *se) /* {{{ */
+static void free_sockent_client (struct sockent_client *sec) /* {{{ */
 {
-       sockent_t *next;
-       while (se != NULL)
-       {
-               next = se->next;
+  if (sec->fd >= 0)
+  {
+    close (sec->fd);
+    sec->fd = -1;
+  }
+  sfree (sec->addr);
+#if HAVE_LIBGCRYPT
+  sfree (sec->username);
+  sfree (sec->password);
+  if (sec->cypher != NULL)
+    gcry_cipher_close (sec->cypher);
+#endif
+} /* }}} void free_sockent_client */
 
-#if HAVE_GCRYPT_H
-               if (se->cypher != NULL)
-               {
-                       gcry_cipher_close (se->cypher);
-                       se->cypher = NULL;
-               }
-               free (se->shared_secret);
-#endif /* HAVE_GCRYPT_H */
+static void free_sockent_server (struct sockent_server *ses) /* {{{ */
+{
+  size_t i;
+
+  for (i = 0; i < ses->fd_num; i++)
+  {
+    if (ses->fd[i] >= 0)
+    {
+      close (ses->fd[i]);
+      ses->fd[i] = -1;
+    }
+  }
 
-               free (se->addr);
-               free (se);
+  sfree (ses->fd);
+#if HAVE_LIBGCRYPT
+  sfree (ses->auth_file);
+  fbh_destroy (ses->userdb);
+  if (ses->cypher != NULL)
+    gcry_cipher_close (ses->cypher);
+#endif
+} /* }}} void free_sockent_server */
 
-               se = next;
-       }
-} /* }}} void free_sockent */
+static void sockent_destroy (sockent_t *se) /* {{{ */
+{
+  sockent_t *next;
+
+  DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
+
+  while (se != NULL)
+  {
+    next = se->next;
+
+    sfree (se->node);
+    sfree (se->service);
+
+    if (se->type == SOCKENT_TYPE_CLIENT)
+      free_sockent_client (&se->data.client);
+    else
+      free_sockent_server (&se->data.server);
+
+    sfree (se);
+    se = next;
+  }
+} /* }}} void sockent_destroy */
 
 /*
  * int network_set_ttl
@@ -1365,6 +1509,8 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
        DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
                        network_config_ttl);
 
+        assert (se->type == SOCKENT_TYPE_CLIENT);
+
        if ((network_config_ttl < 1) || (network_config_ttl > 255))
                return (-1);
 
@@ -1378,7 +1524,7 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
                else
                        optname = IP_TTL;
 
-               if (setsockopt (se->fd, IPPROTO_IP, optname,
+               if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
                                        &network_config_ttl,
                                        sizeof (network_config_ttl)) == -1)
                {
@@ -1399,7 +1545,7 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
                else
                        optname = IPV6_UNICAST_HOPS;
 
-               if (setsockopt (se->fd, IPPROTO_IPV6, optname,
+               if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
                                        &network_config_ttl,
                                        sizeof (network_config_ttl)) == -1)
                {
@@ -1414,13 +1560,13 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
        return (0);
 } /* int network_set_ttl */
 
-static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
+static int network_bind_socket (int fd, const struct addrinfo *ai)
 {
        int loop = 0;
        int yes  = 1;
 
        /* allow multiple sockets to use the same PORT number */
-       if (setsockopt(se->fd, SOL_SOCKET, SO_REUSEADDR,
+       if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
                                &yes, sizeof(yes)) == -1) {
                 char errbuf[1024];
                 ERROR ("setsockopt: %s", 
@@ -1428,9 +1574,9 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
                return (-1);
        }
 
-       DEBUG ("fd = %i; calling `bind'", se->fd);
+       DEBUG ("fd = %i; calling `bind'", fd);
 
-       if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
+       if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
        {
                char errbuf[1024];
                ERROR ("bind: %s",
@@ -1445,12 +1591,12 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
                {
                        struct ip_mreq mreq;
 
-                       DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
+                       DEBUG ("fd = %i; IPv4 multicast address found", fd);
 
                        mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
                        mreq.imr_interface.s_addr = htonl (INADDR_ANY);
 
-                       if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
+                       if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
                                                &loop, sizeof (loop)) == -1)
                        {
                                char errbuf[1024];
@@ -1460,7 +1606,7 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
                                return (-1);
                        }
 
-                       if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+                       if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
                                                &mreq, sizeof (mreq)) == -1)
                        {
                                char errbuf[1024];
@@ -1479,7 +1625,7 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
                {
                        struct ipv6_mreq mreq;
 
-                       DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
+                       DEBUG ("fd = %i; IPv6 multicast address found", fd);
 
                        memcpy (&mreq.ipv6mr_multiaddr,
                                        &addr->sin6_addr,
@@ -1496,7 +1642,7 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
                         * group on more than one interface.*/
                        mreq.ipv6mr_interface = 0;
 
-                       if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
+                       if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
                                                &loop, sizeof (loop)) == -1)
                        {
                                char errbuf[1024];
@@ -1506,7 +1652,7 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
                                return (-1);
                        }
 
-                       if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
+                       if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
                                                &mreq, sizeof (mreq)) == -1)
                        {
                                char errbuf[1024];
@@ -1521,24 +1667,117 @@ static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
        return (0);
 } /* int network_bind_socket */
 
-#define CREATE_SOCKET_FLAGS_LISTEN    0x0001
-static sockent_t *network_create_socket (const char *node, /* {{{ */
-               const char *service,
-               const char *shared_secret,
-                int security_level,
-               int flags)
+/* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
+ * or `SOCKENT_TYPE_SERVER' */
+static int sockent_init (sockent_t *se, int type) /* {{{ */
+{
+       if (se == NULL)
+               return (-1);
+
+       memset (se, 0, sizeof (*se));
+
+       se->type = SOCKENT_TYPE_CLIENT;
+       se->node = NULL;
+       se->service = NULL;
+       se->next = NULL;
+
+       if (type == SOCKENT_TYPE_SERVER)
+       {
+               se->type = SOCKENT_TYPE_SERVER;
+               se->data.server.fd = NULL;
+#if HAVE_LIBGCRYPT
+               se->data.server.security_level = SECURITY_LEVEL_NONE;
+               se->data.server.auth_file = NULL;
+               se->data.server.userdb = NULL;
+               se->data.server.cypher = NULL;
+#endif
+       }
+       else
+       {
+               se->data.client.fd = -1;
+               se->data.client.addr = NULL;
+#if HAVE_LIBGCRYPT
+               se->data.client.security_level = SECURITY_LEVEL_NONE;
+               se->data.client.username = NULL;
+               se->data.client.password = NULL;
+               se->data.client.cypher = NULL;
+#endif
+       }
+
+       return (0);
+} /* }}} int sockent_init */
+
+/* Open the file descriptors for a initialized sockent structure. */
+static int sockent_open (sockent_t *se) /* {{{ */
 {
        struct addrinfo  ai_hints;
        struct addrinfo *ai_list, *ai_ptr;
        int              ai_return;
 
-       sockent_t *se_head = NULL;
-       sockent_t *se_tail = NULL;
+        const char *node;
+        const char *service;
+
+       if (se == NULL)
+               return (-1);
+
+       /* Set up the security structures. */
+#if HAVE_LIBGCRYPT /* {{{ */
+       if (se->type == SOCKENT_TYPE_CLIENT)
+       {
+               if (se->data.client.security_level > SECURITY_LEVEL_NONE)
+               {
+                       if ((se->data.client.username == NULL)
+                                       || (se->data.client.password == NULL))
+                       {
+                               ERROR ("network plugin: Client socket with "
+                                               "security requested, but no "
+                                               "credentials are configured.");
+                               return (-1);
+                       }
+                       gcry_md_hash_buffer (GCRY_MD_SHA256,
+                                       se->data.client.password_hash,
+                                       se->data.client.password,
+                                       strlen (se->data.client.password));
+               }
+       }
+       else /* (se->type == SOCKENT_TYPE_SERVER) */
+       {
+               if (se->data.server.security_level > SECURITY_LEVEL_NONE)
+               {
+                       if (se->data.server.auth_file == NULL)
+                       {
+                               ERROR ("network plugin: Server socket with "
+                                               "security requested, but no "
+                                               "password file is configured.");
+                               return (-1);
+                       }
+               }
+               if (se->data.server.auth_file != NULL)
+               {
+                       se->data.server.userdb = fbh_create (se->data.server.auth_file);
+                       if (se->data.server.userdb == NULL)
+                       {
+                               ERROR ("network plugin: Reading password file "
+                                               "`%s' failed.",
+                                               se->data.server.auth_file);
+                               if (se->data.server.security_level > SECURITY_LEVEL_NONE)
+                                       return (-1);
+                       }
+               }
+       }
+#endif /* }}} HAVE_LIBGCRYPT */
+
+        node = se->node;
+        service = se->service;
 
-       DEBUG ("node = %s, service = %s", node, service);
+        if (service == NULL)
+          service = NET_DEFAULT_PORT;
 
-       memset (&ai_hints, '\0', sizeof (ai_hints));
-       ai_hints.ai_flags    = 0;
+        DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
+            node, service);
+
+       memset (&ai_hints, 0, sizeof (ai_hints));
+       ai_hints.ai_flags  = 0;
 #ifdef AI_PASSIVE
        ai_hints.ai_flags |= AI_PASSIVE;
 #endif
@@ -1552,234 +1791,163 @@ static sockent_t *network_create_socket (const char *node, /* {{{ */
        ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
        if (ai_return != 0)
        {
-               char errbuf[1024];
-               ERROR ("getaddrinfo (%s, %s): %s",
-                               (node == NULL) ? "(null)" : node,
-                               (service == NULL) ? "(null)" : service,
-                               (ai_return == EAI_SYSTEM)
-                               ? sstrerror (errno, errbuf, sizeof (errbuf))
-                               : gai_strerror (ai_return));
-               return (NULL);
+               ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
+                               (se->node == NULL) ? "(null)" : se->node,
+                               (se->service == NULL) ? "(null)" : se->service,
+                               gai_strerror (ai_return));
+               return (-1);
        }
 
        for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
        {
-               sockent_t *se;
                int status;
 
-               if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
+               if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
                {
-                       char errbuf[1024];
-                       ERROR ("malloc: %s",
-                                       sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       continue;
-               }
+                       int *tmp;
 
-               if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
-               {
-                       char errbuf[1024];
-                       ERROR ("malloc: %s",
-                                       sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       free (se);
-                       continue;
-               }
+                       tmp = realloc (se->data.server.fd,
+                                       sizeof (*tmp) * (se->data.server.fd_num + 1));
+                       if (tmp == NULL)
+                       {
+                               ERROR ("network plugin: realloc failed.");
+                               continue;
+                       }
+                       se->data.server.fd = tmp;
+                       tmp = se->data.server.fd + se->data.server.fd_num;
 
-               assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
-               memset (se->addr, '\0', sizeof (struct sockaddr_storage));
-               memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
-               se->addrlen = ai_ptr->ai_addrlen;
+                       *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
+                                       ai_ptr->ai_protocol);
+                       if (*tmp < 0)
+                       {
+                               char errbuf[1024];
+                               ERROR ("network plugin: socket(2) failed: %s",
+                                               sstrerror (errno, errbuf,
+                                                       sizeof (errbuf)));
+                               continue;
+                       }
 
-               se->fd   = socket (ai_ptr->ai_family,
-                               ai_ptr->ai_socktype,
-                               ai_ptr->ai_protocol);
-               se->next = NULL;
+                       status = network_bind_socket (*tmp, ai_ptr);
+                       if (status != 0)
+                       {
+                               close (*tmp);
+                               *tmp = -1;
+                               continue;
+                       }
 
-               if (se->fd == -1)
-               {
-                       char errbuf[1024];
-                       ERROR ("socket: %s",
-                                       sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       free (se->addr);
-                       free (se);
+                       se->data.server.fd_num++;
                        continue;
-               }
-
-               if ((flags & CREATE_SOCKET_FLAGS_LISTEN) != 0)
+               } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
+               else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
                {
-                       status = network_bind_socket (se, ai_ptr);
-                       if (status != 0)
+                       se->data.client.fd = socket (ai_ptr->ai_family,
+                                       ai_ptr->ai_socktype,
+                                       ai_ptr->ai_protocol);
+                       if (se->data.client.fd < 0)
                        {
-                               close (se->fd);
-                               free (se->addr);
-                               free (se);
+                               char errbuf[1024];
+                               ERROR ("network plugin: socket(2) failed: %s",
+                                               sstrerror (errno, errbuf,
+                                                       sizeof (errbuf)));
                                continue;
                        }
-               }
-               else /* sending socket */
-               {
-                       network_set_ttl (se, ai_ptr);
-               }
 
-#if HAVE_GCRYPT_H
-               se->security_level = security_level;
-               se->shared_secret = NULL;
-               se->cypher = NULL;
-               if (shared_secret != NULL)
-               {
-                       se->shared_secret = sstrdup (shared_secret);
-                       assert (se->shared_secret != NULL);
+                       se->data.client.addr = malloc (sizeof (*se->data.client.addr));
+                       if (se->data.client.addr == NULL)
+                       {
+                               ERROR ("network plugin: malloc failed.");
+                               close (se->data.client.fd);
+                               se->data.client.fd = -1;
+                               continue;
+                       }
 
-                       memset (se->shared_secret_hash, 0,
-                                       sizeof (se->shared_secret_hash));
-                       gcry_md_hash_buffer (GCRY_MD_SHA256,
-                                       se->shared_secret_hash,
-                                       se->shared_secret,
-                                       strlen (se->shared_secret));
-               }
-#else
-               /* Make compiler happy */
-               security_level = 0;
-               shared_secret = NULL;
-#endif /* HAVE_GCRYPT_H */
+                       memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
+                       assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
+                       memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
+                       se->data.client.addrlen = ai_ptr->ai_addrlen;
 
-               if (se_tail == NULL)
-               {
-                       se_head = se;
-                       se_tail = se;
-               }
-               else
-               {
-                       se_tail->next = se;
-                       se_tail = se;
-               }
+                       network_set_ttl (se, ai_ptr);
 
-               /* We don't open more than one write-socket per node/service pair.. */
-               if ((flags & CREATE_SOCKET_FLAGS_LISTEN) == 0)
+                       /* We don't open more than one write-socket per
+                        * node/service pair.. */
                        break;
-       }
+               } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
+       } /* for (ai_list) */
 
        freeaddrinfo (ai_list);
 
-       return (se_head);
-} /* }}} sockent_t *network_create_socket */
-
-static sockent_t *network_create_default_socket (int flags) /* {{{ */
-{
-       sockent_t *se_ptr  = NULL;
-       sockent_t *se_head = NULL;
-       sockent_t *se_tail = NULL;
-
-       se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR, NET_DEFAULT_PORT,
-                       /* shared secret = */ NULL, SECURITY_LEVEL_NONE,
-                        flags);
-
-       /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
-       if (((flags & CREATE_SOCKET_FLAGS_LISTEN) == 0) && (se_ptr != NULL))
-               return (se_ptr);
-
-       if (se_ptr != NULL)
+       /* Check if all went well. */
+       if (se->type == SOCKENT_TYPE_SERVER)
        {
-               se_head = se_ptr;
-               se_tail = se_ptr;
-               while (se_tail->next != NULL)
-                       se_tail = se_tail->next;
+               if (se->data.server.fd_num <= 0)
+                       return (-1);
+       }
+       else /* if (se->type == SOCKENT_TYPE_CLIENT) */
+       {
+               if (se->data.client.fd < 0)
+                       return (-1);
        }
 
-       se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT,
-                       /* shared secret = */ NULL, SECURITY_LEVEL_NONE,
-                        flags);
-
-       if (se_tail == NULL)
-               return (se_ptr);
-
-       se_tail->next = se_ptr;
-       return (se_head);
-} /* }}} sockent_t *network_create_default_socket */
+       return (0);
+} /* }}} int sockent_open */
 
-static int network_add_listen_socket (const char *node, /* {{{ */
-    const char *service, const char *shared_secret, int security_level)
+/* Add a sockent to the global list of sockets */
+static int sockent_add (sockent_t *se) /* {{{ */
 {
-       sockent_t *se;
-       sockent_t *se_ptr;
-       int se_num = 0;
-
-        int flags;
-
-        flags = CREATE_SOCKET_FLAGS_LISTEN;
-
-       if (service == NULL)
-               service = NET_DEFAULT_PORT;
-
-       if (node == NULL)
-               se = network_create_default_socket (flags);
-       else
-               se = network_create_socket (node, service,
-                    shared_secret, security_level, flags);
+       sockent_t *last_ptr;
 
        if (se == NULL)
                return (-1);
 
-       for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
-               se_num++;
-
-       listen_sockets_pollfd = realloc (listen_sockets_pollfd,
-                       (listen_sockets_num + se_num)
-                       * sizeof (struct pollfd));
-
-       for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
+       if (se->type == SOCKENT_TYPE_SERVER)
        {
-               listen_sockets_pollfd[listen_sockets_num].fd = se_ptr->fd;
-               listen_sockets_pollfd[listen_sockets_num].events = POLLIN | POLLPRI;
-               listen_sockets_pollfd[listen_sockets_num].revents = 0;
-               listen_sockets_num++;
-       } /* for (se) */
-
-       se_ptr = listen_sockets;
-       while ((se_ptr != NULL) && (se_ptr->next != NULL))
-               se_ptr = se_ptr->next;
-
-       if (se_ptr == NULL)
-               listen_sockets = se;
-       else
-               se_ptr->next = se;
-
-       return (0);
-} /* }}} int network_add_listen_socket */
+               struct pollfd *tmp;
+               size_t i;
 
-static int network_add_sending_socket (const char *node, /* {{{ */
-    const char *service, const char *shared_secret, int security_level)
-{
-       sockent_t *se;
-       sockent_t *se_ptr;
-
-       if (service == NULL)
-               service = NET_DEFAULT_PORT;
+               tmp = realloc (listen_sockets_pollfd,
+                               sizeof (*tmp) * (listen_sockets_num
+                                       + se->data.server.fd_num));
+               if (tmp == NULL)
+               {
+                       ERROR ("network plugin: realloc failed.");
+                       return (-1);
+               }
+               listen_sockets_pollfd = tmp;
+               tmp = listen_sockets_pollfd + listen_sockets_num;
 
-       if (node == NULL)
-               se = network_create_default_socket (/* flags = */ 0);
-       else
-               se = network_create_socket (node, service,
-                               shared_secret, security_level,
-                                /* flags = */ 0);
+               for (i = 0; i < se->data.server.fd_num; i++)
+               {
+                       memset (tmp + i, 0, sizeof (*tmp));
+                       tmp[i].fd = se->data.server.fd[i];
+                       tmp[i].events = POLLIN | POLLPRI;
+                       tmp[i].revents = 0;
+               }
 
-       if (se == NULL)
-               return (-1);
+               listen_sockets_num += se->data.server.fd_num;
 
-       if (sending_sockets == NULL)
+               if (listen_sockets == NULL)
+               {
+                       listen_sockets = se;
+                       return (0);
+               }
+               last_ptr = listen_sockets;
+       }
+       else /* if (se->type == SOCKENT_TYPE_CLIENT) */
        {
-               sending_sockets = se;
-               return (0);
+               if (sending_sockets == NULL)
+               {
+                       sending_sockets = se;
+                       return (0);
+               }
+               last_ptr = sending_sockets;
        }
 
-       for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
-               /* seek end */;
+       while (last_ptr->next != NULL)
+               last_ptr = last_ptr->next;
+       last_ptr->next = se;
 
-       se_ptr->next = se;
        return (0);
-} /* }}} int network_add_sending_socket */
+} /* }}} int sockent_add */
 
 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
 {
@@ -1807,8 +1975,19 @@ static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
 
     /* Look for the correct `sockent_t' */
     se = listen_sockets;
-    while ((se != NULL) && (se->fd != ent->fd))
-           se = se->next;
+    while (se != NULL)
+    {
+      size_t i;
+
+      for (i = 0; i < se->data.server.fd_num; i++)
+        if (se->data.server.fd[i] == ent->fd)
+          break;
+
+      if (i < se->data.server.fd_num)
+        break;
+
+      se = se->next;
+    }
 
     if (se == NULL)
     {
@@ -1826,7 +2005,7 @@ static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
   return (NULL);
 } /* }}} void *dispatch_thread */
 
-static int network_receive (void)
+static int network_receive (void) /* {{{ */
 {
        char buffer[BUFF_SIZE];
        int  buffer_len;
@@ -1837,17 +2016,7 @@ static int network_receive (void)
        receive_list_entry_t *private_list_head;
        receive_list_entry_t *private_list_tail;
 
-       if (listen_sockets_num == 0)
-               network_add_listen_socket (/* node = */ NULL,
-                               /* service = */ NULL,
-                               /* shared secret = */ NULL,
-                               /* encryption = */ 0);
-
-       if (listen_sockets_num == 0)
-       {
-               ERROR ("network: Failed to open a listening socket.");
-               return (-1);
-       }
+        assert (listen_sockets_num > 0);
 
        private_list_head = NULL;
        private_list_tail = NULL;
@@ -1953,7 +2122,7 @@ static int network_receive (void)
        }
 
        return (0);
-} /* int network_receive */
+} /* }}} int network_receive */
 
 static void *receive_thread (void __attribute__((unused)) *arg)
 {
@@ -1976,9 +2145,11 @@ static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
 
        while (42)
        {
-               status = sendto (se->fd, buffer, buffer_size, 0 /* no flags */,
-                               (struct sockaddr *) se->addr, se->addrlen);
-               if (status < 0)
+               status = sendto (se->data.client.fd, buffer, buffer_size,
+                    /* flags = */ 0,
+                    (struct sockaddr *) se->data.client.addr,
+                    se->data.client.addrlen);
+                if (status < 0)
                {
                        char errbuf[1024];
                        if (errno == EINTR)
@@ -1993,95 +2164,126 @@ static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
        } /* while (42) */
 } /* }}} void networt_send_buffer_plain */
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
+#define BUFFER_ADD(p,s) do { \
+  memcpy (buffer + buffer_offset, (p), (s)); \
+  buffer_offset += (s); \
+} while (0)
+
 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
                const char *in_buffer, size_t in_buffer_size)
 {
-       part_signature_sha256_t ps;
-       char buffer[sizeof (ps) + in_buffer_size];
+  part_signature_sha256_t ps;
+  char buffer[BUFF_SIG_SIZE + in_buffer_size];
+  size_t buffer_offset;
+  size_t username_len;
 
-       gcry_md_hd_t hd;
-       gcry_error_t err;
-       unsigned char *hash;
+  gcry_md_hd_t hd;
+  gcry_error_t err;
+  unsigned char *hash;
 
-       hd = NULL;
-       err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
-       if (err != 0)
-       {
-               ERROR ("network plugin: Creating HMAC object failed: %s",
-                               gcry_strerror (err));
-               return;
-       }
+  hd = NULL;
+  err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
+  if (err != 0)
+  {
+    ERROR ("network plugin: Creating HMAC object failed: %s",
+        gcry_strerror (err));
+    return;
+  }
 
-       err = gcry_md_setkey (hd, se->shared_secret,
-                       strlen (se->shared_secret));
-       if (err != 0)
-       {
-               ERROR ("network plugin: gcry_md_setkey failed: %s",
-                               gcry_strerror (err));
-               gcry_md_close (hd);
-               return;
-       }
+  err = gcry_md_setkey (hd, se->data.client.password,
+      strlen (se->data.client.password));
+  if (err != 0)
+  {
+    ERROR ("network plugin: gcry_md_setkey failed: %s",
+        gcry_strerror (err));
+    gcry_md_close (hd);
+    return;
+  }
 
-       /* Initialize the `ps' structure. */
-       memset (&ps, 0, sizeof (ps));
-       ps.head.type = htons (TYPE_SIGN_SHA256);
-       ps.head.length = htons ((uint16_t) sizeof (ps));
+  username_len = strlen (se->data.client.username);
+  if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
+  {
+    ERROR ("network plugin: Username too long: %s",
+        se->data.client.username);
+    return;
+  }
 
-       /* Calculate the hash value. */
-       gcry_md_write (hd, in_buffer, in_buffer_size);
-       hash = gcry_md_read (hd, GCRY_MD_SHA256);
-       if (hash == NULL)
-       {
-               ERROR ("network plugin: gcry_md_read failed.");
-               gcry_md_close (hd);
-               return;
-       }
+  memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
+      se->data.client.username, username_len);
+  memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
+      in_buffer, in_buffer_size);
+
+  /* Initialize the `ps' structure. */
+  memset (&ps, 0, sizeof (ps));
+  ps.head.type = htons (TYPE_SIGN_SHA256);
+  ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
+
+  /* Calculate the hash value. */
+  gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
+      username_len + in_buffer_size);
+  hash = gcry_md_read (hd, GCRY_MD_SHA256);
+  if (hash == NULL)
+  {
+    ERROR ("network plugin: gcry_md_read failed.");
+    gcry_md_close (hd);
+    return;
+  }
+  memcpy (ps.hash, hash, sizeof (ps.hash));
+
+  /* Add the header */
+  buffer_offset = 0;
+
+  BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
+  BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
+  BUFFER_ADD (ps.hash, sizeof (ps.hash));
 
-       /* Add the signature and fill the rest of the buffer. */
-        memcpy (ps.hash, hash, sizeof (ps.hash));
-       memcpy (buffer, &ps, sizeof (ps));
-       memcpy (buffer + sizeof (ps), in_buffer, in_buffer_size);
+  assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
 
-       gcry_md_close (hd);
-       hd = NULL;
+  gcry_md_close (hd);
+  hd = NULL;
 
-       networt_send_buffer_plain (se, buffer, sizeof (buffer));
+  buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
+  networt_send_buffer_plain (se, buffer, buffer_offset);
 } /* }}} void networt_send_buffer_signed */
 
 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
                const char *in_buffer, size_t in_buffer_size)
 {
   part_encryption_aes256_t pea;
-  char buffer[sizeof (pea) + in_buffer_size];
+  char buffer[BUFF_SIG_SIZE + in_buffer_size];
   size_t buffer_size;
   size_t buffer_offset;
-  size_t padding_size;
+  size_t header_size;
+  size_t username_len;
   gcry_error_t err;
   gcry_cipher_hd_t cypher;
 
-  /* Round to the next multiple of 16, because AES has a block size of 128 bit.
-   * the first 20 bytes of `pea' are not encrypted and must be subtracted. */
-  buffer_size = in_buffer_size + 
-    (PART_ENCRYPTION_AES256_SIZE - PART_ENCRYPTION_AES256_UNENCR_SIZE);
-  padding_size = buffer_size;
-  /* Round to the next multiple of 16. */
-  buffer_size = (buffer_size + 15) / 16;
-  buffer_size = buffer_size * 16;
-  /* Calculate padding_size */
-  padding_size = buffer_size - padding_size;
-  assert (padding_size <= sizeof (pea.padding));
-  /* Now add the unencrypted bytes. */
-  buffer_size += PART_ENCRYPTION_AES256_UNENCR_SIZE;
-
   DEBUG ("network plugin: networt_send_buffer_encrypted: "
       "buffer_size = %zu;", buffer_size);
 
   /* Initialize the header fields */
   memset (&pea, 0, sizeof (pea));
   pea.head.type = htons (TYPE_ENCR_AES256);
-  pea.head.length = htons ((uint16_t) buffer_size);
-  pea.orig_length = htons ((uint16_t) in_buffer_size);
+
+  pea.username = se->data.client.username;
+
+  username_len = strlen (pea.username);
+  if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
+  {
+    ERROR ("network plugin: Username too long: %s", pea.username);
+    return;
+  }
+
+  buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
+  header_size = PART_ENCRYPTION_AES256_SIZE + username_len
+    - sizeof (pea.hash);
+
+  assert (buffer_size <= sizeof (buffer));
+
+  pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
+        + username_len + in_buffer_size));
+  pea.username_length = htons ((uint16_t) username_len);
 
   /* Chose a random initialization vector. */
   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
@@ -2089,41 +2291,31 @@ static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
   /* Create hash of the payload */
   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
 
-  /* Fill the extra field with random values. Some entropy in the encrypted
-   * data is usually not a bad thing, I hope. */
-  if (padding_size > 0)
-    gcry_randomize ((void *) &pea.padding, padding_size, GCRY_STRONG_RANDOM);
-
   /* Initialize the buffer */
   buffer_offset = 0;
   memset (buffer, 0, sizeof (buffer));
 
-#define BUFFER_ADD(p,s) do { \
-  memcpy (buffer + buffer_offset, (p), (s)); \
-  buffer_offset += (s); \
-} while (0)
 
   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
+  BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
+  BUFFER_ADD (pea.username, username_len);
   BUFFER_ADD (pea.iv, sizeof (pea.iv));
-  BUFFER_ADD (&pea.orig_length, sizeof (pea.orig_length));
+  assert (buffer_offset == header_size);
   BUFFER_ADD (pea.hash, sizeof (pea.hash));
-
-  if (padding_size > 0)
-    BUFFER_ADD (pea.padding, padding_size);
-
   BUFFER_ADD (in_buffer, in_buffer_size);
 
   assert (buffer_offset == buffer_size);
 
-  cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv));
+  cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
+      se->data.client.password);
   if (cypher == NULL)
     return;
 
   /* Encrypt the buffer in-place */
   err = gcry_cipher_encrypt (cypher,
-      buffer      + PART_ENCRYPTION_AES256_UNENCR_SIZE,
-      buffer_size - PART_ENCRYPTION_AES256_UNENCR_SIZE,
+      buffer      + header_size,
+      buffer_size - header_size,
       /* in = */ NULL, /* in len = */ 0);
   if (err != 0)
   {
@@ -2134,9 +2326,9 @@ static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
 
   /* Send it out without further modifications */
   networt_send_buffer_plain (se, buffer, buffer_size);
-#undef BUFFER_ADD
 } /* }}} void networt_send_buffer_encrypted */
-#endif /* HAVE_GCRYPT_H */
+#undef BUFFER_ADD
+#endif /* HAVE_LIBGCRYPT */
 
 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
 {
@@ -2146,13 +2338,13 @@ static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
 
   for (se = sending_sockets; se != NULL; se = se->next)
   {
-#if HAVE_GCRYPT_H
-    if (se->security_level == SECURITY_LEVEL_ENCRYPT)
+#if HAVE_LIBGCRYPT
+    if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
       networt_send_buffer_encrypted (se, buffer, buffer_len);
-    else if (se->security_level == SECURITY_LEVEL_SIGN)
+    else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
       networt_send_buffer_signed (se, buffer, buffer_len);
-    else /* if (se->security_level == SECURITY_LEVEL_NONE) */
-#endif /* HAVE_GCRYPT_H */
+    else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
+#endif /* HAVE_LIBGCRYPT */
       networt_send_buffer_plain (se, buffer, buffer_len);
   } /* for (sending_sockets) */
 } /* }}} void network_send_buffer */
@@ -2353,7 +2545,31 @@ static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
   return (0);
 } /* }}} int network_config_set_ttl */
 
-#if HAVE_GCRYPT_H
+#if HAVE_LIBGCRYPT
+static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
+    char **ret_string)
+{
+  char *tmp;
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("network plugin: The `%s' config option needs exactly "
+        "one string argument.", ci->key);
+    return (-1);
+  }
+
+  tmp = strdup (ci->values[0].value.string);
+  if (tmp == NULL)
+    return (-1);
+
+  sfree (*ret_string);
+  *ret_string = tmp;
+
+  return (0);
+} /* }}} int network_config_set_string */
+#endif /* HAVE_LIBGCRYPT */
+
+#if HAVE_LIBGCRYPT
 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
     int *retval)
 {
@@ -2381,14 +2597,12 @@ static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
 
   return (0);
 } /* }}} int network_config_set_security_level */
-#endif /* HAVE_GCRYPT_H */
+#endif /* HAVE_LIBGCRYPT */
 
-static int network_config_listen_server (const oconfig_item_t *ci) /* {{{ */
+static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
 {
-  char *node;
-  char *service;
-  char *shared_secret = NULL;
-  int security_level = SECURITY_LEVEL_NONE;
+  sockent_t *se;
+  int status;
   int i;
 
   if ((ci->values_num < 1) || (ci->values_num > 2)
@@ -2400,51 +2614,145 @@ static int network_config_listen_server (const oconfig_item_t *ci) /* {{{ */
     return (-1);
   }
 
-  node = ci->values[0].value.string;
+  se = malloc (sizeof (*se));
+  if (se == NULL)
+  {
+    ERROR ("network plugin: malloc failed.");
+    return (-1);
+  }
+  sockent_init (se, SOCKENT_TYPE_SERVER);
+
+  se->node = strdup (ci->values[0].value.string);
   if (ci->values_num >= 2)
-    service = ci->values[1].value.string;
-  else
-    service = NULL;
+    se->service = strdup (ci->values[1].value.string);
 
   for (i = 0; i < ci->children_num; i++)
   {
     oconfig_item_t *child = ci->children + i;
 
-#if HAVE_GCRYPT_H
-    if (strcasecmp ("Secret", child->key) == 0)
+#if HAVE_LIBGCRYPT
+    if (strcasecmp ("AuthFile", child->key) == 0)
+      network_config_set_string (child, &se->data.server.auth_file);
+    else if (strcasecmp ("SecurityLevel", child->key) == 0)
+      network_config_set_security_level (child,
+          &se->data.server.security_level);
+    else
+#endif /* HAVE_LIBGCRYPT */
     {
-      if ((child->values_num == 1)
-          && (child->values[0].type == OCONFIG_TYPE_STRING))
-        shared_secret = child->values[0].value.string;
-      else
-        ERROR ("network plugin: The `Secret' option needs exactly one string "
-            "argument.");
+      WARNING ("network plugin: Option `%s' is not allowed here.",
+          child->key);
     }
+  }
+
+#if HAVE_LIBGCRYPT
+  if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
+      && (se->data.server.auth_file == NULL))
+  {
+    ERROR ("network plugin: A security level higher than `none' was "
+        "requested, but no AuthFile option was given. Cowardly refusing to "
+        "open this socket!");
+    sockent_destroy (se);
+    return (-1);
+  }
+#endif /* HAVE_LIBGCRYPT */
+
+  status = sockent_open (se);
+  if (status != 0)
+  {
+    ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
+    sockent_destroy (se);
+    return (-1);
+  }
+
+  status = sockent_add (se);
+  if (status != 0)
+  {
+    ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
+    sockent_destroy (se);
+    return (-1);
+  }
+
+  return (0);
+} /* }}} int network_config_add_listen */
+
+static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
+{
+  sockent_t *se;
+  int status;
+  int i;
+
+  if ((ci->values_num < 1) || (ci->values_num > 2)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING)
+      || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
+  {
+    ERROR ("network plugin: The `%s' config option needs "
+        "one or two string arguments.", ci->key);
+    return (-1);
+  }
+
+  se = malloc (sizeof (*se));
+  if (se == NULL)
+  {
+    ERROR ("network plugin: malloc failed.");
+    return (-1);
+  }
+  sockent_init (se, SOCKENT_TYPE_CLIENT);
+
+  se->node = strdup (ci->values[0].value.string);
+  if (ci->values_num >= 2)
+    se->service = strdup (ci->values[1].value.string);
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+#if HAVE_LIBGCRYPT
+    if (strcasecmp ("Username", child->key) == 0)
+      network_config_set_string (child, &se->data.client.username);
+    else if (strcasecmp ("Password", child->key) == 0)
+      network_config_set_string (child, &se->data.client.password);
     else if (strcasecmp ("SecurityLevel", child->key) == 0)
-      network_config_set_security_level (child, &security_level);
+      network_config_set_security_level (child,
+          &se->data.client.security_level);
     else
-#endif /* HAVE_GCRYPT_H */
+#endif /* HAVE_LIBGCRYPT */
     {
       WARNING ("network plugin: Option `%s' is not allowed here.",
           child->key);
     }
   }
 
-  if ((security_level > SECURITY_LEVEL_NONE) && (shared_secret == NULL))
+#if HAVE_LIBGCRYPT
+  if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
+      && ((se->data.client.username == NULL)
+        || (se->data.client.password == NULL)))
   {
     ERROR ("network plugin: A security level higher than `none' was "
-        "requested, but no shared key was given. Cowardly refusing to open "
-        "this socket!");
+        "requested, but no Username or Password option was given. "
+        "Cowardly refusing to open this socket!");
+    sockent_destroy (se);
     return (-1);
   }
+#endif /* HAVE_LIBGCRYPT */
 
-  if (strcasecmp ("Listen", ci->key) == 0)
-    network_add_listen_socket (node, service, shared_secret, security_level);
-  else
-    network_add_sending_socket (node, service, shared_secret, security_level);
+  status = sockent_open (se);
+  if (status != 0)
+  {
+    ERROR ("network plugin: network_config_add_server: sockent_open failed.");
+    sockent_destroy (se);
+    return (-1);
+  }
+
+  status = sockent_add (se);
+  if (status != 0)
+  {
+    ERROR ("network plugin: network_config_add_server: sockent_add failed.");
+    sockent_destroy (se);
+    return (-1);
+  }
 
   return (0);
-} /* }}} int network_config_listen_server */
+} /* }}} int network_config_add_server */
 
 static int network_config_set_cache_flush (const oconfig_item_t *ci) /* {{{ */
 {
@@ -2472,9 +2780,10 @@ static int network_config (oconfig_item_t *ci) /* {{{ */
   {
     oconfig_item_t *child = ci->children + i;
 
-    if ((strcasecmp ("Listen", child->key) == 0)
-        || (strcasecmp ("Server", child->key) == 0))
-      network_config_listen_server (child);
+    if (strcasecmp ("Listen", child->key) == 0)
+      network_config_add_listen (child);
+    else if (strcasecmp ("Server", child->key) == 0)
+      network_config_add_server (child);
     else if (strcasecmp ("TimeToLive", child->key) == 0)
       network_config_set_ttl (child);
     else if (strcasecmp ("Forward", child->key) == 0)
@@ -2588,7 +2897,7 @@ static int network_shutdown (void)
                dispatch_thread_running = 0;
        }
 
-       free_sockent (listen_sockets);
+       sockent_destroy (listen_sockets);
 
        if (send_buffer_fill > 0)
                flush_buffer ();
index 9ee1518..2c92652 100644 (file)
 #endif
 #define _POSIX_C_SOURCE 200112L
 
-#if 0
-/* Single UNIX needed for strdup. */
 #ifdef _XOPEN_SOURCE
 # undef _XOPEN_SOURCE
 #endif
-#define _XOPEN_SOURCE 500
-#endif
+#define _XOPEN_SOURCE 600
 
 #ifndef _REENTRANT
 # define _REENTRANT
index 3f983c8..8502c9d 100644 (file)
 #endif
 #define _POSIX_C_SOURCE 200112L
 
-#if 0
-/* Single UNIX needed for strdup. */
 #ifdef _XOPEN_SOURCE
 # undef _XOPEN_SOURCE
 #endif
-#define _XOPEN_SOURCE 500
-#endif
+#define _XOPEN_SOURCE 600
 
 #ifndef _REENTRANT
 # define _REENTRANT
index 19ff7b9..61b50b6 100644 (file)
 #endif
 #define _POSIX_C_SOURCE 200112L
 
-#if 0
-/* Single UNIX needed for strdup. */
 #ifdef _XOPEN_SOURCE
 # undef _XOPEN_SOURCE
 #endif
-#define _XOPEN_SOURCE 500
-#endif
+#define _XOPEN_SOURCE 600
 
 #ifndef _REENTRANT
 # define _REENTRANT
index e07329c..f8b2f81 100644 (file)
@@ -70,6 +70,7 @@ memory                        value:GAUGE:0:281474976710656
 multimeter             value:GAUGE:U:U
 mysql_commands         value:COUNTER:0:U
 mysql_handler          value:COUNTER:0:U
+mysql_locks            value:COUNTER:0:U
 mysql_log_position     value:COUNTER:0:4294967295
 mysql_octets           rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
 mysql_qcache           hits:COUNTER:0:U, inserts:COUNTER:0:U, not_cached:COUNTER:0:U, lowmem_prunes:COUNTER:0:U, queries_in_cache:GAUGE:0:U
diff --git a/src/utils_fbhash.c b/src/utils_fbhash.c
new file mode 100644 (file)
index 0000000..d20b7e3
--- /dev/null
@@ -0,0 +1,270 @@
+/**
+ * collectd - src/utils_fbhash.c
+ * Copyright (C) 2009  Florian octo Forster
+ *
+ * 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; only version 2 of the License is applicable.
+ *
+ * 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 St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Florian octo Forster <octo at verplant.org>
+ **/
+
+#include "collectd.h"
+#include "plugin.h"
+
+#include <pthread.h>
+
+#include "utils_fbhash.h"
+#include "utils_avltree.h"
+
+struct fbhash_s
+{
+  char *filename;
+  time_t mtime;
+
+  pthread_mutex_t lock;
+  c_avl_tree_t *tree;
+};
+
+/* 
+ * Private functions
+ */
+static void fbh_free_tree (c_avl_tree_t *tree) /* {{{ */
+{
+  int status;
+
+  if (tree == NULL)
+    return;
+
+  while (42)
+  {
+    char *key = NULL;
+    char *value = NULL;
+
+    status = c_avl_pick (tree, (void *) &key, (void *) &value);
+    if (status != 0)
+      break;
+
+    free (key);
+    free (value);
+  }
+
+  c_avl_destroy (tree);
+} /* }}} void fbh_free_tree */
+
+static int fbh_read_file (fbhash_t *h) /* {{{ */
+{
+  FILE *fh;
+  char buffer[4096];
+  struct flock fl;
+  c_avl_tree_t *tree;
+  int status;
+
+  fh = fopen (h->filename, "r");
+  if (fh == NULL)
+    return (-1);
+
+  memset (&fl, 0, sizeof (fl));
+  fl.l_type = F_RDLCK;
+  fl.l_whence = SEEK_SET;
+  fl.l_start = 0;
+  fl.l_len = 0; /* == entire file */
+  /* TODO: Lock file? -> fcntl */
+
+  status = fcntl (fileno (fh), F_SETLK, &fl);
+  if (status != 0)
+  {
+    fclose (fh);
+    return (-1);
+  }
+
+  tree = c_avl_create ((void *) strcmp);
+  if (tree == NULL)
+  {
+    fclose (fh);
+    return (-1);
+  }
+
+  /* Read `fh' into `tree' */
+  while (fgets (buffer, sizeof (buffer), fh) != NULL) /* {{{ */
+  {
+    size_t len;
+    char *key;
+    char *value;
+
+    char *key_copy;
+    char *value_copy;
+
+    buffer[sizeof (buffer) - 1] = 0;
+    len = strlen (buffer);
+
+    /* Remove trailing newline characters. */
+    while ((len > 0)
+        && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
+    {
+      len--;
+      buffer[len] = 0;
+    }
+
+    /* Seek first non-space character */
+    key = buffer;
+    while ((*key != 0) && isspace ((int) *key))
+      key++;
+
+    /* Skip empty lines and comments */
+    if ((key[0] == 0) || (key[0] == '#'))
+      continue;
+
+    /* Seek first colon */
+    value = strchr (key, ':');
+    if (value == NULL)
+      continue;
+
+    /* Null-terminate `key'. */
+    *value = 0;
+    value++;
+
+    /* Skip leading whitespace */
+    while ((*value != 0) && isspace ((int) *value))
+      value++;
+
+    /* Skip lines without value */
+    if (value[0] == 0)
+      continue;
+
+    key_copy = strdup (key);
+    value_copy = strdup (value);
+
+    if ((key_copy == NULL) || (value_copy == NULL))
+    {
+      free (key_copy);
+      free (value_copy);
+      continue;
+    }
+
+    status = c_avl_insert (tree, key_copy, value_copy);
+    if (status != 0)
+    {
+      free (key_copy);
+      free (value_copy);
+      continue;
+    }
+
+    DEBUG ("utils_fbhash: fbh_read_file: key = %s; value = %s;",
+        key, value);
+  } /* }}} while (fgets) */
+
+  fclose (fh);
+
+  fbh_free_tree (h->tree);
+  h->tree = tree;
+
+  return (0);
+} /* }}} int fbh_read_file */
+
+static int fbh_check_file (fbhash_t *h) /* {{{ */
+{
+  struct stat statbuf;
+  int status;
+
+  memset (&statbuf, 0, sizeof (statbuf));
+
+  status = stat (h->filename, &statbuf);
+  if (status != 0)
+    return (-1);
+
+  if (h->mtime >= statbuf.st_mtime)
+    return (0);
+
+  status = fbh_read_file (h);
+  if (status == 0)
+    h->mtime = statbuf.st_mtime;
+
+  return (status);
+} /* }}} int fbh_check_file */
+
+/* 
+ * Public functions
+ */
+fbhash_t *fbh_create (const char *file) /* {{{ */
+{
+  fbhash_t *h;
+  int status;
+
+  if (file == NULL)
+    return (NULL);
+
+  h = malloc (sizeof (*h));
+  if (h == NULL)
+    return (NULL);
+  memset (h, 0, sizeof (*h));
+
+  h->filename = strdup (file);
+  if (h->filename == NULL)
+  {
+    free (h);
+    return (NULL);
+  }
+
+  h->mtime = 0;
+  pthread_mutex_init (&h->lock, /* attr = */ NULL);
+
+  status = fbh_check_file (h);
+  if (status != 0)
+  {
+    fbh_destroy (h);
+    return (NULL);
+  }
+
+  return (h);
+} /* }}} fbhash_t *fbh_create */
+
+void fbh_destroy (fbhash_t *h) /* {{{ */
+{
+  if (h == NULL)
+    return;
+
+  free (h->filename);
+  fbh_free_tree (h->tree);
+} /* }}} void fbh_destroy */
+
+char *fbh_get (fbhash_t *h, const char *key) /* {{{ */
+{
+  char *value;
+  char *value_copy;
+  int status;
+
+  if ((h == NULL) || (key == NULL))
+    return (NULL);
+
+  value = NULL;
+  value_copy = NULL;
+
+  pthread_mutex_lock (&h->lock);
+
+  /* TODO: Checking this everytime may be a bit much..? */
+  fbh_check_file (h);
+
+  status = c_avl_get (h->tree, key, (void *) &value);
+  if (status == 0)
+  {
+    assert (value != NULL);
+    value_copy = strdup (value);
+  }
+
+  pthread_mutex_unlock (&h->lock);
+
+  return (value_copy);
+} /* }}} char *fbh_get */
+
+/* vim: set sw=2 sts=2 et fdm=marker : */
diff --git a/src/utils_fbhash.h b/src/utils_fbhash.h
new file mode 100644 (file)
index 0000000..0a0305e
--- /dev/null
@@ -0,0 +1,47 @@
+/**
+ * collectd - src/utils_fbhash.h
+ * Copyright (C) 2009  Florian octo Forster
+ *
+ * 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; only version 2 of the License is applicable.
+ *
+ * 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 St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Florian octo Forster <octo at verplant.org>
+ **/
+
+#ifndef UTILS_FBHASH_H
+#define UTILS_FBHASH_H 1
+
+/*
+ * File-backed hash
+ *
+ * This module reads a file of the form
+ *   key: value
+ * into a hash, which can then be queried. The file is given to `fbh_create',
+ * the hash is queried using `fbh_get'. If the file is changed during runtime,
+ * it will automatically be re-read.
+ */
+
+struct fbhash_s;
+typedef struct fbhash_s fbhash_t;
+
+fbhash_t *fbh_create (const char *file);
+void fbh_destroy (fbhash_t *h);
+
+/* Returns the value as a newly allocated `char *'. It's the caller's
+ * responsibility to free this memory. */
+char *fbh_get (fbhash_t *h, const char *key);
+
+#endif /* UTILS_FBHASH_H */
+
+/* vim: set sw=2 sts=2 et fdm=marker : */
index a39c869..a32a6fe 100644 (file)
@@ -133,7 +133,7 @@ int match_apply (cu_match_t *obj, const char *str);
  *
  * DESCRIPTION
  *  Returns the pointer passed to `match_create_callback' or a pointer to the
- *  `cu_match_value_t' structure allocated by `match_create_callback'.
+ *  `cu_match_value_t' structure allocated by `match_create_simple'.
  */
 void *match_get_user_data (cu_match_t *obj);