Commit Graph

542 Commits

Author SHA1 Message Date
Wei Jiangang
c3d4eb124c Fix conficts with HACKING doc
Don't compare a bool variable against the literal, "true".

Signed-off-by: Wei Jiangang <weijg.fnst@cn.fujitsu.com>
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-10-15 11:31:27 +02:00
Erik Skultety
152e315433 nwfilter: Fix sscanf off-by-one error in virNWFilterSnoopLeaseFileLoad
We allocate 16 bytes for IPv4 address and 55 bytes for interface
key, therefore we should read up to 15/54 bytes and let the last byte
reserved for terminating null byte in sscanf.

https://bugzilla.redhat.com/show_bug.cgi?id=1226400
2015-06-02 10:16:29 +02:00
Michal Privoznik
77d92e2e77 nwfilter: Partly initialize driver even for non-privileged users
https://bugzilla.redhat.com/show_bug.cgi?id=1211436

This reverts commit b7829f959b.

The previous fix was not correct. Like everywhere else, a driver is a
global variable allocated in stateInitialize function (or something
similar for stateless drivers). Later, when a driver API is called,
it's possible that the global variable is accessed and dereferenced.
Now, some drivers require root privileges because they undertake some
actions reserved only for the system admin (e.g. manipulating host
firewall). And here's the trouble, the NWFilter state initializer
exited too early when finding out it's running unprivileged, leaving
the global NWFilter driver variable uninitialized. Any subsequent
API call that tried to lock the driver resulted in dereferencing the
driver and thus crash.

On the other hand, in order to not resurrect the bug the original
commit was fixing, Let's forbid the nwfilter define in session mode.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>

Conflicts:
	src/nwfilter/nwfilter_driver.c: Context. Code changed a bit
        since 2013.
2015-04-17 10:04:05 +02:00
Jiri Denemark
23d0c979f7 Force usage of virThreadCreate
We want all threads to be set as workers or to have a job assigned to
them, which can easily be achieved in virThreadCreate wrapper to
pthread_create. Let's make sure we always use the wrapper.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-03-25 10:00:53 +01:00
Daniel P. Berrange
55ea7be7d9 Removing probing of secondary drivers
For stateless, client side drivers, it is never correct to
probe for secondary drivers. It is only ever appropriate to
use the secondary driver that is associated with the
hypervisor in question. As a result the ESX & HyperV drivers
have both been forced to do hacks where they register no-op
drivers for the ones they don't implement.

For stateful, server side drivers, we always just want to
use the same built-in shared driver. The exception is
virtualbox which is really a stateless driver and so wants
to use its own server side secondary drivers. To deal with
this virtualbox has to be built as 3 separate loadable
modules to allow registration to work in the right order.

This can all be simplified by introducing a new struct
recording the precise set of secondary drivers each
hypervisor driver wants

struct _virConnectDriver {
    virHypervisorDriverPtr hypervisorDriver;
    virInterfaceDriverPtr interfaceDriver;
    virNetworkDriverPtr networkDriver;
    virNodeDeviceDriverPtr nodeDeviceDriver;
    virNWFilterDriverPtr nwfilterDriver;
    virSecretDriverPtr secretDriver;
    virStorageDriverPtr storageDriver;
};

Instead of registering the hypervisor driver, we now
just register a virConnectDriver instead. This allows
us to remove all probing of secondary drivers. Once we
have chosen the primary driver, we immediately know the
correct secondary drivers to use.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2015-01-27 12:02:04 +00:00
Daniel P. Berrange
7b1ba9566b Remove use of nwfilterPrivateData from nwfilter driver
The nwfilter driver can rely on its global state instead
of the connect private data.
2015-01-27 12:02:03 +00:00
Stefan Berger
3a3b3691d1 nwfilter: Add support for icmpv6 filtering
Make use of the ebtables functionality to be able to filter certain
parameters of icmpv6 packets. Extend the XML parser for icmpv6 types,
type ranges, codes, and code ranges. Extend the nwfilter documentation,
schema, and test cases.

Being able to filter icmpv6 types and codes helps extending the DHCP
snooper for IPv6 and filtering at least some parameters of IPv6's NDP
(Neighbor Discovery Protocol) packets. However, the filtering will not
be as good as the filtering of ARP packets since we cannot
check on IP addresses in the payload of the NDP packets.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2015-01-07 11:41:49 -05:00
John Ferlan
7b4938f524 Replace virNWFilterFree with virObjectUnref
Since virNWFilterFree will call virObjectUnref anyway, let's just use that
directly so as to avoid the possibility that we inadvertently clear out
a pending error message when using the public API.
2014-12-02 11:03:41 -05:00
Martin Kletzander
138c2aee01 Remove unnecessary curly brackets in rest of src/[a-n]*/
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-11-14 17:13:36 +01:00
Eric Blake
ff99c79195 maint: avoid static zero init in helpers
C guarantees that static variables are zero-initialized.  Some older
compilers (and also gcc -fno-zero-initialized-in-bss) create larger
binaries if you explicitly zero-initialize a static variable.

* src/conf/nwfilter_conf.c: Fix initialization.
* src/cpu/cpu_x86.c: Likewise.
* src/interface/interface_backend_netcf.c: Likewise.
* src/locking/lock_daemon.c: Likewise.
* src/locking/lock_driver_lockd.c: Likewise.
* src/locking/lock_driver_sanlock.c: Likewise.
* src/network/bridge_driver.c: Likewise.
* src/node_device/node_device_udev.c: Likewise.
* src/nwfilter/nwfilter_learnipaddr.c: Likewise.
* src/rpc/virnetserver.c: Likewise.
* src/security/security_selinux.c
(virSecuritySELinuxGenSecurityLabel): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-10-29 09:55:09 -06:00
Eric Blake
ff78ff7c93 maint: use consistent if-else braces in conf and friends
I'm about to add a syntax check that enforces our documented
HACKING style of always using matching {} on if-else statements.

This patch focuses on code shared between multiple drivers.

* src/conf/domain_conf.c (virDomainFSDefParseXML)
(virSysinfoParseXML, virDomainNetDefParseXML)
(virDomainWatchdogDefParseXML)
(virDomainRedirFilterUSBDevDefParseXML): Correct use of {}.
* src/conf/interface_conf.c (virInterfaceDefParseDhcp)
(virInterfaceDefParseIp, virInterfaceVlanDefFormat)
(virInterfaceDefParseStartMode, virInterfaceDefParseBondMode)
(virInterfaceDefParseBondMiiCarrier)
(virInterfaceDefParseBondArpValid): Likewise.
* src/conf/node_device_conf.c (virNodeDevCapStorageParseXML):
Likewise.
* src/conf/nwfilter_conf.c (virNWFilterRuleDetailsParse)
(virNWFilterRuleParse, virNWFilterDefParseXML): Likewise.
* src/conf/secret_conf.c (secretXMLParseNode): Likewise.
* src/cpu/cpu_x86.c (x86Baseline, x86FeatureLoad, x86ModelLoad):
Likewise.
* src/network/bridge_driver.c (networkKillDaemon)
(networkDnsmasqConfContents): Likewise.
* src/node_device/node_device_hal.c (dev_refresh): Likewise.
* src/nwfilter/nwfilter_gentech_driver.c (virNWFilterInstantiate):
Likewise.
* src/nwfilter/nwfilter_ebiptables_driver.c
(_iptablesCreateRuleInstance): Likewise.
* src/storage/storage_backend_disk.c
(virStorageBackendDiskBuildPool): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-09-04 08:53:21 -06:00
Michal Privoznik
66eaa887e9 Fix spacing around commas
On some places in the libvirt code we have:

  f(a,z)

instead of

  f(a, z)

This trivial patch fixes couple of such occurrences.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-08-22 15:03:39 +02:00
Eric Blake
ee70839bbf nwfilter: plug memory leak with firewall
Introduced in commit 70571ccc (v1.2.4). Caught by valgrind:

==9816== 170 (32 direct, 138 indirect) bytes in 1 blocks are definitely lost in loss record 646 of 821
==9816==    at 0x4A081D4: calloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==9816==    by 0x50836FB: virAlloc (viralloc.c:144)
==9816==    by 0x50AEC2B: virFirewallNew (virfirewall.c:204)
==9816==    by 0x1E2308ED: ebiptablesDriverProbeStateMatch (nwfilter_ebiptables_driver.c:3715)
==9816==    by 0x1E2309AD: ebiptablesDriverInit (nwfilter_ebiptables_driver.c:3742)

* src/nwfilter/nwfilter_ebiptables_driver.c
(ebiptablesDriverProbeStateMatch): Properly clean up.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-07-23 13:15:14 -06:00
Ján Tomko
92a8e72f9d Use virBufferCheckError everywhere we report OOM error
Replace:
if (virBufferError(&buf)) {
    virBufferFreeAndReset(&buf);
    virReportOOMError();
    ...
}

with:
if (virBufferCheckError(&buf) < 0)
    ...

This should not be a functional change (unless some callers
misused the virBuffer APIs - a different error would be reported
then)
2014-07-03 10:48:14 +02:00
Ján Tomko
275f022454 More indentation fixes
Reindent nwfilter gentech driver and one block in rbd storage backend.
2014-07-03 10:41:15 +02:00
Stefan Berger
cdebc2f74c nwfilter: Tear down temp. filters when tearing all filters
Refactor the ebiptablesTearNewRules function so that the teardown of temporary
filters can also be called by the ebiptablesAllTeardown function.

This fixes a problem that leaves temporary filters behind when a VM shuts down
while its filters are modified.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>

v1->v2:
  - test cases adjusted to expect more commands
2014-04-30 12:51:38 -04:00
Daniel P. Berrange
4131bff5b7 Remove last trace of direct firewall command exection
Remove all the left over code related to the direct invocation
of firewall-cmd/iptables/ip6tables/ebtables. This is all handled
by the virFirewallPtr APIs now.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
70571ccc98 Convert ebiptablesDriverProbeStateMatch to virFirewall
Conver the ebiptablesDriverProbeStateMatch initialization
check to use the virFirewall APIs for querying iptables
version.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
001130c096 Convert nwfilter ebiptablesApplyNewRules to virFirewall
Convert the nwfilter ebtablesApplyNewRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
051eb0238a Convert nwfilter ebtablesApplyDropAllRules to virFirewall
Convert the nwfilter ebtablesApplyDropAllRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
423735d763 Convert nwfilter ebtablesApplyDHCPOnlyRules to virFirewall
Convert the nwfilter ebtablesApplyDHCPOnlyRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
d01eb15303 Convert nwfilter ebtablesApplyBasicRules to virFirewall
Convert the nwfilter ebtablesApplyBasicRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
138ef25e99 Convert nwfilter ebiptablesTearNewRules to virFirewall
Convert the nwfilter ebiptablesTearNewRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:10 +01:00
Daniel P. Berrange
d7b83ab7c3 Convert nwfilter ebtablesRemoveBasicRules to virFirewall
Convert the nwfilter ebtablesRemoveBasicRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
3010fae592 Convert nwfilter ebiptablesTearOldRules to virFirewall
Convert the nwfilter ebiptablesTearOldRules method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
8d55986427 Convert nwfilter ebiptablesAllTeardown to virFirewall
Convert the nwfilter ebiptablesAllTeardown method to use the
virFirewall object APIs instead of creating shell scripts
using virBuffer APIs. This provides a performance improvement
through allowing direct use of firewalld dbus APIs and will
facilitate automated testing.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
b1c1df05bf Remove two-stage construction of commands in nwfilter
The nwfilter ebiptables driver will build up commands to run in
two phases. The first phase contains all of the command, except
for the '-A' part. Instead it has a '%c' placeholder, along with
a '%s' placeholder for a position arg. The second phase than
substitutes these placeholders. The only values ever used for
these substitutions though is '-A' and '', so it is entirely
pointless. Remove the second phase entirely, since it will make
it harder to convert to the new firewall APIs

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
3f74b2eb2c Merge nwfilter createRuleInstance driver into applyNewRules
The current nwfilter tech driver API has a 'createRuleInstance' method
which populates virNWFilterRuleInstPtr with a command line string
containing variable placeholders. The 'applyNewRules' method then
expands the variables and executes the commands. This split of
responsibility won't work when switching to the virFirewallPtr
APIs, since we can't just build up command line strings. This patch
this merges the functionality of 'createRuleInstance' into the
applyNewRules method.

The virNWFilterRuleInstPtr struct is changed from holding an array
of opaque pointers, into holding generic metadata about the rules
to be processed. In essence this is the result of taking a linked
set of virNWFilterDefPtr's and flattening the tree to get a list
of virNWFilterRuleDefPtr's. At the same time we must keep track of
any nested virNWFilterObjPtr instances, so that the locks are held
for the duration of the 'applyNewRules' method.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
4dd7eaa36f Push virNWFilterRuleInstPtr out of (eb|ip)tablesCreateRuleInstance
Later refactoring will change use of the virNWFilterRuleInstPtr struct.
Prepare for this by pushing use of the virNWFilterRuleInstPtr parameter
out of the ebtablesCreateRuleInstance and iptablesCreateRuleInstance
methods. Instead they simply string(s) with the constructed rule data.
The ebiptablesCreateRuleInstance method will make use of the
virNWFilterRuleInstPtr struct instead.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
23b1d0c07d Add helper methods for determining what protocol layer is used
Add virNWFilterRuleIsProtocol{Ethernet,IPv4,IPv6} helper methods
to avoid having to write a giant switch statements with many cases.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
143a8a3038 Remove nwfilter tech driver 'displayRuleInstance' callback
The 'displayRuleInstance' callback in the nwfilter tech driver
is never invoked, so can be deleted.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
9b8aef1a02 Remove nwfilter tech driver 'removeRules' callback
The 'removeRules' callback in the nwfilter tech driver is never
invoked, so can be deleted.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
293d4fe2f1 Remove pointless storage of var names in virNWFilterHashTable
The virNWFilterHashTable struct contains a virHashTable and
then a 'char **names' field which keeps a copy of all the
hash keys. Presumably this was intended to record the ordering
of the hash keys. No code ever uses this and the ordering is
mangled whenever a variable is removed from the hash, because
the last element in the list is copied into the middle of the
list when shrinking the array.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
50859fc1dd Remove virDomainNetType parameter from nwfilter drivers
The 'virDomainNetType' is unused in every impl of the
virNWFilterRuleCreateInstance driver method. Remove it
from the code to avoid the dependancy on the external
enum.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
bc46c7fb92 Move virNWFilterTechDriver struct out of nwfilter_conf.h
The virNWFilterTechDriver struct is nothing to do with the nwfilter
XML configuration. It stores data specific to the driver implementation
so should be in a header in the driver directory instead.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
3f671e6c52 Use a static initializer for static mutexes
Now that we ditched our custom pthread impl for Win32, we can
use PTHREAD_MUTEX_INITIALIZER for static mutexes. This avoids
the need to use a virOnce one-time global initializer in a
number of places.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-08 13:46:29 +01:00
Eric Blake
09567144d6 hash: add common utility functions
I almost wrote a hash value free function that just called
VIR_FREE, then realized I couldn't be the first person to
do that.  Sure enough, it was worth factoring into a common
helper routine.

* src/util/virhash.h (virHashValueFree): New function.
* src/util/virhash.c (virHashValueFree): Implement it.
* src/util/virobject.h (virObjectFreeHashData): New function.
* src/libvirt_private.syms (virhash.h, virobject.h): Export them.
* src/nwfilter/nwfilter_learnipaddr.c (virNWFilterLearnInit): Use
common function.
* src/qemu/qemu_capabilities.c (virQEMUCapsCacheNew): Likewise.
* src/qemu/qemu_command.c (qemuDomainCCWAddressSetCreate):
Likewise.
* src/qemu/qemu_monitor.c (qemuMonitorGetBlockInfo): Likewise.
* src/qemu/qemu_process.c (qemuProcessWaitForMonitor): Likewise.
* src/util/virclosecallbacks.c (virCloseCallbacksNew): Likewise.
* src/util/virkeyfile.c (virKeyFileParseGroup): Likewise.
* tests/qemumonitorjsontest.c
(testQemuMonitorJSONqemuMonitorJSONGetBlockInfo): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-04-07 06:14:45 -06:00
Ján Tomko
5d8315975e Indent top-level labels by one space in src/nwfilter/ 2014-03-25 14:58:39 +01:00
Martin Kletzander
58d467116b Use K&R style for curly braces in src/nwfilter/
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-03-20 17:16:38 +01:00
Stefan Berger
963dcf905c nwfilter: Fix double free of pointer
https://bugzilla.redhat.com/show_bug.cgi?id=1071181

Commit 49b59a15 fixed one problem but masks another one related to pointer
freeing.

Avoid putting of the virNWFilterSnoopReq once the thread has been started.
It belongs to the thread and the thread will call virNWFilterSnoopReqPut() on it.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-19 13:38:44 -04:00
Daniel P. Berrange
df3a681c03 Change CMD_STOPONERR(1) to use true
The CMD_STOPONERR macro uses its parameter as a boolean, so should
be passed true rather than 1.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:27 +00:00
Daniel P. Berrange
7dd1c91a11 Change 'int isTempChain' to bool in nwfilter
The 'int isTempChain' parameter to various nwfilter methods
only takes two values so should be a bool type.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:27 +00:00
Daniel P. Berrange
741c855e0e Remove pointless return values in nwfilter methods
Many nwfilter methods have an int return value but only ever
return 0 and their callers never check the return value either.
These methods can all be void.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:27 +00:00
Daniel P. Berrange
2b42e17c7e Remove 'int stopOnError' parameters in nwfilter methods
Many nwfilter methods have an 'int stopOnError' parameter but
with 1 exception, the callers always pass '1'. The parameter
can therefore be removed from all except one method. That method
will be changed to 'bool stopOnError'

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:27 +00:00
Daniel P. Berrange
6c582bb9c6 Remove pointless brackets around boolean
A lot of methods have a 'bool incoming' parameter but then
do  (incoming) ? ... : .... The round brackets here add nothing
to the code so can be removed.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:27 +00:00
Daniel P. Berrange
7f66afceda Change 'int incoming' to 'bool incoming' in nwfilter code
Many methods in the nwfilter code have an 'int incoming' parameter
that only takes 0 or 1, so should use a bool instead.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:27 +00:00
Daniel P. Berrange
2835c1e730 Add virLogSource variables to all source files
Any source file which calls the logging APIs now needs
to have a VIR_LOG_INIT("source.name") declaration at
the start of the file. This provides a static variable
of the virLogSource type.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:22 +00:00
Daniel P. Berrange
ef2c4c965b Give virNWFilterVarCombIterNext saner semantics
The virNWFilterVarCombIterNext method will free its
parameter when it gets to the end of the iterator.
This is somewhat misleading design, making it appear
as if the caller has a memory leak. Remove the free'ing
of the parameter and ensure that the calling method
ebiptablesCreateRuleInstanceIterate free's it instead.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-17 17:08:54 +00:00
Daniel P. Berrange
9f7da130f4 Fix leak on OOM when creating nwfilter rule instances
The ebiptablesAddRuleInst method would leak an instance
of ebiptablesRuleInstPtr if it hit OOM when adding it
to the list of instances. Remove the pointless helper
method virNWFilterRuleInstAddData and just inline the
call to VIR_APPEND_ELEMENT and free the instance on
failure.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-17 17:08:54 +00:00
Daniel P. Berrange
cb873e9d15 Fix mistakes in checking return values
Thre was a syntax error in checking virRegisterStateDriver in
the remote driver, and bogus checking of a void return type
of virDomainConfNWFilterRegister in nwfilter.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-17 15:48:49 +00:00
Pavel Hrdina
b396fae9e2 Fix issue found by coverity and cleanup
Coverity found an issue in lxc_driver and uml_driver that we don't
check the return value of register functions.

I've also updated all other places and unify the way we check the
return value.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2014-03-17 15:02:51 +01:00
Stefan Berger
a81756f1ff nwfilter: Add ARP src/dst IP mask for ebtables ARP
Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=862887

Add a netmask for the source and destination IP address for the
ebtables --arp-ip-src and --arp-ip-dst options. Extend the XML
parser with support for XML attributes for these netmasks similar
to already supported netmasks. Extend the documentation.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-13 18:30:09 -04:00
Stefan Berger
5a2b17beb8 nwfilter: Fix rule priority problem
Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1072292

Fix a problem related to rule priorities that did not allow to
have rules applied that had a higher priority than the chain they
were in. In this case the chain did not exist yet when the rule
was instantiated. The solution is to adjust the priority of rules
if the priority of the chain is of higher value. That way the chain
will be created before the rule.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-13 18:30:09 -04:00
Stefan Berger
41064facd4 nwfilter: Add missing goto err_exit in error path
https://bugzilla.redhat.com/show_bug.cgi?id=1071095

Add a missing goto err_exit in the error path where an unsupported
value is assigned to the CTRL_IP_LEARNING key.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-12 10:35:13 -04:00
Michal Privoznik
6c1bde6a94 src/nwfilter: Utilize more of VIR_(APPEND|INSERT|DELETE)_ELEMENT
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-03-10 13:45:10 +01:00
Daniel P. Berrange
925de19ed7 Add a mutex to serialize updates to firewall
The nwfilter conf update mutex previously serialized
updates to the internal data structures for firewall
rules, and updates to the firewall itself. The latter
was recently turned into a read/write lock, and filter
instantiation allowed to proceed in parallel. It was
believed that this was ok, since each filter is created
on a separate iptables/ebtables chain.

It turns out that there is a subtle lock ordering problem
on virNWFilterObjPtr instances. __virNWFilterInstantiateFilter
will hold a lock on the virNWFilterObjPtr it is instantiating.
This in turn invokes virNWFilterInstantiate which then invokes
virNWFilterDetermineMissingVarsRec which then invokes
virNWFilterObjFindByName. This iterates over every single
virNWFilterObjPtr in the list, locking them and checking their
name. So if 2 or more threads try to instantiate a filter in
parallel, they'll all hold 1 lock at the top level in the
__virNWFilterInstantiateFilter method which will cause the
other thread to deadlock in virNWFilterObjFindByName.

The fix is to add an exclusive mutex to serialize the
execution of __virNWFilterInstantiateFilter.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-10 11:56:45 +00:00
Eric Blake
b75c7bd6b9 build: fix cppi warning
Jenkins pointed out that the previous commit violates syntax
check when cppi is installed.

* src/nwfilter/nwfilter_dhcpsnoop.c (SNOOP_POLL_MAX_TIMEOUT_MS):
Update indentation.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 14:02:42 -07:00
Stefan Berger
49b59a151f nwfilter: Increase buffer size for libpcap
Libpcap 1.5 requires a larger buffer than previous pcap versions.
Adjust the size of the buffer to 128kb.

This patch should address symptoms in BZ 1071181 and BZ 731059

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-03 15:13:50 -05:00
Stefan Berger
64df4c7518 nwfilter: Display the pcap errror message
Display the pcap error message in the log.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-03 15:13:47 -05:00
Stefan Berger
a718eb19e3 nwfilter: Cap the poll timeout in the DHCP Snooping code
Cap the poll timeout in the DHCP Snooping code to a max. of 10 seconds
to not hold up the libvirt shutdown longer than this.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2014-03-03 15:13:44 -05:00
Eric Blake
f972a7c72c nwfilter: make ignoring non-zero status easier to follow
While auditing all callers of virCommandRun, I noticed that nwfilter
code never paid attention to commands with a non-zero status; they
were merely passing a pointer to avoid spamming the logs with a
message about commands that might indeed fail.  But proving this
required chasing through a lot of code; refactoring things to
localize the decision of whether to ignore non-zero status makes
it easier to prove that later changes to virFork don't negatively
affect this code.

While at it, I also noticed that ebiptablesRemoveRules would
actually report success if the child process failed for a
reason other than non-zero status, such as OOM.

* src/nwfilter/nwfilter_ebiptables_driver.c (ebiptablesExecCLI):
Change parameter from pointer to bool.
(ebtablesApplyBasicRules, ebtablesApplyDHCPOnlyRules)
(ebtablesApplyDropAllRules, ebtablesCleanAll)
(ebiptablesApplyNewRules, ebiptablesTearNewRules)
(ebiptablesTearOldRules, ebiptablesAllTeardown)
(ebiptablesDriverInitWithFirewallD)
(ebiptablesDriverTestCLITools, ebiptablesDriverProbeStateMatch):
Adjust all clients.
(ebiptablesRemoveRules): Likewise, and fix return value on failure.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:31 -07:00
Daniel P. Berrange
6e5c79a1b5 Push nwfilter update locking up to top level
The NWFilter code has as a deadlock race condition between
the virNWFilter{Define,Undefine} APIs and starting of guest
VMs due to mis-matched lock ordering.

In the virNWFilter{Define,Undefine} codepaths the lock ordering
is

  1. nwfilter driver lock
  2. virt driver lock
  3. nwfilter update lock
  4. domain object lock

In the VM guest startup paths the lock ordering is

  1. virt driver lock
  2. domain object lock
  3. nwfilter update lock

As can be seen the domain object and nwfilter update locks are
not acquired in a consistent order.

The fix used is to push the nwfilter update lock upto the top
level resulting in a lock ordering for virNWFilter{Define,Undefine}
of

  1. nwfilter driver lock
  2. nwfilter update lock
  3. virt driver lock
  4. domain object lock

and VM start using

  1. nwfilter update lock
  2. virt driver lock
  3. domain object lock

This has the effect of serializing VM startup once again, even if
no nwfilters are applied to the guest. There is also the possibility
of deadlock due to a call graph loop via virNWFilterInstantiate
and virNWFilterInstantiateFilterLate.

These two problems mean the lock must be turned into a read/write
lock instead of a plain mutex at the same time. The lock is used to
serialize changes to the "driver->nwfilters" hash, so the write lock
only needs to be held by the define/undefine methods. All other
methods can rely on a read lock which allows good concurrency.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-01-30 18:00:20 +00:00
Thorsten Behrens
721949059b maint: align whitespaces with project conventions. 2014-01-20 14:35:08 +01:00
Daniel P. Berrange
147a3d2487 Remove stray semicolon after pragma macros
The VIR_WARNINGS_NO_CAST_ALIGN / VIR_WARNINGS_RESET should
not have any trailing ';' since they are pragmas. The use
of a ';' results in an empty statement which confuses CIL.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-12-19 16:02:38 +00:00
John Ferlan
5a298ec040 nwfilter: Remove Coverity DEADCODE warning
The nwfilterStateInitialize() would only assign sysbus inside
a WITH_DBUS conditional, thus leaving a subsequent check for sysbus
and nwfilterDriverInstallDBusMatches() as a no-op

Rather than try to add WITH_DBUS conditions which ended up conflicting
with the usage of HAVE_FIREWALLD conditionals, just remove the WITH_DBUS
since virdbus.c has entry points for with and without conditions.
2013-12-04 06:27:19 -05:00
Eric Blake
f56903366f maint: fix comma style issues: nwfilter
Most of our code base uses space after comma but not before;
fix the remaining uses before adding a syntax check.

* src/nwfilter/nwfilter_ebiptables_driver.c: Consistently use
commas.
* src/nwfilter/nwfilter_gentech_driver.c: Likewise.
* src/nwfilter/nwfilter_learnipaddr.c: Likewise.
* src/conf/nwfilter_conf.c: Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-11-20 09:14:54 -07:00
Ján Tomko
b7829f959b Disable nwfilter driver when running unprivileged
When opening a new connection to the driver, nwfilterOpen
only succeeds if the driverState has been allocated.

Move the privilege check in driver initialization before
the state allocation to disable the driver.

This changes the nwfilter-define error from:
error: cannot create config directory (null): Bad address
To:
this function is not supported by the connection driver:
virNWFilterDefineXML

https://bugzilla.redhat.com/show_bug.cgi?id=1029266
2013-11-13 09:41:57 +01:00
Eric Blake
1b7ec657c5 maint: avoid 'const fooPtr' in nwfilter files
'const fooPtr' is the same as 'foo * const' (the pointer won't
change, but it's contents can).  But in general, if an interface
is trying to be const-correct, it should be using 'const foo *'
(the pointer is to data that can't be changed).

Fix up offenders in nwfilter code.

This patch does nothing about the stupidity evident in having
__virNWFilterInstantiateFilter, _virNWFilterInstantiateFilter,
and virNWFilterInstantiateFilter, which differ only by leading
underscores, and which infringes on the namespace reserved to
the implementation - that would need to be a separate cleanup.

* src/nwfilter/nwfilter_dhcpsnoop.h (virNWFilterDHCPSnoopReq): Use
intended type.
* src/nwfilter/nwfilter_gentech_driver.h
(virNWFilterInstantiateFilter)
(virNWFilterUpdateInstantiateFilter)
(virNWFilterInstantiataeFilterLate, virNWFilterTeardownFilter)
(virNWFilterCreateVarHashmap): Likewise.
* src/nwfilter/nwfilter_learnipaddr.h (virNWFilterLearnIPAddress):
Likewise.
* src/conf/nwfilter_conf.h (virNWFilterApplyBasicRules)
(virNWFilterApplyDHCPOnlyRules): Likewise.
(virNWFilterDefFormat): Make const-correct.
* src/conf/nwfilter_params.h (virNWFilterVarValueCopy)
(virNWFilterVarValueGetSimple, virNWFilterVarValueGetCardinality)
(virNWFilterVarValueEqual, virNWFilterVarAccessEqual)
(virNWFilterVarAccessGetVarName, virNWFilterVarAccessGetType)
(virNWFilterVarAccessGetIterId, virNWFilterVarAccessGetIndex)
(virNWFilterVarAccessIsAvailable)
(virNWFilterVarCombIterGetVarValue): Use intended type.
(virNWFilterVarValueGetNthValue): Make const-correct.
* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopReqLeaseDel)
(virNWFilterSnoopIFKeyFMT, virNWFilterDHCPSnoopReq)
(virNWFilterSnoopPruneIter, virNWFilterSnoopRemAllReqIter)
(virNWFilterDHCPSnoopReq): Fix fallout.
* src/nwfilter/nwfilter_gentech_driver.c
(virNWFilterVarHashmapAddStdValues, virNWFilterCreateVarHashmap)
(virNWFilterInstantiate, __virNWFilterInstantiateFilter)
(_virNWFilterInstantiateFilter, virNWFilterInstantiateFilterLate)
(virNWFilterInstantiateFilter)
(virNWFilterUpdateInstantiateFilter)
(virNWFilterRollbackUpdateFilter, virNWFilterTeardownFilter):
Likewise.
* src/nwfilter/nwfilter_learnipaddr.c (virNWFilterLearnIPAddress):
Likewise.
* src/conf/nwfilter_params.c (virNWFilterVarValueCopy)
(virNWFilterVarValueGetSimple)
(virNWFilterVarValueGetCardinality, virNWFilterVarValueEqual)
(virNWFilterVarCombIterAddVariable)
(virNWFilterVarCombIterGetVarValue, virNWFilterVarValueCompare)
(virNWFilterFormatParamAttributes, virNWFilterVarAccessEqual)
(virNWFilterVarAccessGetVarName, virNWFilterVarAccessGetType)
(virNWFilterVarAccessGetIterId, virNWFilterVarAccessGetIndex)
(virNWFilterVarAccessGetIntIterId)
(virNWFilterVarAccessIsAvailable)
(virNWFilterVarValueGetNthValue): Likewise.
* src/nwfilter/nwfilter_ebiptables_driver.c (ebtablesApplyBasicRules)
(ebtablesApplyDHCPOnlyRules, ebiptablesRuleOrderSort)
(ebiptablesRuleOrderSortPtr): Likewise.
* src/conf/nwfilter_conf.c (virNWFilterDefEqual)
(virNWFilterDefFormat): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-10-14 13:13:18 -06:00
Eric Blake
b43efdaa13 maint: avoid 'const fooPtr' in hashes
'const fooPtr' is the same as 'foo * const' (the pointer won't
change, but it's contents can).  But in general, if an interface
is trying to be const-correct, it should be using 'const foo *'
(the pointer is to data that can't be changed).

Fix up virhash to provide a const-correct interface: all actions
that don't modify the table take a const table.  Note that in
one case (virHashSearch), we actually strip const away - we aren't
modifying the contents of the table, so much as associated data
for ensuring that the code uses the table correctly (if this were
C++, it would be a case for the 'mutable' keyword).

* src/util/virhash.h (virHashKeyComparator, virHashEqual): Use
intended type.
(virHashSize, virHashTableSize, virHashLookup, virHashSearch):
Make const-correct.
* src/util/virhash.c (virHashEqualData, virHashEqual)
(virHashLookup, virHashSize, virHashTableSize, virHashSearch)
(virHashComputeKey): Fix fallout.
* src/conf/nwfilter_params.c
(virNWFilterFormatParameterNameSorter): Likewise.
* src/nwfilter/nwfilter_ebiptables_driver.c
(ebiptablesFilterOrderSort): Likewise.
* tests/virhashtest.c (testHashGetItemsCompKey)
(testHashGetItemsCompValue): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-10-14 11:40:24 -06:00
Daniel P. Berrange
6bd8860001 Don't ignore all dbus connection errors
Previous commit

  commit 7ada155cdf
  Author: Gao feng <gaofeng@cn.fujitsu.com>
  Date:   Wed Sep 11 11:15:02 2013 +0800

    DBus: introduce virDBusIsServiceEnabled

Made the cgroups code fallback to non-systemd based setup
when dbus is not running. It was too big a hammer though,
as it did not check what error code was received when the
dbus connection failed. Thus it silently ignored serious
errors from dbus such as "too many client connections",
which should always be treated as fatal.

We only want to ignore errors if the dbus unix socket does
not exist, or if nothing is listening on it.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-10-14 10:33:10 +01:00
Hongwei Bi
3a49c34ace nwfilter: fix a typo in nwfilter_gentech_driver.c
s/occcurred/occurred
2013-10-11 08:29:05 -06:00
Daniel P. Berrange
999d72fbd5 Remove use of virConnectPtr from all remaining nwfilter code
The virConnectPtr is passed around loads of nwfilter code in
order to provide it as a parameter to the callback registered
by the virt drivers. None of the virt drivers use this param
though, so it serves no purpose.

Avoiding the need to pass a virConnectPtr means that the
nwfilterStateReload method no longer needs to open a bogus
QEMU driver connection. This addresses a race condition that
can lead to a crash on startup.

The nwfilter driver starts before the QEMU driver and registers
some callbacks with DBus to detect firewalld reload. If the
firewalld reload happens while the QEMU driver is still starting
up though, the nwfilterStateReload method will open a connection
to the partially initialized QEMU driver and cause a crash.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-10-07 14:19:10 +01:00
Daniel P. Berrange
ebca369e3f Don't pass virConnectPtr in nwfilter 'struct domUpdateCBStruct'
The nwfilter driver only needs a reference to its private
state object, not a full virConnectPtr. Update the domUpdateCBStruct
struct to have a 'void *opaque' field instead of a virConnectPtr.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-10-07 14:19:10 +01:00
Daniel P. Berrange
b77b16ce41 Remove virConnectPtr arg from virNWFilterDefParse*
None of the virNWFilterDefParse* methods require a virConnectPtr
arg, so just drop it

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-10-07 14:19:10 +01:00
Daniel P. Berrange
bbcdd9b5dc Stop free'ing 'const char *' strings
The VIR_FREE() macro will cast away any const-ness. This masked a
number of places where we passed a 'const char *' string to
VIR_FREE. Fortunately in all of these cases, the variable was not
in fact const data, but a heap allocated string. Fix all the
variable declarations to reflect this.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-09-05 11:28:01 +01:00
Peter Krempa
e0e61b4cf7 nwfilter: Don't fail to start if DBus isn't available
When the daemon is compiled with firewalld support but the DBus message
bus isn't started in the system, the initialization of the nwfilter
driver fails even if there are fallback options.
2013-08-19 16:31:57 +02:00
Stefan Berger
06844ccbaa nwfilter: Use -m conntrack rather than -m state
Since iptables version 1.4.16 '-m state --state NEW' is converted to
'-m conntrack --ctstate NEW'. Therefore, when encountering this or later
versions of iptables use '-m conntrack --ctstate'.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2013-08-06 20:30:46 -04:00
Guido Günther
dc4cdc57c7 Create directory for lease files if it's missing
If we don't autostart a network it's not being created.

Debian Bug http://bugs.debian.org/715200
2013-07-16 19:46:31 +02:00
Daniel P. Berrange
a1a1433ca0 Convert 'int i' to 'size_t i' in src/nwfilter/ files
Convert the type of loop iterators named 'i', 'j', k',
'ii', 'jj', 'kk', to be 'size_t' instead of 'int' or
'unsigned int', also santizing 'ii', 'jj', 'kk' to use
the normal 'i', 'j', 'k' naming

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-07-10 17:55:16 +01:00
Michal Privoznik
8abed96d21 Adapt to VIR_ALLOC and virAsprintf in src/nwfilter/* 2013-07-10 11:07:32 +02:00
Daniel P. Berrange
70b1573fc1 Add access control filtering of nwfilter objects
Ensure that all APIs which list nwfilter objects filter
them against the access control system.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-07-03 15:54:53 +01:00
Daniel P. Berrange
1eca3f5bdf Add ACL checks into the nwfilter driver
Insert calls to the ACL checking APIs in all nwfilter driver
entrypoints.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-06-24 15:25:44 +01:00
Michal Privoznik
e463f4de77 Prefer VIR_STRDUP over virAsprintf(&dst, "%s", str)
There's no sense in using virAsprintf() just to duplicate a string.
We should use VIR_STRDUP which is designed just for that.
2013-06-07 17:45:53 +02:00
Ján Tomko
817a67b925 nwfilter: change two-state int parameters to bool 2013-06-06 17:22:53 +02:00
Ján Tomko
85f9178160 Remove redundant two-state integers 2013-06-06 17:22:53 +02:00
Ján Tomko
e557766c3b Replace two-state local integers with bool
Found with 'git grep "= 1"'.
2013-06-06 17:22:53 +02:00
Stefan Berger
0ec376c20a nwfilter: grab driver lock earlier during init (bz96649)
This patch is in relation to Bug 966449:

https://bugzilla.redhat.com/show_bug.cgi?id=966449

This is a patch addressing the coredump.

Thread 1 must be calling  nwfilterDriverRemoveDBusMatches(). It does so with
nwfilterDriverLock held. In the patch below I am now moving the
nwfilterDriverLock(driverState) further up so that the initialization, which
seems to either take a long time or is entirely stuck, occurs with the lock
held and the shutdown cannot occur at the same time. 

Remove the lock in virNWFilterDriverIsWatchingFirewallD to avoid
double-locking.
2013-06-04 14:50:20 -04:00
John Ferlan
64919d978e Check for existence of interface prior to setting terminate flag
https://bugzilla.redhat.com/show_bug.cgi?id=903480

During domain destruction it's possible that the learnIPAddressThread has
already removed the interface prior to the teardown filter path being run.
The teardown code would only be telling the thread to terminate.
2013-05-31 10:43:29 -04:00
Stefan Berger
b9c4bd0c07 nwfilter: Remove error report in virNWFilterDHCPSnoopEnd
Remove error reporting when calling the virNWFilterDHCPSnoopEnd
function with an interface for which no thread is snooping traffic.

Document the usage of this function.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2013-05-24 08:01:03 -04:00
Osier Yang
1f49c0e138 nwfilter: Change the comment style
The more common habit is to add the comment after the statements.
2013-05-22 13:15:57 +08:00
Osier Yang
610ae59fcc src/nwfilter: Remove the whitespace before ';' 2013-05-21 23:41:44 +08:00
Stefan Berger
a6a04ea47a nwfilter: check for inverted ctdir
Linux netfilter at some point (Linux 2.6.39) inverted the meaning of the
'--ctdir reply' and newer netfilter implementations now expect
'--ctdir original' instead and vice-versa.
We check for the kernel version and assume that all Linux kernels with version
2.6.39 have the newer inverted logic.

Any distro backporting the Linux kernel patch that inverts the --ctdir logic
(Linux commit 96120d86f) must also backport this patch for Linux and
adapt the kernel version being tested for.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2013-05-15 21:02:11 -04:00
Michal Privoznik
0ca51d5c9f Adapt to VIR_STRDUP and VIR_STRNDUP in src/nwfilter/* 2013-05-09 14:01:37 +02:00
Ján Tomko
dcea5a492f get rid of virBufferAsprintf where possible
Use virBufferAddLit or virBufferAddChar instead.
2013-05-07 17:38:58 +02:00
Eric Blake
25ae3d3015 build: avoid useless virAsprintf
virAsprintf(&foo, "%s", bar) is wasteful compared to
foo = strdup(bar) (or eventually, VIR_STRDUP(foo, bar),
but one thing at a time...).

Noticed while reviewing Laine's attempt to clean up broken
qemu:///session.

* cfg.mk (sc_prohibit_asprintf): Enhance rule.
* src/esx/esx_storage_backend_vmfs.c
(esxStorageBackendVMFSVolumeLookupByKey): Fix offender.
* src/network/bridge_driver.c (networkStateInitialize): Likewise.
* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopDHCPOpen):
Likewise.
* src/storage/storage_backend_sheepdog.c
(virStorageBackendSheepdogRefreshVol): Likewise.
* src/util/vircgroup.c (virCgroupAddTaskStrController): Likewise.
* src/util/virdnsmasq.c (addnhostsAdd): Likewise.
* src/xen/block_stats.c (xenLinuxDomainDeviceID): Likewise.
* src/xen/xen_driver.c (xenUnifiedConnectOpen): Likewise.
* tools/virsh.c (vshGetTypedParamValue): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 13:35:26 -06:00
Michal Privoznik
7c9a2d88cd virutil: Move string related functions to virstring.c
The source code base needs to be adapted as well. Some files
include virutil.h just for the string related functions (here,
the include is substituted to match the new file), some include
virutil.h without any need (here, the include is removed), and
some require both.
2013-05-02 16:56:55 +02:00
Daniel P. Berrange
90430791ae Make driver method names consistent with public APIs
Ensure that all drivers implementing public APIs use a
naming convention for their implementation that matches
the public API name.

eg for the public API   virDomainCreate make sure QEMU
uses qemuDomainCreate and not qemuDomainStart

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-24 11:00:18 +01:00
Daniel P. Berrange
d407a11eab Dedicated name for sub-driver open/close methods
It will simplify later work if the sub-drivers have dedicated
APIs / field names. ie virNetworkDriver should have
virDrvNetworkOpen and virDrvNetworkClose methods

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-24 10:59:54 +01:00
Daniel P. Berrange
abe038cfc0 Extend previous check to validate driver struct field names
Ensure that the driver struct field names match the public
API names. For an API virXXXX we must have a driver struct
field xXXXX. ie strip the leading 'vir' and lowercase any
leading uppercase letters.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-24 10:59:53 +01:00
Daniel P. Berrange
e57aaa6fcf Disable cast-align warnings in various places
There are a number of places which generate cast alignment
warnings, which are difficult or impossible to address. Use
pragmas to disable the warnings in these few places

conf/nwfilter_conf.c: In function 'virNWFilterRuleDetailsParse':
conf/nwfilter_conf.c:1806:16: warning: cast increases required alignment of target type [-Wcast-align]
         item = (nwItemDesc *)((char *)nwf + att[idx].dataIdx);
conf/nwfilter_conf.c: In function 'virNWFilterRuleDefDetailsFormat':
conf/nwfilter_conf.c:3238:16: warning: cast increases required alignment of target type [-Wcast-align]
         item = (nwItemDesc *)((char *)def + att[i].dataIdx);

storage/storage_backend_mpath.c: In function 'virStorageBackendCreateVols':
storage/storage_backend_mpath.c:247:17: warning: cast increases required alignment of target type [-Wcast-align]
         names = (struct dm_names *)(((char *)names) + next);

nwfilter/nwfilter_dhcpsnoop.c: In function 'virNWFilterSnoopDHCPDecode':
nwfilter/nwfilter_dhcpsnoop.c:994:15: warning: cast increases required alignment of target type [-Wcast-align]
         pip = (struct iphdr *) pep->eh_data;
nwfilter/nwfilter_dhcpsnoop.c:1004:11: warning: cast increases required alignment of target type [-Wcast-align]
     pup = (struct udphdr *) ((char *) pip + (pip->ihl << 2));

nwfilter/nwfilter_learnipaddr.c: In function 'procDHCPOpts':
nwfilter/nwfilter_learnipaddr.c:327:33: warning: cast increases required alignment of target type [-Wcast-align]
                 uint32_t *tmp = (uint32_t *)&dhcpopt->value;
nwfilter/nwfilter_learnipaddr.c: In function 'learnIPAddressThread':
nwfilter/nwfilter_learnipaddr.c:501:43: warning: cast increases required alignment of target type [-Wcast-align]
                     struct iphdr *iphdr = (struct iphdr*)(packet +
nwfilter/nwfilter_learnipaddr.c:538:43: warning: cast increases required alignment of target type [-Wcast-align]
                     struct iphdr *iphdr = (struct iphdr*)(packet +
nwfilter/nwfilter_learnipaddr.c:544:48: warning: cast increases required alignment of target type [-Wcast-align]
                         struct udphdr *udphdr= (struct udphdr *)

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-08 10:03:21 +01:00
Stefan Berger
b7d00de2bd Fix libvirt upgrade path when nwfilter is used
Between revision 65fb9d49 and before this patch, an upgrade of libvirt while
VMs are running and instantiating iptables filtering rules due to nwfilter
rules, may leave stray iptables rules behind when shutting VMs down.
Left-over iptables rules may look like this:

Chain FP-vnet0 (1 references)
target     prot opt source               destination         
DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp spt:122
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           

[...]

Chain libvirt-out (1 references)
target     prot opt source               destination         
FO-vnet0   all  --  0.0.0.0/0            0.0.0.0/0           [goto]  PHYSDEV match --physdev-out vnet0



The reason is that the recent nwfilter code only removed filtering rules in
the libvirt-out chain that contain the --physdev-is-bridged parameter.
Older rules didn't match and were not removed.

Note that the user-defined chain FO-vnet0 could not be removed due to the
reference from the rule in libvirt-out.

Often the work around may be done through

service iptables restart
kill -SIGHUP $(pidof libvirtd)

This patch now also removes older libvirt versions' iptables rules.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2013-02-15 21:33:37 -05:00
Michal Privoznik
0d36f228a4 virCondDestroy: Lose attribute RETURN_CHECK
We are wrapping it in ignore_value() anyway.
2013-02-08 09:12:11 +01:00
Daniel P. Berrange
37abd47165 Turn virDomainObjList into an opaque virObject
As a step towards making virDomainObjList thread-safe turn it
into an opaque virObject, preventing any direct access to its
internals.

As part of this a new method virDomainObjListForEach is
introduced to replace all existing usage of virHashForEach
2013-02-05 15:49:25 +00:00
Daniel P. Berrange
abbec81bd0 Fix nwfilter driver reload/shutdown handling when unprivileged
Although the nwfilter driver skips startup when running in a
session libvirtd, it did not skip reload or shutdown. This
caused errors to be reported when sending SIGHUP to libvirtd,
and caused an abort() in libdbus on shutdown due to trying
to remove a dbus filter that was never added
2013-01-23 12:43:28 +00:00
Reinier Schoof
65fb9d49cc fixed xt_physdev warning when defining ip(6)tables rules
When starting a VM, /var/log/messages was spammed with the following message:
 xt_physdev: using --physdev-out in the OUTPUT, FORWARD and POSTROUTING chains for non-bridged traffic is not supported anymore.

With each extra VM I start, the messages get amplified
exponentially. This results in longer starting times every new VM,
relative the the previously started VM. When I ran a test with
starting 100 equal VM's, the first VM started in about 2 seconds, the
100th VM took 48 seconds to start. I'm running a vanilla 3.7.1 kernel,
but I have the same issue on VM hosts with kernel 3.2.28 or 3.2.0,
running libvirt 0.9.12 and 0.9.8 respectively.

Looking into the warning, it seemed that iptables need an extra argument,
--physdev-is-bridged, in commands like:
 iptables -A libvirt-out -m physdev --physdev-is-bridged --physdev-out vnet99 -g FP-vnet99

With that, the warnings in /var/log/messages are gone and running the
test again proved the 100th VM started in 3.8 seconds.
2013-01-17 11:32:26 -07:00
Daniel P. Berrange
325b02b5a3 Convert virDomainObj, qemuAgent, qemuMonitor, lxcMonitor to virObjectLockable
The  virDomainObj, qemuAgent, qemuMonitor, lxcMonitor classes
all require a mutex, so can be switched to use virObjectLockable

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-01-16 11:02:58 +00:00
Daniel P. Berrange
da77f04ed5 Convert HAVE_DBUS to WITH_DBUS
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-01-14 13:25:47 +00:00
John Ferlan
aafe41971c nwfilter: Remove unprivileged code path to set base
Commit id f8ab364c removed ability to run this driver unprivileged. Coverity
detected the check and flagged it.
2013-01-08 17:18:31 -07:00
Daniel P. Berrange
f24404a324 Rename virterror.c virterror_internal.h to virerror.{c,h} 2012-12-21 11:19:50 +00:00
Daniel P. Berrange
404174cad3 Rename threads.{c,h} to virthread.{c,h} 2012-12-21 11:19:49 +00:00
Daniel P. Berrange
20463736cc Rename threadpool.{c,h} to virthreadpool.{c,h} 2012-12-21 11:19:48 +00:00
Daniel P. Berrange
ab9b7ec2f6 Rename memory.{c,h} to viralloc.{c,h} 2012-12-21 11:17:14 +00:00
Daniel P. Berrange
936d95d347 Rename logging.{c,h} to virlog.{c,h} 2012-12-21 11:17:14 +00:00
Daniel P. Berrange
04d9510f50 Rename command.{c,h} to vircommand.{c,h} 2012-12-21 11:17:13 +00:00
Daniel P. Berrange
2005f7b552 Rename buf.{c,h} to virbuffer.{c,h}
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-12-21 11:17:12 +00:00
Daniel P. Berrange
79b8a56995 Replace polling for active VMs with signalling by drivers
Currently to deal with auto-shutdown libvirtd must periodically
poll all stateful drivers. Thus sucks because it requires
acquiring both the driver lock and locks on every single virtual
machine. Instead pass in a "inhibit" callback to virStateInitialize
which drivers can invoke whenever they want to inhibit shutdown
due to existance of active VMs.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-12-04 12:14:04 +00:00
Daniel P. Berrange
ae2163f852 Only let VM drivers block libvirtd timed shutdown
The only important state that should prevent libvirtd shutdown
is from running VMs. Networks, host devices, network filters
and storage pools are all long lived resources that have no
significant in-memory state. They should not block shutdown.
2012-12-04 12:12:51 +00:00
Ján Tomko
4f9af0857c nwfilter: report an error on OOM
Also removed some unreachable code found by coverity:
libvirt-0.10.2/src/nwfilter/nwfilter_driver.c:259: unreachable: This
code cannot be reached: "nwfilterDriverUnlock(driver...".
2012-11-30 15:35:14 +01:00
Daniel P. Berrange
f4ea67f5b3 Turn some dual-state int parameters into booleans
The virStateInitialize method and several cgroups methods were
using an 'int privileged' parameter or similar for dual-state
values. These are better represented with the bool type.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-11-29 16:14:43 +00:00
Eric Blake
89cf363061 nwfilter: drop dead code
Commit cb022152 went overboard and introduced a dead conditional
while trying to get rid of a potential NULL dereference.

* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopReqNew):
Remove redundant conditional.
2012-11-28 09:21:33 -07:00
Ján Tomko
cb02215252 nwfilter: fix NULL pointer check in virNWFilterSnoopReqNew
This can't lead to a crash since virNWFilterSnoopReqNew is only called
with a static array as the argument, but if we check for NULL we should
do it right.
2012-11-29 00:00:39 +08:00
Daniel P. Berrange
1c04f99970 Remove spurious whitespace between function name & open brackets
The libvirt coding standard is to use 'function(...args...)'
instead of 'function (...args...)'. A non-trivial number of
places did not follow this rule and are fixed in this patch.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-11-02 13:36:49 +00:00
Eric Blake
4ecb723b9e maint: fix up copyright notice inconsistencies
https://www.gnu.org/licenses/gpl-howto.html recommends that
the 'If not, see <url>.' phrase be a separate sentence.

* tests/securityselinuxhelper.c: Remove doubled line.
* tests/securityselinuxtest.c: Likewise.
* globally: s/;  If/.  If/
2012-09-20 16:30:55 -06:00
Osier Yang
1483d79ce9 list: Implement listAllNWFilters
Simply returns the object list. No filtering.

src/nwfilter/nwfilter_driver.c: Implement listAllNWFilters
2012-09-17 12:36:51 +08:00
Dwight Engen
14dd70cca2 build: fix missing include
virNWFilterSnoopAdjustPoll() uses a struct pollfd but poll.h is never included
nwfilter/nwfilter_dhcpsnoop.c:1297: error: 'struct pollfd' declared inside parameter list
2012-09-14 16:55:58 -06:00
Eric Blake
ddd8c3b995 nwfilter: drop use of awk
Commit 2a41bc9 dropped a dependency on gawk, but we can go one step
further and avoid awk altogether.

* src/nwfilter/nwfilter_ebiptables_driver.c
(iptablesLinkIPTablesBaseChain): Simplify command.
(ebiptablesDriverInit, ebiptablesDriverShutdown): Drop awk probe.
2012-09-06 16:33:06 -06:00
Eric Blake
ccaf0beec8 build: improved handling of <execinfo.h>, BSD <net/if.h>
FreeBSD and OpenBSD have a <net/if.h> that is not self-contained;
and mingw lacks the header altogether.  But gnulib has just taken
care of that for us, so we might as well simplify our code.  In
the process, I got a syntax-check failure if we don't also take
the gnulib execinfo module.

* .gnulib: Update to latest, for execinfo and net_if.
* bootstrap.conf (gnulib_modules): Add execinfo and net_if modules.
* configure.ac: Let gnulib check for headers.  Simplify check for
'struct ifreq', while also including enough prereq headers.
* src/internal.h (IF_NAMESIZE): Drop, now that gnulib guarantees it.
* src/nwfilter/nwfilter_learnipaddr.h: Use correct header for
IF_NAMESIZE.
* src/util/virnetdev.c (includes): Assume <net/if.h> exists.
* src/util/virnetdevbridge.c (includes): Likewise.
* src/util/virnetdevtap.c (includes): Likewise.
* src/util/logging.c (includes): Assume <execinfo.h> exists.
(virLogStackTraceToFd): Handle gnulib's fallback implementation.
2012-09-06 10:08:47 -06:00
Stefan Berger
4021b85fce nwfilter: adapt IP learning for broadcasted DHCP replies
Adapt the IP learning code to also accept broadcasted DHCP replies
2012-08-31 11:41:30 +08:00
Stefan Berger
c828a746fa nwfilter: accept broadcasted DHCP replies in DHCP snooping code
Some DHCP servers send their DHCP replies to the broadcast MAC address
rather than to the MAC address of the VM. The existing DHCP snooping
code assumes that the reply always goes to the MAC address of the VM
thus filtering the traffic of some DHCP servers' replies.

The below patch adapts the code to

1) filter DHCP replies by comparing the MAC address in the reply against
   the MAC address of the VM (held in the snoop request)

2) adapts the pcap filter for traffic towards the VM to accept DHCP replies
   sent to any MAC address; for further filtering we rely on 1)

3) creates initial rules that are active while waiting for DHCP replies;
   these rules now accept DHCP replies to the VM's MAC address or to the
   MAC broadcast address
2012-08-31 11:41:26 +08:00
Stefan Berger
9e995c9a23 nwfilter: loop generated too many rules
The loop processing the trusted DHCP server generated one too
many rules and added one final rules that accepted responses
from all DHCP servers. Below patch fixes this.
2012-08-30 13:51:27 -04:00
Peter Krempa
f33dfffc41 nwfilter: Don't try to acquire DBus context when DBus is disabled
To silence error if DBus support is not compiled in.
2012-08-29 12:00:23 +08:00
Guido Günther
2a41bc95b5 Don't require gawk for a simple print expression
Fedora uses gawk as awk so there's no change and in behavior while
Debian/Ubuntu use mawk by default.

This was reported by Luca Capello in
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=636712
2012-08-29 12:00:03 +08:00
Laine Stump
e1602a76bd nwfilter: don't log error if firewalld is disabled, improve diagnostics
The original patch to support firewalld in nwfilter wasn't personally
checking the exit status of firewall-cmd, but was instead sending NULL
in the *exitstatus arg, which meant that virCommandWait would log an
error just for the exit status being non-0 (and a "more scary than
useful" error at that).

We don't want to treat this as an error, though, just as a reason to
use standard (ip|eb)tables commands instead of firewall-cmd.

This patch modifies the virCommandRun in the nwfilter code to request
status back from the caller. This avoids virCommandWait logging an
error message, and allows the caller to do as it likes after examining
the status.

The VIR_DEBUG() logged when firewalld is enabled has also been
reworded and changed to a VIR_INFO, and a similar VIR_INFO has been
added in the case that firewalld is *not* found+enabled.
2012-08-24 03:07:00 -04:00
Stefan Berger
4efde75fab nwfilter: provide basic support for firewalld
This patch provides basic support for using firewalld's firewall-cmd
rather than then plain eb/ip(6)tables commands.
2012-08-21 13:40:58 -04:00
Stefan Berger
98c7d8b278 nwfilter: remove target table before renaming it
Remove the target table before renaming a table to it, i.e.,
remove table B before renaming A to B. This makes the
renaming more robust against unconnected left-over tables.
2012-08-09 16:17:13 -04:00
Daniel P. Berrange
0c9fd4cfe9 Rewrite virAtomic APIs using GLib's atomic ops code
There are a few issues with the current virAtomic APIs

 - They require use of a virAtomicInt struct instead of a plain
   int type
 - Several of the methods do not implement memory barriers
 - The methods do not implement compiler re-ordering barriers
 - There is no Win32 native impl

The GLib library has a nice LGPLv2+ licensed impl of atomic
ops that works with GCC, Win32, or pthreads.h that addresses
all these problems. The main downside to their code is that
the pthreads impl uses a single global mutex, instead of
a per-variable mutex. Given that it does have a Win32 impl
though, we don't expect anyone to seriously use the pthread.h
impl, so this downside is not significant.

* .gitignore: Ignore test case
* configure.ac: Check for which atomic ops impl to use
* src/Makefile.am: Add viratomic.c
* src/nwfilter/nwfilter_dhcpsnoop.c: Switch to new atomic
  ops APIs and plain int datatype
* src/util/viratomic.h: inline impls of all atomic ops
  for GCC, Win32 and pthreads
* src/util/viratomic.c: Global pthreads mutex for atomic
  ops
* tests/viratomictest.c: Test validate to validate safety
  of atomic ops.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-02 11:50:59 +01:00
Eric Blake
768007aedc maint: don't permit format strings without %
Any time we have a string with no % passed through gettext, a
translator can inject a % to cause a stack overread.  When there
is nothing to format, it's easier to ask for a string that cannot
be used as a formatter, by using a trivial "%s" format instead.

In the past, we have used --disable-nls to catch some of the
offenders, but that doesn't get run very often, and many more
uses have crept in.  Syntax check to the rescue!

The syntax check can catch uses such as
virReportError(code,
               _("split "
                 "string"));
by using a sed script to fold context lines into one pattern
space before checking for a string without %.

This patch is just mechanical insertion of %s; there are probably
several messages touched by this patch where we would be better
off giving the user more information than a fixed string.

* cfg.mk (sc_prohibit_diagnostic_without_format): New rule.
* src/datatypes.c (virUnrefConnect, virGetDomain)
(virUnrefDomain, virGetNetwork, virUnrefNetwork, virGetInterface)
(virUnrefInterface, virGetStoragePool, virUnrefStoragePool)
(virGetStorageVol, virUnrefStorageVol, virGetNodeDevice)
(virGetSecret, virUnrefSecret, virGetNWFilter, virUnrefNWFilter)
(virGetDomainSnapshot, virUnrefDomainSnapshot): Add %s wrapper.
* src/lxc/lxc_driver.c (lxcDomainSetBlkioParameters)
(lxcDomainGetBlkioParameters): Likewise.
* src/conf/domain_conf.c (virSecurityDeviceLabelDefParseXML)
(virDomainDiskDefParseXML, virDomainGraphicsDefParseXML):
Likewise.
* src/conf/network_conf.c (virNetworkDNSHostsDefParseXML)
(virNetworkDefParseXML): Likewise.
* src/conf/nwfilter_conf.c (virNWFilterIsValidChainName):
Likewise.
* src/conf/nwfilter_params.c (virNWFilterVarValueCreateSimple)
(virNWFilterVarAccessParse): Likewise.
* src/libvirt.c (virDomainSave, virDomainSaveFlags)
(virDomainRestore, virDomainRestoreFlags)
(virDomainSaveImageGetXMLDesc, virDomainSaveImageDefineXML)
(virDomainCoreDump, virDomainGetXMLDesc)
(virDomainMigrateVersion1, virDomainMigrateVersion2)
(virDomainMigrateVersion3, virDomainMigrate, virDomainMigrate2)
(virStreamSendAll, virStreamRecvAll)
(virDomainSnapshotGetXMLDesc): Likewise.
* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopReqLeaseDel)
(virNWFilterDHCPSnoopReq): Likewise.
* src/openvz/openvz_driver.c (openvzUpdateDevice): Likewise.
* src/openvz/openvz_util.c (openvzKBPerPages): Likewise.
* src/qemu/qemu_cgroup.c (qemuSetupCgroup): Likewise.
* src/qemu/qemu_command.c (qemuBuildHubDevStr, qemuBuildChrChardevStr)
(qemuBuildCommandLine): Likewise.
* src/qemu/qemu_driver.c (qemuDomainGetPercpuStats): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainAttachNetDevice): Likewise.
* src/rpc/virnetsaslcontext.c (virNetSASLSessionGetIdentity):
Likewise.
* src/rpc/virnetsocket.c (virNetSocketNewConnectUNIX)
(virNetSocketSendFD, virNetSocketRecvFD): Likewise.
* src/storage/storage_backend_disk.c
(virStorageBackendDiskBuildPool): Likewise.
* src/storage/storage_backend_fs.c
(virStorageBackendFileSystemProbe)
(virStorageBackendFileSystemBuild): Likewise.
* src/storage/storage_backend_rbd.c
(virStorageBackendRBDOpenRADOSConn): Likewise.
* src/storage/storage_driver.c (storageVolumeResize): Likewise.
* src/test/test_driver.c (testInterfaceChangeBegin)
(testInterfaceChangeCommit, testInterfaceChangeRollback):
Likewise.
* src/vbox/vbox_tmpl.c (vboxListAllDomains): Likewise.
* src/xenxs/xen_sxpr.c (xenFormatSxprDisk, xenFormatSxpr):
Likewise.
* src/xenxs/xen_xm.c (xenXMConfigGetUUID, xenFormatXMDisk)
(xenFormatXM): Likewise.
2012-07-26 14:32:30 -06:00
Osier Yang
f9ce7dad60 Desert the FSF address in copyright
Per the FSF address could be changed from time to time, and GNU
recommends the following now: (http://www.gnu.org/licenses/gpl-howto.html)

  You should have received a copy of the GNU General Public License
  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

This patch removes the explicit FSF address, and uses above instead
(of course, with inserting 'Lesser' before 'General').

Except a bunch of files for security driver, all others are changed
automatically, the copyright for securify files are not complete,
that's why to do it manually:

  src/security/security_selinux.h
  src/security/security_driver.h
  src/security/security_selinux.c
  src/security/security_apparmor.h
  src/security/security_apparmor.c
  src/security/security_driver.c
2012-07-23 10:50:50 +08:00
Daniel P. Berrange
f8ab364c5f Disable NWFilter driver completely when unprivileged
Running libvirtd unprivileged results in a warning message from
the NWFilter driver

  virNWFilterSnoopLeaseFileRefresh:1882 : open("/var/run/libvirt/network/nwfilter.ltmp"): No such file or directory

Since it requires privileged network access, this driver should
not even run when unprivileged.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-20 17:32:26 +01:00
Daniel P. Berrange
fa7ebc174f Replace use of virNWFilterReportError with virReportError
Update the network filter driver to use virReportError instead
of the virNWFilterReportError custom macro

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-18 21:16:25 +01:00
Daniel P. Berrange
6d964bcf66 Add missing "%s" with constant string error message in nwfilter_dhcpsnoop.c
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-18 21:15:43 +01:00
Daniel P. Berrange
1e0bb184a7 Convert all files in src/conf/ to use virReportError()
This removes all the per-file error reporting macros
from the code in src/conf/

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-18 19:01:50 +01:00
Michal Privoznik
9d1938896c nwfilter: Convert to virMacAddrPtr not virMacAddrPtr*
My previous patch wasn't complete as it converted from
(unsigned char *) to (virMacAddrPtr *). It should be
(virMacAddrPtr) only.
2012-07-17 16:29:43 +02:00
Michal Privoznik
14197c7472 nwfilter: Convert to virMacAddrPtr completely
The previous commit (387117ad92) was incomplete leaving those
who does not use libpcap with uncompilable sources beacuse
of incomplete conversion of virNWFilterDHCPSnoopReq function.
2012-07-17 16:05:30 +02:00
Stefan Berger
387117ad92 Convert 'raw MAC address' usages to use virMacAddr
Introduce new members in the virMacAddr 'class'
- virMacAddrSet: set virMacAddr from a virMacAddr
- virMacAddrSetRaw: setting virMacAddr from raw 6 byte MAC address buffer
- virMacAddrGetRaw: writing virMacAddr into raw 6 byte MAC address buffer
- virMacAddrCmp: comparing two virMacAddr
- virMacAddrCmpRaw: comparing a virMacAddr with a raw 6 byte MAC address buffer

then replace raw MAC addresses by replacing

- 'unsigned char *' with virMacAddrPtr
- 'unsigned char ... [VIR_MAC_BUFLEN]' with virMacAddr

and introduce usage of above functions where necessary.
2012-07-17 08:07:59 -04:00
Daniel P. Berrange
b9852862ea Fix launch of libvirtd when DHCP snooping support is not available.
When libpcap is not available, the NWFilter driver provides a
no-op stub for the DHCP snooping initialization. This was
mistakenly returning '-1' instead of '0', so the entire driver
initialization failed
2012-06-15 15:33:51 +01:00
Stefan Berger
b92d52d3c0 nwfilter: Add multiple IP address support to DHCP snooping
With support for multiple IP addresses per interface in place, this patch
now adds support for multiple IP addresses per interface for the DHCP
snooping code.


Testing:

Since the infrastructure I tested this with does not provide multiple IP
addresses per MAC address (anymore), I either had to plug the VM's interface
from the virtual bride connected directly to the infrastructure to virbr0
to get a 2nd IP address from dnsmasq (kill and run dhclient inside the VM)
or changed the lease file  (/var/run/libvirt/network/nwfilter.leases) and
restart libvirtd to have a 2nd IP address on an existing interface.
Note that dnsmasq can take a lease timeout parameter as part of the --dhcp-range
command line parameter, so that timeouts can be tested that way
(--dhcp-range 192.168.122.2,192.168.122.254,120). So, terminating and restarting
dnsmasq with that parameter is another choice to watch an IP address disappear
after 120 seconds.

Regards,
   Stefan
2012-06-01 19:32:06 -04:00
Stefan Berger
797b47580a nwfilter: move code for IP address map into separate file
The goal of this patch is to prepare for support for multiple IP
addresses per interface in the DHCP snooping code.

Move the code for the IP address map that maps interface names to
IP addresses into their own file. Rename the functions on the way
but otherwise leave the code as-is. Initialize this new layer
separately before dependent layers (iplearning, dhcpsnooping)
and shut it down after them.
2012-06-01 19:32:06 -04:00
Stefan Berger
cec281fcaa nwfilter: add DHCP snooping
This patch adds DHCP snooping support to libvirt. The learning method for
IP addresses is specified by setting the "CTRL_IP_LEARNING" variable to one of
"any" [default] (existing IP learning code), "none" (static only addresses)
or "dhcp" (DHCP snooping).

Active leases are saved in a lease file and reloaded on restart or HUP.

The following interface XML activates and uses the DHCP snooping:

    <interface type='bridge'>
      <source bridge='virbr0'/>
      <filterref filter='clean-traffic'>
        <parameter name='CTRL_IP_LEARNING' value='dhcp'/>
      </filterref>
    </interface>

All filters containing the variable 'IP' are automatically adjusted when
the VM receives an IP address via DHCP. However, multiple IP addresses per
interface are silently ignored in this patch, thus only supporting one IP
address per interface. Multiple IP address support is added in a later
patch in this series.

Signed-off-by: David L Stevens <dlstevens@us.ibm.com>
Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2012-06-01 19:32:06 -04:00
Daniel P. Berrange
517368a377 Remove uid param from directory lookup APIs
Remove the uid param from virGetUserConfigDirectory,
virGetUserCacheDirectory, virGetUserRuntimeDirectory,
and virGetUserDirectory

These functions were universally called with the
results of getuid() or geteuid(). To make it practical
to port to Win32, remove the uid parameter and hardcode
geteuid()

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-05-28 10:55:06 +01:00
Stefan Berger
a3f3ab4c9c nwfilter: Add support for ipset
This patch adds support for the recent ipset iptables extension
to libvirt's nwfilter subsystem. Ipset allows to maintain 'sets'
of IP addresses, ports and other packet parameters and allows for
faster lookup (in the order of O(1) vs. O(n)) and rule evaluation
to achieve higher throughput than what can be achieved with
individual iptables rules.

On the command line iptables supports ipset using

iptables ... -m set --match-set <ipset name> <flags> -j ...

where 'ipset name' is the name of a previously created ipset and
flags is a comma-separated list of up to 6 flags. Flags use 'src' and 'dst'
for selecting IP addresses, ports etc. from the source or
destination part of a packet. So a concrete example may look like this:

iptables -A INPUT -m set --match-set test src,src -j ACCEPT

Since ipset management is quite complex, the idea was to leave ipset 
management outside of libvirt but still allow users to reference an ipset.
The user would have to make sure the ipset is available once the VM is
started so that the iptables rule(s) referencing the ipset can be created.

Using XML to describe an ipset in an nwfilter rule would then look as
follows:

  <rule action='accept' direction='in'>
    <all ipset='test' ipsetflags='src,src'/>
  </rule>

The two parameters on the command line are also the two distinct XML attributes
'ipset' and 'ipsetflags'.

FYI: Here is the man page for ipset:

https://ipset.netfilter.org/ipset.man.html

Regards,
    Stefan
2012-05-21 06:26:34 -04:00
William Jon McCann
32a9aac2e0 Use XDG Base Directories instead of storing in home directory
As defined in:
http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

This offers a number of advantages:
 * Allows sharing a home directory between different machines, or
sessions (eg. using NFS)
 * Cleanly separates cache, runtime (eg. sockets), or app data from
user settings
 * Supports performing smart or selective migration of settings
between different OS versions
 * Supports reseting settings without breaking things
 * Makes it possible to clear cache data to make room when the disk
is filling up
 * Allows us to write a robust and efficient backup solution
 * Allows an admin flexibility to change where data and settings are stored
 * Dramatically reduces the complexity and incoherence of the
system for administrators
2012-05-14 15:15:58 +01:00
Stefan Berger
9c1ce3dc11 nwfilter: address coverity findings
This patch addresses the following coverity findings:

/libvirt/src/conf/nwfilter_params.c:157:
deref_parm: Directly dereferencing parameter "val".

/libvirt/src/conf/nwfilter_params.c:473:
negative_returns: Using variable "iterIndex" as an index to array "res->iter".

/libvirt/src/nwfilter/nwfilter_ebiptables_driver.c:2891:
unchecked_value: No check of the return value of "virAsprintf(&protostr, "-d 01:80:c2:00:00:00 ")".

/libvirt/src/nwfilter/nwfilter_ebiptables_driver.c:2894:
unchecked_value: No check of the return value of "virAsprintf(&protostr, "-p 0x%04x ", l3_protocols[protoidx].attr)".

/libvirt/src/nwfilter/nwfilter_ebiptables_driver.c:3590:
var_deref_op: Dereferencing null variable "inst".
2012-04-26 16:45:36 -04:00
Stefan Berger
7c26343bc3 nwfilter: Fix support for trusted DHCP servers
Fix the support for trusted DHCP server in the ebtables code's
hard-coded function applying DHCP only filtering rules:
Rather than using a char * use the more flexible
virNWFilterVarValuePtr that contains the trusted DHCP server(s)
IP address. Process all entries.

Since all callers so far provided NULL as parameter, no changes
are necessary in any other code.
2012-04-19 10:21:43 -04:00
Martin Kletzander
9943276fd2 Cleanup for a return statement in source files
Return statements with parameter enclosed in parentheses were modified
and parentheses were removed. The whole change was scripted, here is how:

List of files was obtained using this command:
git grep -l -e '\<return\s*([^()]*\(([^()]*)[^()]*\)*)\s*;' |             \
grep -e '\.[ch]$' -e '\.py$'

Found files were modified with this command:
sed -i -e                                                                 \
's_^\(.*\<return\)\s*(\(\([^()]*([^()]*)[^()]*\)*\))\s*\(;.*$\)_\1 \2\4_' \
-e 's_^\(.*\<return\)\s*(\([^()]*\))\s*\(;.*$\)_\1 \2\3_'

Then checked for nonsense.

The whole command looks like this:
git grep -l -e '\<return\s*([^()]*\(([^()]*)[^()]*\)*)\s*;' |             \
grep -e '\.[ch]$' -e '\.py$' | xargs sed -i -e                            \
's_^\(.*\<return\)\s*(\(\([^()]*([^()]*)[^()]*\)*\))\s*\(;.*$\)_\1 \2\4_' \
-e 's_^\(.*\<return\)\s*(\([^()]*\))\s*\(;.*$\)_\1 \2\3_'
2012-03-26 14:45:22 -06:00
Stefan Berger
1c310eaf30 nwfilter: improved logging during driver initialization
Improve the logging during driver initialization when testing the command
line tools.
2012-02-16 18:56:39 -05:00
Daniel P. Berrange
4ce98dadcc Rename virXXXXMacAddr to virMacAddrXXX
Rename virFormatMacAddr, virGenerateMacAddr and virParseMacAddr
to virMacAddrFormat, virMacAddrGenerate and virMacAddrParse
respectively
2012-01-27 17:53:44 +00:00
Stefan Berger
8fa78dd49c nwfilter: Force instantiation of filters upon driver reload
Introduce a function that rebuilds all running VMs' filters. Call
this function when reloading the nwfilter driver.

This addresses a problem introduced by the 2nd patch that typically
causes no filters to be reinstantiate anymore upon driver reload
since their XML has not changed. Yet the current behavior is that
upon a SIGHUP all filters get reinstantiated.
2012-01-27 08:19:58 -05:00
Stefan Berger
64484d550d Address side effects of accessing vars via index
Address side effect of accessing a variable via an index: Filters
accessing a variable where an element is accessed that is beyond the
size of the list (for example $TEST[10] and only 2 elements are available)
cannot instantiate that filter. Test for this and report proper error
to user.
2012-01-11 06:42:37 -05:00
Stefan Berger
80e9a5cd4c Introduce possibility to have an iterator per variable
This patch introduces the capability to use a different iterator per
variable.

The currently supported notation of variables in a filtering rule like

  <rule action='accept' direction='out'>
     <tcp  srcipaddr='$A' srcportstart='$B'/>
  </rule>

processes the two lists 'A' and 'B' in parallel. This means that A and B
must have the same number of 'N' elements and that 'N' rules will be 
instantiated (assuming all tuples from A and B are unique).

In this patch we now introduce the assignment of variables to different
iterators. Therefore a rule like

  <rule action='accept' direction='out'>
     <tcp  srcipaddr='$A[@1]' srcportstart='$B[@2]'/>
  </rule>

will now create every combination of elements in A with elements in B since
A has been assigned to an iterator with Id '1' and B has been assigned to an
iterator with Id '2', thus processing their value independently.

The first rule has an equivalent notation of

  <rule action='accept' direction='out'>
     <tcp  srcipaddr='$A[@0]' srcportstart='$B[@0]'/>
  </rule>
2012-01-11 06:42:37 -05:00
Stefan Berger
1c8f0cbb83 nwfilter: Do not require DHCP requests to be broadcasted
Remove the requirement that DHCP messages have to be broadcasted.
DHCP requests are most often sent via broadcast but can be directed
towards a specific DHCP server. For example 'dhclient' takes '-s <server>'
as a command line parameter thus allowing DHCP requests to be sent to a
specific DHCP server.
2011-12-21 10:54:47 -05:00
Stefan Berger
b4d579de1e nwfilter: do not create ebtables chain unnecessarily
If only iptables rules are created then two unnecessary ebtables chains
are also created. This patch fixes this and prevents these chains from
being created. They have been cleaned up properly, though.
2011-12-16 16:54:49 -05:00
Stefan Berger
33eb3567dd Pass the VM's UUID into the nwfilter subsystem
A preparatory patch for DHCP snooping where we want to be able to
differentiate between a VM's interface using the tuple of
<VM UUID, Interface MAC address>. We assume that MAC addresses could
possibly be re-used between different networks (VLANs) thus do not only
want to rely on the MAC address to identify an interface.

At the current 'final destination' in virNWFilterInstantiate I am leaving
the vmuuid parameter as ATTRIBUTE_UNUSED until the DHCP snooping patches arrive.
(we may not post the DHCP snooping patches for 0.9.9, though)

Mostly this is a pretty trivial patch. On the lowest layers, in lxc_driver
and uml_conf, I am passing the virDomainDefPtr around until I am passing
only the VM's uuid into the NWFilter calls.
2011-12-08 21:35:20 -05:00
Stefan Berger
95ff5899b9 nwfilter: cleanup return codes in nwfilter subsystem
This patch cleans up return codes in the nwfilter subsystem.

Some functions in nwfilter_conf.c (validators and formatters) are
keeping their bool return for now and I am converting their return
code to true/false.

All other functions now have failure return codes of -1 and success
of 0.

[I searched for all occurences of ' 1;' and checked all 'if ' and
adapted where needed. After that I did a grep for 'NWFilter' in the source
tree.]
2011-12-08 21:26:34 -05:00
Stefan Berger
dc62c22532 nwfilter: remove virConnectPtr from internal API calls
Remove the virConnectPtr from the nwfilter's internal API calls as
far as possible.
2011-11-23 14:13:03 -05:00
Michal Privoznik
489e14f258 nwfilter: Initialize virNWFilterAddIpAddrForIfname return variable
Latest nwfilter patch ad6c67cf introduced uninitialized return
value. This was spotted by 4.6.2 gcc.
2011-11-23 07:43:36 -05:00
Daniel P. Berrange
3fb94eeeb2 Fix uninitialized variable in NWfilter IP learning code
* src/nwfilter/nwfilter_learnipaddr.c: Initialize ret variable
2011-11-23 12:16:01 +00:00
Stefan Berger
ad6c67cf85 Enable detection of multiple IP addresses
In preparation of DHCP Snooping and the detection of multiple IP
addresses per interface:

The hash table that is used to collect the detected IP address of an
interface can so far only handle one IP address per interface. With
this patch we extend this to allow it to handle a list of IP addresses.

Above changes the returned variable type of virNWFilterGetIpAddrForIfname()
from char * to virNWFilterVarValuePtr; adapt all existing functions calling
this function.
2011-11-22 19:05:45 -05:00
Stefan Berger
7ca82ecbea Pass additional parameter into applyDHCPOnly function
In preparation for the DHCP Snooping code:
Pass an additional parameter into the applyDHCPOnly function
of the 'techdriver'.
2011-11-22 15:59:26 -05:00
Stefan Berger
aa1cb7e706 nwfilter: use shell variable to invoke 'ip(6)tables' command
Introduce a shell variable 'IBT' to invoke the ip(6)tables command.

Tested with libvirt-tck.
2011-11-22 15:12:04 -05:00
Stefan Berger
970b417abb nwfilter: use shell variable to invoke 'ebtables' command
Introduce a shell variable 'EBT' to invoke the ebtables command.
Hard-code the used ebtables table to '-t nat'.

Tested with libvirt-tck.
2011-11-22 15:12:04 -05:00
Stefan Berger
fa69eb5f52 Improve error reporting of failures to apply filtering rules
Display the executed command and failure message if a command failed to
execute.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-22 15:12:04 -05:00
Stefan Berger
ba3bf00acf Add support for STP filtering
This patch adds support for filtering of STP (spanning tree protocol) traffic
to the parser and makes us of the ebtables support for STP filtering. This code
now enables the filtering of traffic in chains with prefix 'stp'.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-22 15:12:03 -05:00
Stefan Berger
af37ce3dc7 Add a 'mac' chain
With hunks borrowed from one of David Steven's previous patches, we now
add the capability of having a 'mac' chain which is useful to filter
for multiple valid MAC addresses.

Signed-off-by: David L Stevens <dlstevens@us.ibm.com>
Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-22 15:12:03 -05:00
Stefan Berger
8047c4bffa Add support for VLAN filtering
This patch adds support for filtering of VLAN (802.1Q) traffic to the
parser and makes us of the ebtables support for VLAN filtering. This code
now enables the filtering of traffic in chains with prefix 'vlan'.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-19 07:26:56 -05:00
Stefan Berger
c80296e21a Create rules for each member of a list
This patch extends the NWFilter driver for Linux (ebiptables) to create
rules for each member of a previously introduced list. If for example
an attribute value (internally) looks like this:

IP = [10.0.0.1, 10.0.0.2, 10.0.0.3]

then 3 rules will be generated for a rule accessing the variable 'IP',
one for each member of the list. The effect of this is that this now
allows for filtering for multiple values in one field. This can then be
used to support for filtering/allowing of multiple IP addresses per
interface.

An iterator is introduced that extracts each member of a list and
puts it into a hash table which then is passed to the function creating
a rule. For the above example the iterator would cause 3 loops.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:18 -05:00
Stefan Berger
581d1cea34 Rework value part of name-value pairs
NWFilters can be provided name-value pairs using the following
XML notation:

      <filterref filter='xyz'>
        <parameter name='PORT' value='80'/>
        <parameter name='VAL' value='abc'/>
      </filterref>

The internal representation currently is so that a name is stored as a
string and the value as well. This patch now addresses the value part of it
and introduces a data structure for storing a value either as a simple
value or as an array for later support of lists.

This patch adjusts all code that was handling the values in hash tables
and makes it use the new data type.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:18 -05:00
Stefan Berger
6aa99120fa Interleave jumping into chains with filtering rules in 'root' table
The previous patch extends the priority of filtering rules into negative
numbers. We now use this possibility to interleave the jumping into
chains with filtering rules to for example create the 'root' table of
an interface with the following sequence of rules:

Bridge chain: libvirt-I-vnet0, entries: 6, policy: ACCEPT
-p IPv4 -j I-vnet0-ipv4
-p ARP -j I-vnet0-arp
-p ARP -j ACCEPT 
-p 0x8035 -j I-vnet0-rarp
-p 0x835 -j ACCEPT 
-j DROP 

The '-p ARP -j ACCEPT' rule now appears between the jumps.
Since the 'arp' chain has been assigned priority -700 and the 'rarp'
chain -600, the above ordering can now be achieved with the following
rule:

  <rule action='accept' direction='out' priority='-650'>
    <mac protocolid='arp'/>
  </rule>

This patch now sorts the commands generating the above shown jumps into
chains and interleaves their execution with those for generating rules.


Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:18 -05:00
Stefan Berger
f6e80a713f Extend rule priorities into negative numbers
So far rules' priorities have only been valid in the range [0,1000].
Now I am extending their priority into the range [-1000, 1000] for subsequently
being able to sort rules and the access of (jumps into) chains following
priorities.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:18 -05:00
Stefan Berger
19028ad6dc Use the actual names of chains in data structure
Use the name of the chain rather than its type index (enum).
This pushes the later enablement of chains with user-given names
into the XML parser. For now we still only allow those names that
are well known ('root', 'arp', 'rarp', 'ipv4' and 'ipv6').

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:17 -05:00
Stefan Berger
4a410218a0 Use scripting for cleaning and renaming of chains
Use scripts for the renaming and cleaning up of chains. This allows us to get
rid of some of the code that is only capable of renaming and removing chains
whose names are hardcoded.

A shell function 'collect_chains' is introduced that is given the name
of an ebtables chain and then recursively determines the names of all
chains that are accessed from this chain and its sub-chains using 'jumps'.

The resulting list of chain names is then used to delete all the found
chains by first flushing and then deleting them.

The same function is also used for renaming temporary filters to their final
names.

I tested this with the bash and dash as script interpreters.


Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:17 -05:00
Stefan Berger
be39b3e4a5 Make filter creation in root table more flexible
Use the previously introduced chain priorities to sort the chains for access
from an interface's 'root' table and have them created in the proper order.
This gets rid of a lot of code that was previously creating the chains in a 
more hardcoded way.

To determine what protocol a filter is used for evaluation do prefix-
matching, i.e., the filter 'arp' is used to filter for the 'arp' protocol,
'ipv4' for the 'ipv4' protocol and 'arp-xyz' will also be used to filter
for the 'arp' protocol following the prefix 'arp' in its name.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:17 -05:00
Stefan Berger
4df34ec394 Introduce an internal priority for chains
For better handling of the sorting of chains introduce an internally used
priority. Use a lookup table to store the priorities. For now their actual
values do not matter just that the values cause the chains to be properly
sorted through changes in the following patches. However, the values are
chosen as negative so that once they are sorted along with filtering rules
(whose priority may only be positive for now) they will always be instantiated
before them (lower values cause instantiation before higher values). This
is done to maintain backwards compatibility.


Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:17 -05:00
Daniel P. Berrange
91904106a2 Move ifaceMacvtapLinkDump and ifaceGetNthParent functions
Move the ifaceMacvtapLinkDump and ifaceGetNthParent functions
into virnetdevvportprofile.c since they are specific to that
code. This avoids polluting the headers with the Linux specific
netlink data types

* src/util/interface.c, src/util/interface.h: Move
  ifaceMacvtapLinkDump and ifaceGetNthParent functions and delete
  remaining file
* src/util/virnetdevvportprofile.c: Add ifaceMacvtapLinkDump
  and ifaceGetNthParent functions
* src/network/bridge_driver.c, src/nwfilter/nwfilter_gentech_driver.c,
  src/nwfilter/nwfilter_learnipaddr.c, src/util/virnetdevmacvlan.c:
  Remove include of interface.h
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
6e0c4dce0b Rename ifaceCheck to virNetDevValidateConfig
Rename the ifaceCheck method to virNetDevValidateConfig and change
so that it always raises an error and returns -1 on error.

* src/util/interface.c, src/util/interface.h: Rename ifaceCheck
  to virNetDevValidateConfig
* src/nwfilter/nwfilter_gentech_driver.c,
  src/nwfilter/nwfilter_learnipaddr.c: Update for API rename
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
00bba08d24 Move virNetDevGetIndex & virNetDevGetVLanID to virnetdev.c
Move virNetDevGetIndex & virNetDevGetVLanID to virnetdev.c to
suit their functional purpose

* util/interface.c, util/interface.h: Remove virNetDevGetIndex &
  virNetDevGetVLanID
* util/virnetdev.c, util/virnetdev.h: Add virNetDevGetIndex &
  virNetDevGetVLanID
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
ebbb6bd11f Rename ifaceGetIndex and ifaceGetVLAN
Rename the ifaceGetIndex method to virNetDevGetIndex and
ifaceGetVlanID to virNetDevGetVLanID. Also change the error
reporting behaviour to always raise errors and return -1 on
failure

* util/interface.c, util/interface.h: Rename ifaceGetIndex
  and ifaceGetVLAN
* nwfilter/nwfilter_gentech_driver.c, nwfilter/nwfilter_learnipaddr.c,
  nwfilter/nwfilter_learnipaddr.c, util/virnetdevvportprofile.c: Update
  for API renames and error handling changes
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
268085c3bd Remove ifaceUp, ifaceDown, ifaceCtrl & ifaceIsUp APIs
The ifaceUp, ifaceDown, ifaceCtrl & ifaceIsUp APIs can be replaced
with calls to virNetDevSetOnline and virNetDevIsOnline

* src/util/interface.c, src/util/interface.h: Delete ifaceUp,
  ifaceDown, ifaceCtrl & ifaceIsUp
* src/nwfilter/nwfilter_gentech_driver.c, src/util/macvtap.c:
  Update to use virNetDevSetOnline and virNetDevIsOnline
2011-11-15 10:28:02 +00:00
Eric Blake
3b7122c0b2 nwfilter: simplify execution of ebiptables scripts
It's not worth even worrying about a temporary file, unless we
ever expect the script to exceed maximum command-line argument
length limits.

* src/nwfilter/nwfilter_ebiptables_driver.c (ebiptablesExecCLI):
Run the commands as an argument to /bin/sh, rather than worrying
about a temporary file.
(ebiptablesWriteToTempFile): Delete unused function.
2011-11-09 17:10:02 -07:00
Eric Blake
bd6083c9ba nwfilter: avoid failure with noexec /tmp
If /tmp is mounted with the noexec flag (common on security-conscious
systems), then nwfilter will fail to initialize, because we cannot
run any temporary script via virRun("/tmp/script"); but we _can_
use "/bin/sh /tmp/script".  For that matter, using /tmp risks collisions
with other unrelated programs; we already have /var/run/libvirt as a
dedicated temporary directory for use by libvirt.

* src/nwfilter/nwfilter_ebiptables_driver.c
(ebiptablesWriteToTempFile): Use internal directory, not /tmp;
drop attempts to make script executable; and detect close error.
(ebiptablesExecCLI): Switch to virCommand, and invoke the shell to
read the script, rather than requiring an executable script.
2011-11-09 17:02:48 -07:00
Daniel P. Berrange
4c544e6c61 Santize naming of socket address APIs
The socket address APIs in src/util/network.h either take the
form  virSocketAddrXXX, virSocketXXX or virSocketXXXAddr.

Sanitize this so everything is virSocketAddrXXXX, and ensure
that the virSocketAddr parameter is always the first one.

* src/util/network.c, src/util/network.h: Santize socket
  address API naming
* src/conf/domain_conf.c, src/conf/network_conf.c,
  src/conf/nwfilter_conf.c, src/network/bridge_driver.c,
  src/nwfilter/nwfilter_ebiptables_driver.c,
  src/nwfilter/nwfilter_learnipaddr.c,
  src/qemu/qemu_command.c, src/rpc/virnetsocket.c,
  src/util/dnsmasq.c, src/util/iptables.c,
  src/util/virnetdev.c, src/vbox/vbox_tmpl.c: Update for
  API renaming
2011-11-09 17:10:23 +00:00
Stefan Berger
762101c7af nwfilter: tolerate disappearing interfaces while instantiating filter
When instantiating a filter, a VM may disappear and remove its tap interfaces. Tolerate this case and don't report an error.
2011-08-11 06:56:50 -04:00
Laine Stump
f7e18208e1 util: make interface.c functions consistently return < 0 on error
All of the functions in util/interface.c were returning 0 on success,
but some returned -1 on error, and some returned a positive value
(usually the value of errno, but sometimes just 1). Libvirt's standard
is to return < 0 on error (in the case of functions that need to
return errno, -errno is returned.

This patch modifies all functions in interface.c to consistently
return < 0 on error, and makes changes to callers of those functions
where necessary.
2011-07-22 09:27:07 -04:00
Eric Blake
8e22e08935 build: rename files.h to virfile.h
In preparation for a future patch adding new virFile APIs.

* src/util/files.h, src/util/files.c: Move...
* src/util/virfile.h, src/util/virfile.c: ...here, and rename
functions to virFile prefix.  Macro names are intentionally
left alone.
* *.c: All '#include "files.h"' uses changed.
* src/Makefile.am (UTIL_SOURCES): Reflect rename.
* cfg.mk (exclude_file_name_regexp--sc_prohibit_close): Likewise.
* src/libvirt_private.syms: Likewise.
* docs/hacking.html.in: Likewise.
* HACKING: Regenerate.
2011-07-21 10:34:51 -06:00
Eric Blake
833fe8abec util: reject unknown flags, and prefer unsigned flags
Silently ignored flags get in the way of new features that
use those flags.  Also, an upcoming syntax check will favor
unsigned flags.

* src/nodeinfo.h (nodeGetCPUStats, nodeGetMemoryStats): Drop
unused attribute.
* src/interface/netcf_driver.c (interfaceOpenInterface)
(interfaceDefineXML, interfaceCreate, interfaceDestroy): Reject
unknown flags.
* src/network/bridge_driver.c (networkOpenNetwork)
(networkGetXMLDesc): Likewise.
* src/nwfilter/nwfilter_driver.c (nwfilterOpen): Likewise.
* src/secret/secret_driver.c (secretOpen, secretDefineXML)
(secretGetXMLDesc, secretSetValue): Likewise.
* src/util/logging.c (virLogDefineFilter, virLogDefineOutput)
(virLogMessage): Likewise; also use unsigned flags.
* src/util/logging.h (virLogDefineFilter, virLogDefineOutput)
(virLogMessage): Change signature.
* src/util/command.c (virExecWithHook): Likewise.
2011-07-13 09:04:54 -06:00
Eric Blake
1740c38116 drivers: prefer unsigned int for flags
Now that the public APIs always use unsigned flags, the internal
driver callbacks might as well do likewise.

* src/driver.h (vrDrvOpen, virDrvDomainCoreDump)
(virDrvDomainGetXMLDesc, virDrvNetworkGetXMLDesc)
(virDrvNWFilterGetXMLDesc): Update type.
* src/remote/remote_protocol.x (remote_open_args)
(remote_domain_core_dump_args, remote_domain_get_xml_desc_args)
(remote_network_get_xml_desc_args)
(remote_nwfilter_get_xml_desc_args): Likewise.
* src/test/test_driver.c: Update clients.
* src/remote/remote_driver.c: Likewise.
* src/xen/xen_hypervisor.c: Likewise.
* src/xen/xen_hypervisor.h: Likewise.
* src/xen/xen_driver.c: Likewise.
* src/xen/xend_internal.c: Likewise.
* src/xen/xend_internal.h: Likewise.
* src/xen/xm_internal.c: Likewise.
* src/xen/xm_internal.h: Likewise.
* src/xen/xs_internal.c: Likewise.
* src/xen/xs_internal.h: Likewise.
* src/xen/xen_inotify.c: Likewise.
* src/xen/xen_inotify.h: Likewise.
* src/phyp/phyp_driver.c: Likewise.
* src/openvz/openvz_driver.c: Likewise.
* src/vmware/vmware_driver.c: Likewise.
* src/vbox/vbox_driver.c: Likewise.
* src/vbox/vbox_tmpl.c: Likewise.
* src/xenapi/xenapi_driver.c: Likewise.
* src/esx/esx_driver.c: Likewise.
* src/esx/esx_interface_driver.c: Likewise.
* src/esx/esx_network_driver.c: Likewise.
* src/esx/esx_storage_driver.c: Likewise.
* src/esx/esx_device_monitor.c: Likewise.
* src/esx/esx_secret_driver.c: Likewise.
* src/esx/esx_nwfilter_driver.c: Likewise.
* src/interface/netcf_driver.c: Likewise.
* src/nwfilter/nwfilter_driver.c: Likewise.
* src/libxl/libxl_driver.c: Likewise.
* src/qemu/qemu_driver.c: Likewise.
* src/lxc/lxc_driver.c: Likewise.
* src/uml/uml_driver.c: Likewise.
* src/network/bridge_driver.c: Likewise.
* src/secret/secret_driver.c: Likewise.
* src/storage/storage_driver.c: Likewise.
* src/node_device/node_device_hal.c: Likewise.
* src/node_device/node_device_udev.c: Likewise.
* src/remote_protocol-structs: Likewise.
2011-07-07 14:15:37 -06:00
Stefan Berger
ecfbf79541 nwfilter: Return error message about unresolvable variables
This is in response to bugzilla 664629

https://bugzilla.redhat.com/show_bug.cgi?id=664629

The patch below returns an appropriate error message if the chain of
nwfilters is found to contain unresolvable variables and therefore
cannot be instantiated.

Example: The following XMl added to a domain:

    <interface type='bridge'>
      <mac address='52:54:00:9f:80:45'/>
      <source bridge='virbr0'/>
      <model type='virtio'/>
      <filterref filter='test'/>
    </interface>

that references the following filter

<filter name='test' chain='root'>
  <filterref filter='clean-traffic'/>
  <filterref filter='allow-dhcp-server'/>
</filter>

now displays upon 'virsh start mydomain'

error: Failed to start domain mydomain
error: internal error Cannot instantiate filter due to unresolvable variable: DHCPSERVER

'DHPCSERVER' is contained in allow-dhcp-server.
2011-06-27 12:53:59 -04:00
Eric Blake
89d994ad6b build: update gnulib for intprops
Done as a separate commit to make backporting the next patch easier.
We are already using "intprops.h", but this makes it explicit.

* .gnulib: Update, for syntax-check fix.
* bootstrap.conf (gnulib_modules): Make intprops use explicit.
* src/locking/domain_lock.c (includes): Drop unused header.
* src/nwfilter/nwfilter_learnipaddr.c (includes): Use "", not <>,
for gnulib.
2011-06-24 15:52:52 -06:00
Cole Robinson
02e86910e2 Move virRun, virExec*, virFork to util/command
Seems reasonable to have all command wrappers in the same place

v2:
    Dont move SetInherit

v3:
    Comment spelling fix
    Adjust WARN0 comment
    Remove spurious #include movement
    Don't include sys/types.h
    Combine virExec enums

Signed-off-by: Cole Robinson <crobinso@redhat.com>
2011-06-07 14:06:11 -04:00
Stefan Berger
8cc166e76e nwfilter: reorder locks
This patch reorders the locks for the nwfilter updates and the access
the nwfilter objects. In the case that the IP address learning thread
was instantiating filters while an update happened, the previous order
lead to a deadlock.
2011-05-27 16:50:40 -04:00
Matthias Bolte
1ff2b6f6ee Fix sign mismatches between public API, driver API and XDR protocol
In most cases this affects flags parameters that are unsigned in the
public and driver API but signed in the XDR protocol. Switch the
XDR protocol to unsigned for those.

A counterexample is virNWFilterGetXMLDesc. Its flags parameter is signed
in the public API and XDR protocol, but unsigned in the driver API.
2011-05-25 19:18:14 +02:00
Stefan Berger
fcb0e8c227 nwfilter: enable filtering of gratuitous ARP packets
This patch enables filtering of gratuitous ARP packets using the following XML:

<rule action='accept' direction='in' priority='425'>
<arp gratuitous='true'/>
</rule>
2011-05-23 19:41:18 -04:00
Daniel P. Berrange
9b1ae97fdc Add many version number annotations to drivers
Add many version number annotations to the internal driver
tables, to allow hvsupport.html to display more accurate
information
2011-05-16 14:20:48 +01:00
Eric Blake
88d03d4ff1 nwfilter: drop unused flag argument
The public API and RPC over-the-wire format have no flags argument,
so neither should the internal callback API.  This simplifies the
RPC generator.

* src/driver.h (virDrvNWFilterDefineXML): Drop argument that does
not match public API.
* src/nwfilter/nwfilter_driver.c (nwfilterDefine): Likewise.
* src/libvirt.c (virNWFilterDefineXML): Likewise.
* daemon/remote_generator.pl: Drop special case.
2011-05-11 19:26:59 -06:00
Lai Jiangshan
b65f37a4a1 libvirt,logging: cleanup VIR_XXX0()
These VIR_XXXX0 APIs make us confused, use the non-0-suffix APIs instead.

How do these coversions works? The magic is using the gcc extension of ##.
When __VA_ARGS__ is empty, "##" will swallow the "," in "fmt," to
avoid compile error.

example: origin				after CPP
	high_level_api("%d", a_int)	low_level_api("%d", a_int)
	high_level_api("a  string")	low_level_api("a  string")

About 400 conversions.

8 special conversions:
VIR_XXXX0("") -> VIR_XXXX("msg") (avoid empty format) 2 conversions
VIR_XXXX0(string_literal_with_%) -> VIR_XXXX(%->%%) 0 conversions
VIR_XXXX0(non_string_literal) -> VIR_XXXX("%s", non_string_literal)
  (for security) 6 conversions

Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
2011-05-11 12:41:14 -06:00
Matthias Bolte
9817604afc Rename internal DumpXML functions to GetXMLDesc
This matches the public API and helps to get rid of some special
case code in the remote generator.

Rename driver API functions and XDR protocol structs.

No functional change included outside of the remote generator.
2011-05-10 20:32:41 +02:00
Eric Blake
f84fe150e1 maint: avoid comparisons to bool constants
HACKING already mentions that comparisons against literal 'true'
are unsafe; for consistency, also shorten comparisons against 'false'.

* src/conf/domain_conf.c (virDomainNetDefParseXML): Simplify.
* src/nwfilter/nwfilter_gentech_driver.c
(virNWFilterDomainFWUpdateCB): Likewise.
* tools/virsh.c (cmdVolDownload, vshCommandRun, vshPrintExtra):
Likewise.
2011-05-06 10:28:28 -06:00
Eric Blake
68ea80cfdd maint: rename virBufferVSprintf to virBufferAsprintf
We already have virAsprintf, so picking a similar name helps for
seeing a similar purpose.  Furthermore, the prefix V before printf
generally implies 'va_list', even though this variant was '...', and
the old name got in the way of adding a new va_list version.

global rename performed with:

$ git grep -l virBufferVSprintf \
  | xargs -L1 sed -i 's/virBufferVSprintf/virBufferAsprintf/g'

then revert the changes in ChangeLog-old.
2011-05-05 13:47:40 -06:00
Matthias Bolte
0e7c7b8b32 nwfilter: Fix memory leak in the ebtables subdriver
Call shutdown functions for all subcomponents in nwfilterDriverShutdown.

Make sure that this shutdown functions can safely be called multiple times
and independent from the actual subcomponents state.
2011-04-30 17:37:54 +02:00
Stefan Berger
973b681bdf nwfilter: no support for direct type of interface
Ebtables filtering doesn't work on macvtap device. Remove support for direct type of interface.
2011-04-19 16:23:59 -04:00
Christophe Fergeau
454e50beee Fix gcc 4.6 warnings
gcc 4.6 warns when a variable is initialized but isn't used afterwards:

vmware/vmware_driver.c:449:18: warning: variable 'vmxPath' set but not used [-Wunused-but-set-variable]

This patch fixes these warnings. There are still 2 offending files:

- vbox_tmpl.c: the variable is used inside an #ifdef and is assigned several
  times outside of #ifdef. Fixing the warning would have required wrapping
  all the assignment inside #ifdef which hurts readability.

vbox/vbox_tmpl.c: In function 'vboxAttachDrives':
vbox/vbox_tmpl.c:3918:22: warning: variable 'accessMode' set but not used [-Wunused-but-set-variable]

- esx_vi_types.generated.c: the name implies it's generated code and I
  didn't want to dive into the code generator

esx/esx_vi_types.generated.c: In function 'esxVI_FileQueryFlags_Free':
esx/esx_vi_types.generated.c:1203:3: warning: variable 'item' set but not used [-Wunused-but-set-variable]
2011-04-14 19:09:12 +02:00
Stefan Berger
6ab24feb44 nwfilters: support for TCP flags evaluation
This patch adds support for the evaluation of TCP flags in nwfilters.

It adds documentation to the web page and extends the tests as well.
Also, the nwfilter schema is extended.

The following are some example for rules using the tcp flags:

<rule action='accept' direction='in'>
    <tcp state='NONE' flags='SYN/ALL' dsptportstart='80'/>
</rule>
<rule action='drop' direction='in'>
    <tcp state='NONE' flags='SYN/ALL'/>
</rule>
2011-04-07 20:13:38 -04:00
Eric Blake
208a044a54 command: properly diagnose process exit via signal
Child processes don't always reach _exit(); if they die from a
signal, then any messages should still be accurate.  Most users
either expect a 0 status (thankfully, if status==0, then
WIFEXITED(status) is true and WEXITSTATUS(status)==0 for all
known platforms) or were filtering on WIFEXITED before printing
a status, but a few were missing this check.  Additionally,
nwfilter_ebiptables_driver was making an assumption that works
on Linux (where WEXITSTATUS shifts and WTERMSIG just masks)
but fails on other platforms (where WEXITSTATUS just masks and
WTERMSIG shifts).

* src/util/command.h (virCommandTranslateStatus): New helper.
* src/libvirt_private.syms (command.h): Export it.
* src/util/command.c (virCommandTranslateStatus): New function.
(virCommandWait): Use it to also diagnose status from signals.
* src/security/security_apparmor.c (load_profile): Likewise.
* src/storage/storage_backend.c
(virStorageBackendQEMUImgBackingFormat): Likewise.
* src/util/util.c (virExecDaemonize, virRunWithHook)
(virFileOperation, virDirCreate): Likewise.
* daemon/remote.c (remoteDispatchAuthPolkit): Likewise.
* src/nwfilter/nwfilter_ebiptables_driver.c (ebiptablesExecCLI):
Likewise.
2011-03-25 05:34:48 -06:00
Phil Petty
5a81401235 fixes for several memory leaks
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-03-04 09:52:12 -07:00
Daniel P. Berrange
16ba2aafc4 Allow hash tables to use generic pointers as keys
Relax the restriction that the hash table key must be a string
by allowing an arbitrary hash code generator + comparison func
to be provided

* util/hash.c, util/hash.h: Allow any pointer as a key
* internal.h: Include stdbool.h as standard.
* conf/domain_conf.c, conf/domain_conf.c,
  conf/nwfilter_params.c, nwfilter/nwfilter_gentech_driver.c,
  nwfilter/nwfilter_gentech_driver.h, nwfilter/nwfilter_learnipaddr.c,
  qemu/qemu_command.c, qemu/qemu_driver.c,
  qemu/qemu_process.c, uml/uml_driver.c,
  xen/xm_internal.c: s/char */void */ in hash callbacks
2011-02-25 13:00:54 +00:00
Daniel P. Berrange
6952708ca4 Remove deallocator parameter from hash functions
Since the deallocator is passed into the constructor of
a hash table it is not desirable to pass it into each
function again. Remove it from all functions, but provide
a virHashSteal to allow a item to be removed from a hash
table without deleteing it.

* src/util/hash.c, src/util/hash.h: Remove deallocator
  param from all functions. Add virHashSteal
* src/libvirt_private.syms: Add virHashSteal
* src/conf/domain_conf.c, src/conf/nwfilter_params.c,
  src/nwfilter/nwfilter_learnipaddr.c,
  src/qemu/qemu_command.c, src/xen/xm_internal.c: Update
  for changed hash API
2011-02-25 13:00:46 +00:00
Eric Blake
03ba07cb73 hash: make virHashFree more free-like
Two-argument free functions are uncommon; match the style elsewhere
by caching the callback at creation.

* src/util/hash.h (virHashCreate, virHashFree): Move deallocator
argument to creation.
* cfg.mk (useless_free_options): Add virHashFree.
* src/util/hash.c (_virHashTable): Track deallocator.
(virHashCreate, virHashFree): Update to new signature.
* src/conf/domain_conf.c (virDomainObjListDeinit)
(virDomainObjListInit, virDomainDiskDefForeachPath)
(virDomainSnapshotObjListDeinit, virDomainSnapshotObjListInit):
Update callers.
* src/conf/nwfilter_params.c (virNWFilterHashTableFree)
(virNWFilterHashTableCreate): Likewise.
* src/conf/nwfilter_conf.c (virNWFilterTriggerVMFilterRebuild):
Likewise.
* src/cpu/cpu_generic.c (genericHashFeatures, genericBaseline):
Likewise.
* src/xen/xm_internal.c (xenXMOpen, xenXMClose): Likewise.
* src/nwfilter/nwfilter_learnipaddr.c (virNWFilterLearnInit)
(virNWFilterLearnShutdown): Likewise.
* src/qemu/qemu_command.c (qemuDomainPCIAddressSetCreate)
(qemuDomainPCIAddressSetFree): Likewise.
* src/qemu/qemu_process.c (qemuProcessWaitForMonitor): Likewise.
2011-02-21 08:27:02 -07:00
Stefan Berger
912d170f87 nwfilter: enable rejection of packets
This patch adds the possibility to not just drop packets, but to also have them rejected where iptables at least sends an ICMP msg back to the originator. On ebtables this again maps into dropping packets since rejecting is not supported.

I am adding 'since 0.8.9' to the docs assuming this will be the next version of libvirt.
2011-02-18 20:13:40 -05:00
Christophe Fergeau
9905c69e4f remove no longer needed calls to virReportOOMError
Now that the virHash handling functions call virReportOOMError by
themselves when needed, users of the virHash API no longer need to
do it by themselves. Since users of the virHash API were not
consistently calling virReportOOMError after memory failures from
the virHash code, this has the added benefit of making OOM
reporting from this code more consistent and reliable.
2011-02-17 16:59:14 -07:00
Stefan Berger
13e9ba7c2b nwfilter: reorder match extensions relative to state match
This patch reorders the connlimit and comment match extensions relative to the state match (-m state); connlimit being most useful if found after a -m state --state NEW and not before it.
2011-02-14 14:10:24 -05:00
Daniel P. Berrange
525434dd60 Avoid warnings from nwfilter driver when run non-root
When run non-root the nwfilter driver logs error messages about
being unable to find iptables/ebtables commands (they are in
/sbin which isn't in $PATH). The nwfilter driver can't ever work
as non-root, so simply skip it entirely thus avoiding the error
messages

* src/conf/nwfilter_conf.h, src/nwfilter/nwfilter_driver.c,
  src/nwfilter/nwfilter_gentech_driver.c,
  src/nwfilter/nwfilter_gentech_driver.h: Pass 'bool privileged'
  flag down to final driver impl
* src/nwfilter/nwfilter_ebiptables_driver.c: Skip initialization
  if not privileged
2011-02-10 14:29:57 +00:00
Matthias Bolte
dc52cab126 Prefer C style comments over C++ ones
Pure cosmetic change.
2011-01-29 00:59:45 +01:00
Matthias Bolte
8c6d61162f Fix misuse of VIR_ERR_INVALID_* error code
VIR_ERR_INVALID_* is meant for invalid pointers only.
2011-01-18 23:14:37 +01:00
Matthias Bolte
2c0db5b5dc Simplify "NWFilterPool" to "NWFilter"
The public object is called NWFilter but the corresponding private
object is called NWFilterPool. I don't see compelling reasons for this
Pool suffix. One might argue that an NWFilter is a "pool" of rules, etc.

Remove the Pool suffix from NWFilterPool. No functional change included.
2011-01-18 23:14:37 +01:00
Stefan Berger
52834904d2 nwfilter: re-order lock grabbed by IP addr. learn thread
The IP address learning thread was causing a deadlock when it instantiated a filter while a filter update/change was ongoing. The reason for this was the ordering of locks due to the following calls

virNWFilterUnlockFilterUpdates()
virNWFilterPoolObjFindByName()

The below patch now puts the order of the locks in the above shown order when instantiating the filter from the IP address learning thread.
2010-11-19 20:41:25 -05:00
Eric Blake
0d5f54bb21 maint: use gnulib configmake rather than open-coding things
* bootstrap.conf (gnulib_modules): Add configmake.
* daemon/Makefile.am (libvirtd_CFLAGS): Drop defines provided by
gnulib.
* src/Makefile.am (INCLUDES): Likewise.
* tests/Makefile.am (INCLUDES): Likewise.
* tools/Makefile.am (virsh_CFLAGS): Likewise.
* daemon/libvirtd.c (qemudInitPaths, usage, main): Update
clients.
* src/cpu/cpu_map.c (CPUMAPFILE): Likewise.
* src/driver.c (DEFAULT_DRIVER_DIR): Likewise.
* src/internal.h (_): Likewise.
* src/libvirt.c (virInitialize): Likewise.
* src/lxc/lxc_conf.h (LXC_CONFIG_DIR, LXC_STATE_DIR, LXC_LOG_DIR):
Likewise.
* src/lxc/lxc_conf.c (lxcCapsInit, lxcLoadDriverConfig):
Likewise.
* src/network/bridge_driver.c (NETWORK_PID_DIR)
(NETWORK_STATE_DIR, DNSMASQ_STATE_DIR, networkStartup): Likewise.
* src/nwfilter/nwfilter_driver.c (nwfilterDriverStartup):
Likewise.
* src/qemu/qemu_conf.c (qemudLoadDriverConfig): Likewise.
* src/qemu/qemu_driver.c (qemudStartup): Likewise.
* src/remote/remote_driver.h (LIBVIRTD_PRIV_UNIX_SOCKET)
(LIBVIRTD_PRIV_UNIX_SOCKET_RO, LIBVIRTD_CONFIGURATION_FILE)
(LIBVIRT_PKI_DIR): Likewise.
* src/secret/secret_driver.c (secretDriverStartup): Likewise.
* src/security/security_apparmor.c (VIRT_AA_HELPER): Likewise.
* src/security/virt-aa-helper.c (main): Likewise.
* src/storage/storage_backend_disk.c (PARTHELPER): Likewise.
* src/storage/storage_driver.c (storageDriverStartup): Likewise.
* src/uml/uml_driver.c (TEMPDIR, umlStartup): Likewise.
* src/util/hooks.c (LIBVIRT_HOOK_DIR): Likewise.
* tools/virsh.c (main): Likewise.
* docs/hooks.html.in: Likewise.
2010-11-17 08:58:58 -07:00
Stefan Berger
d4897acff8 nwfilter: also purge ip(6)tables rules before detecting IP address
Rather than only cleaning any remaining ebtables rules, also clean those applied to iptables and ip6tables when detecting the IP address of an interface. Previous applied iptables rules may hinder DHCP packets.
2010-11-16 21:18:21 -05:00
Eric Blake
61af79c141 nwfilter: use /bin/sh rather than requiring bash
* src/nwfilter/nwfilter_ebiptables_driver.c (CMD_EXEC): Fix syntax
error in previous patch.
Reported by Stefan Berger.
2010-11-16 07:53:32 -07:00
Eric Blake
61cdff653c nwfilter: use /bin/sh rather than requiring bash
* src/nwfilter/nwfilter_ebiptables_driver.c
(ebiptablesWriteToTempFile): Use /bin/sh.
(bash_cmd_path): Delete.
(ebiptablesDriverInit, ebiptablesDriverShutdown): No need to
search for bash.
(CMD_EXEC): Prefer $() over ``, since we can assume POSIX.
(iptablesSetupVirtInPost): Use portable 'test' syntax.
(iptablesLinkIPTablesBaseChain): Use POSIX $(()) syntax.
2010-11-15 16:14:33 -07:00
Stefan Berger
60ae1c34ad bye to close(), welcome to VIR_(FORCE_)CLOSE()
Using automated replacement with sed and editing I have now replaced all
occurrences of close() with VIR_(FORCE_)CLOSE() except for one, of
course. Some replacements were straight forward, others I needed to pay
attention. I hope I payed attention in all the right places... Please
have a look. This should have at least solved one more double-close
error.
2010-11-09 15:48:48 -05:00
Daniel P. Berrange
a8ae7d19f4 Remove all use of inet_pton and inet_ntop
The  inet_pton and inet_ntop functions are obsolete, replaced
by getaddrinfo+getnameinfo with the AI_NUMERICHOST flag set.
These can be accessed via the virSocket APIs.

The bridge.c code had methods for fetching the IP address of
a bridge which used inet_ntop. Aside from the use of inet_ntop
these methods are broken, because a NIC can have multiple
addresses and this only returns one address. Since the methods
are never used, just remove them.

* src/conf/network_conf.c, src/nwfilter/nwfilter_learnipaddr.c:
  Replace inet_pton and inet_ntop with virSocket APIs
* src/util/bridge.c, src/util/bridge.h: Remove unused methods
  which called inet_ntop.
2010-10-22 11:59:18 +01:00
Daniel P. Berrange
497adba2d4 Expand virSocketFormat to be more flexible
The getnameinfo() function is more flexible than inet_ntop()
avoiding the need to if/else the code based on socket family.
Also make it support UNIX socket addrs and allow inclusion
of a port (service) address. Finally do proper error reporting
via normal APIs.

* src/conf/domain_conf.c, src/nwfilter/nwfilter_ebiptables_driver.c,
  src/qemu/qemu_conf.c: Fix error handling with virSocketFormat
* src/util/network.c: Rewrite virSocketFormat to use getnameinfo
  and cope with UNIX socket addrs.
2010-10-22 11:24:12 +01:00
Daniel P. Berrange
7ab7d17bfb Remove pointless nwIPAddress struct & void *casts
The nwIPAddress was simply a wrapper about virSocketAddr.
Just use the latter directly, removing all the extra field
de-references from code & helper APIs for parsing/formatting.

Also remove all the redundant casts from strong types to
void * and then immediately back to strong types.

* src/conf/nwfilter_conf.h: Remove nwIPAddress
* src/conf/nwfilter_conf.c, src/nwfilter/nwfilter_ebiptables_driver.c:
  Update to use virSocketAddr and remove void * casts.
2010-10-22 11:21:27 +01:00
Stefan Berger
c2fbdf1088 nwfilter: avoid dir. enforcement for certain types of rules
Avoid the enforcement of direction if
- icmp rules specify the type/code information
- the 'skipMatch' variable is set to 'true'
2010-10-19 19:25:37 -04:00
Stefan Berger
7d79da247a nwfilter: changes to rules in VM->host table
In the table built for traffic coming from the VM going to the host make the following changes:

- don't ACCEPT the packets but do a 'RETURN' and let the host-specific firewall rules in subsequent rules evaluate whether the traffic is allowed to enter

- use the '-m state' in the rules as everywhere else
2010-10-19 11:35:58 -04:00
Stefan Berger
2b3df906f3 nwfilter: cut off connections after changing filters
The following filter transition from a filter allowing incoming TCP connections

  <rule action='accept' direction='in' priority='401'>
    <tcp/>
  </rule>
  <rule action='accept' direction='out' priority='500'>
    <tcp/>
  </rule>

to one that does not allow them

  <rule action='drop' direction='in' priority='401'>
    <tcp/>
  </rule>
  <rule action='accept' direction='out' priority='500'>
    <tcp/>
  </rule>

did previously not cut off existing (ssh) connections but only prevented newly initiated ones. The attached patch allows to cut off existing connections as well, thus enforcing what the filter is showing.

I had only tested with a configuration where the physical interface is connected to the bridge where the filters are applied. This patch now also solves a filtering problem where the physical interface is not connected to the bridge, but the bridge is given an IP address and the host routes between bridge and physical interface. Here the filters drop non-allowed traffic on the outgoing side on the host.
2010-10-14 08:54:03 -04:00
Stefan Berger
4435f3c477 nwfilter: resolve deadlock between VM ops and filter update
This is from a bug report and conversation on IRC where Soren reported that while a filter update is occurring on one or more VMs (due to a rule having been edited for example), a deadlock can occur when a VM referencing a filter is started.

The problem is caused by the two locking sequences of

qemu driver, qemu domain, filter             # for the VM start operation
filter, qemu_driver, qemu_domain            # for the filter update operation

that obviously don't lock in the same order. The problem is the 2nd lock sequence. Here the qemu_driver lock is being grabbed in qemu_driver:qemudVMFilterRebuild()

The following solution is based on the idea of trying to re-arrange the 2nd sequence of locks as follows:

qemu_driver, filter, qemu_driver, qemu_domain

and making the qemu driver recursively lockable so that a second lock can occur, this would then lead to the following net-locking sequence

qemu_driver, filter, qemu_domain

where the 2nd qemu_driver lock has been ( logically ) eliminated.

The 2nd part of the idea is that the sequence of locks (filter, qemu_domain) and (qemu_domain, filter) becomes interchangeable if all code paths where filter AND qemu_domain are locked have a preceding qemu_domain lock that basically blocks their concurrent execution

So, the following code paths exist towards qemu_driver:qemudVMFilterRebuild where we now want to put a qemu_driver lock in front of the filter lock.

-> nwfilterUndefine()   [ locks the filter ]
    -> virNWFilterTestUnassignDef()
        -> virNWFilterTriggerVMFilterRebuild()
            -> qemudVMFilterRebuild()

-> nwfilterDefine()
    -> virNWFilterPoolAssignDef() [ locks the filter ]
        -> virNWFilterTriggerVMFilterRebuild()
            -> qemudVMFilterRebuild()

-> nwfilterDriverReload()
    -> virNWFilterPoolLoadAllConfigs()
        ->virNWFilterPoolObjLoad()
            -> virNWFilterPoolAssignDef() [ locks the filter ]
                -> virNWFilterTriggerVMFilterRebuild()
                    -> qemudVMFilterRebuild()

-> nwfilterDriverStartup()
    -> virNWFilterPoolLoadAllConfigs()
        ->virNWFilterPoolObjLoad()
            -> virNWFilterPoolAssignDef() [ locks the filter ]
                -> virNWFilterTriggerVMFilterRebuild()
                    -> qemudVMFilterRebuild()

Qemu is not the only driver using the nwfilter driver, but also the UML driver calls into it. Therefore qemuVMFilterRebuild() can be exchanged with umlVMFilterRebuild() along with the driver lock of qemu_driver that can now be a uml_driver. Further, since UML and Qemu domains can be running on the same machine, the triggering of a rebuild of the filter can touch both types of drivers and their domains.

In the patch below I am now extending each nwfilter callback driver with functions for locking and unlocking the (VM) driver (UML, QEMU) and introduce new functions for locking all registered callback drivers and unlocking them. Then I am distributing the lock-all-cbdrivers/unlock-all-cbdrivers call into the above call paths. The last shown callpath starting with nwfilterDriverStart() is problematic since it is initialize before the Qemu and UML drives are and thus a lock in the path would result in a NULL pointer attempted to be locked -- the call to virNWFilterTriggerVMFilterRebuild() is never called, so we never lock either the qemu_driver or the uml_driver in that path. Therefore, only the first 3 paths now receive calls to lock and unlock all callback drivers. Now that the locks are distributed where it matters I can remove the qemu_driver and uml_driver lock from qemudVMFilterRebuild() and umlVMFilterRebuild() and not requiring the recursive locks.

For now I want to put this out as an RFC patch. I have tested it by 'stretching' the critical section after the define/undefine functions each lock the filter so I can (easily) concurrently execute another VM operation (suspend,start). That code is in this patch and if you want you can de-activate it. It seems to work ok and operations are being blocked while the update is being done.
I still also want to verify the other assumption above that locking filter and qemu_domain always has a preceding qemu_driver lock.
2010-10-13 10:33:26 -04:00
Guido Günther
b2d7cedeb9 Pass -n to ip(6)tables
to avoid long timeouts waiting for DNS servers
2010-10-08 23:54:03 +02:00
Stefan Berger
5b0c71ee07 nwfilter: Instantiate state match in ip(6)tables rules
In this patch I am extending the rule instantiator to create the state
match according to the state attribute in the XML. Only one iptables
rule in the incoming or outgoing direction will be created for a rule
in direction 'in' or 'out' respectively. A rule in direction 'inout' does
get iptables rules in both directions.
2010-10-07 06:41:37 -04:00
Stefan Berger
2e224f197c nwfilter: fix memory leaks
Fixing memory leak shown by valgrind and freeing buffer in two more places.
2010-10-04 06:34:05 -04:00
Stefan Berger
b00f41a1d2 nwfilter: Instantiate comments in ip(6)tables rules
In this patch I am extending the rule instantiator to create the comment
node where supported, which is the case for iptables and ip6tables.

Since commands are written in the format

cmd='iptables ...-m comment --comment \"\" '

certain characters ('`) in the comment need to be escaped to
prevent comments from becoming commands themselves or cause other
forms of (bash) substitutions. I have tested this with various input and in
my tests the input made it straight into the comment. A test case for TCK
will be provided separately that tests this.
2010-09-30 15:56:09 -04:00
Justin Clift
48005255b0 nwfilter: remove recently added workaround define for macos x
This reverses commit 04c3704, which added a define to nwfilter to
allow libvirtd compilation on Mac OS X.  Stefan Bergers commit, 2e7294d,
is the proper solution, removing the requirement for nwfilter on non-Linux.
2010-09-28 22:41:11 +10:00
Justin Clift
04c3704e70 nwfilter: add a missing define, so libvirtd builds on macos x
The nwfilter code uses ETH_ALEN, which isn't defined on MacOS X.
This is a simple workaround, to add it when missing.
2010-09-28 01:31:52 +10:00
Stefan Berger
570d040435 nwfilter: report if ip(6)tables rules would not be active
The patch below reports a warning in the log if the generated ip(6)tables rules would not be effective due to the proc filesystem entries

    /proc/sys/net/bridge/bridge-nf-call-iptables
    /proc/sys/net/bridge/bridge-nf-call-ip6tables

containing a '0'. The warning tells the user what to do. I am rate-limiting the warning message to appear only every 10 seconds.
2010-09-24 12:06:17 -04:00
Eric Blake
52baf647ca nwfilter: use consistent OOM reporting
* src/nwfilter/nwfilter_driver.c (nwfilterLog): Delete.
(nwfilterDriverStartup): Use virReportOOMError instead.
2010-08-19 13:14:41 -06:00
Stefan Berger
cf6f8b9a97 nwfilter: extend nwfilter reload support
In this patch I am extending and fixing the nwfilter module's reload support to stop all ongoing threads (for learning IP addresses of interfaces) and rebuild the filtering rules of all interfaces of all VMs when libvirt is started. Now libvirtd rebuilds the filters upon the SIGHUP signal and libvirtd restart.

About the patch: The nwfilter functions require a virConnectPtr. Therefore I am opening a connection in qemudStartup, which later on needs to be closed outside where the driver lock is held since otherwise it ends up in a deadlock due to virConnectClose() trying to lock the driver as well.

I have tested this now for a while with several machines running and needing the IP address learner thread(s). The rebuilding of the firewall rules seems to work fine following libvirtd restart or a SIGHUP. Also the termination of libvirtd worked fine.
2010-08-16 12:59:54 -04:00
Stefan Berger
753d76e0cd nwfilter: Discard class D,E IP addresses when sniffing pkts
When sniffing the network traffic, discard class D and E IP addresses when sniffing traffic. This was a reason why filters were not correctly rebuilt on VMs on the local 192.* network when libvirt was restarted and those VMs did not use a DHCP request to get its IP address.
2010-08-13 16:41:39 -04:00
Stefan Berger
bed3a217f6 nwfilter: serialize execution of scripts with ebtables cmds
While testing the SIGHUP handling and reloading of the nwfilter driver, I found that when the filters are rebuilt and mutlipe threads handled the individual interfaces, concurrently running multiple external bash scripts causes strange failures even though the executed ebtables commands are working on different tables for different interfaces. I cannot say for sure where the concurrency problems are caused, but introducing this lock definitely helps.
2010-08-13 15:47:10 -04:00
Stefan Berger
cab5a52aa2 nwfilter: fix loadable module support
Following Daniel Berrange's multiple helpful suggestions for improving
this patch and introducing another driver interface, I now wrote the
below patch where the nwfilter driver registers the functions to
instantiate and teardown the nwfilters with a function in
conf/domain_nwfilter.c called virDomainConfNWFilterRegister. Previous
helper functions that were called from qemu_driver.c and qemu_conf.c
were move into conf/domain_nwfilter.h with slight renaming done for
consistency. Those functions now call the function expored by
domain_nwfilter.c, which in turn call the functions of the new driver
interface, if available.
2010-06-21 14:18:31 -04:00
Stefan Berger
51d3fb0276 nwfilter: add XML attribute to control iptables state match
This patch adds an optional XML attribute to a nwfilter rule to give the user control over whether the rule is supposed to be using the iptables state match or not. A rule may now look like shown in the XML below with the statematch attribute either having value '0' or 'false' (case-insensitive).

[...]
<rule action='accept' direction='in' statematch='false'>
<tcp srcmacaddr='1:2:3:4:5:6'
           srcipaddr='10.1.2.3' srcipmask='32'
           dscp='33'
           srcportstart='20' srcportend='21'
           dstportstart='100' dstportend='1111'/>
</rule>
[...]

I am also extending the nwfilter schema and add this attribute to a test case.
2010-06-17 14:12:34 -04:00
Stefan Berger
2dce970162 nwfilter: use match target on incoming traffic
The following patch enables the iptables match target to be used by
default for incoming traffic. So far it has only be used for outgoing
traffic.
2010-06-17 07:15:20 -04:00
Jim Meyering
0058184c4e ebiptablesWriteToTempFile: don't close a negative file descriptor
* src/nwfilter/nwfilter_ebiptables_driver.c (ebiptablesWriteToTempFile):
Skip the close if "fd" is negative.
2010-05-18 16:55:26 +02:00
Stefan Berger
018fd697b6 nwfilter: skip some interfaces on filter update
When a filter is updated, only those interfaces must have their old
rules cleared that either reference the filter directly or indirectly
through another filter. Remember between the different steps of the
instantiation of the filters which interfaces must be skipped. I am
using a hash map to remember the names of the interfaces and store a
bogus pointer to ~0 into it that need not be freed.
2010-05-03 18:14:58 -04:00
Stefan Berger
5c77fddf4e pass info where request stems from to have rules applied
For the decision on whether to instantiate the rules, the check for a
pending IP address learn request is not sufficient since then only the
thread could instantiate the rules. So, a boolean needs to be passed
when the thread instantiates the filter rules late and the IP address
learn request is still pending in order to override the check for the
pending learn request. If the rules are to be updated while the thread
is active, this will not be done immediately but the thread will do that
later on.
2010-05-03 18:11:48 -04:00
Stefan Berger
5054e89272 Prevent updates while IP address learn thread is running
Prevent updating and tearing down of filter while the IP
address learning thread is running and has its own filtering
rules applied.
2010-04-30 08:12:26 -04:00
Stefan Berger
ebacb31fb5 Syncronize the teardown of rules with the thread
Introduce a function to notify the IP address learning
thread to terminate and thus release the lock on the interface.
Notify the thread before grabbing the lock on the interface
and tearing down the rules. This prevents a 'virsh destroy' to
tear down the rules that the IP address learning thread has
applied.
2010-04-30 08:10:12 -04:00
Stefan Berger
59fe163f2f Clean all tables before applying 'basic' rules
The functions invoked by the IP address learning thread
that apply some basic filtering rules did not clean up
any previous filtering rules that may still be there
(due to a libvirt restart for example). With the
patch below all the rules are cleaned up first.

Also, I am introducing a function to drop all traffic
in case the IP address learning thread could not apply
the rules.
2010-04-30 08:06:18 -04:00
Stefan Berger
7c66c033a9 nwfilter: Also pick IP address from a DHCP ACK message
The local DHCP server on virtbr0 sends DHCP ACK messages when a VM is
started and requests an IP address while the initial DHCP lease on the
VM's MAC address hasn't expired. So, also pick the IP address of the VM
if that type of message is seen.
Thanks to Gerhard Stenzel for providing a test case for this.

Changes from V1 to V2:
- cleanup: replacing DHCP option numbers through constants
2010-04-30 07:51:47 -04:00
Stefan Berger
aea68ce906 nwfilter: add support for RAPR protocol
This patch adds support for the RARP protocol. This may be needed due to
qemu sending out a RARP packet (at least that's what it seems to want to
do even though the protocol id is wrong) when migration finishes and
we'd need a rule to let the packets pass.

Unfortunately my installation of ebtables does not understand -p RARP
and also seems to otherwise depend on strings in /etc/ethertype
translated to protocol identifiers. Therefore I need to pass -p 0x8035
for RARP. To generally get rid of the dependency of that file I switch
all so far supported protocols to use their protocol identifier in the
-p parameter rather than the string.

I am also extending the schema and added a test case.

changes from v1 to v2:
- added test case into patch
2010-04-27 07:26:12 -04:00
Stefan Berger
5c7c755f50 nwfilter: enable hex number inputs in filter XML
With this patch I want to enable hex number inputs in the filter XML. A
number that was entered as hex is also printed as hex unless a string
representing the meaning can be found.

I am also extending the schema and adding a test case. A problem with
the DSCP value is fixed on the way as well.

Changes from V1 to V2:

- using asHex boolean in all printf type of functions to select the
output format in hex or decimal format
2010-04-26 13:50:40 -04:00
Daniel P. Berrange
98bd5e6c5a Fix crash in nwfilter driver check
The nwfilterDriverActive() could de-reference a NULL pointer
if it hadn't be started at the point it was called. It was
also not thread safe, since it lacked locking around data
accesses.

* src/nwfilter/nwfilter_driver.c: Fix locking & NULL checks
  in nwfilterDriverActive()
2010-04-23 11:06:30 +01:00
Stefan Berger
647c26c886 Changes from V1 to V2:
- using INT_BUFSIZE_BOUND() to determine the length of the buffersize
for printing and integer into

 - not explicitly initializing static var threadsTerminate to false
anymore, since that's done automatically

Changes after V2:
  - removed while looks in case of OOM error
  - removed on ifaceDown() call
  - preceding one ifaceDown() call with an ifaceCheck() call

Since the name of an interface can be the same between stops and starts
of different VMs I have to switch the IP address learning thread to use
the index of the interface to determine whether an interface is still
available or not - in the case of macvtap the thread needs to listen for
traffic on the physical interface, thus having to time out periodically
to check whether the VM's macvtap device is still there as an indication
that the VM is still alive. Previously the following sequence of 2 VMs
with macvtap device

virsh start testvm1; virsh destroy testvm1 ; virsh start testvm2

would not terminate the thread upon testvm1's destroy since the name of
the interface on the host could be the same (i.e, macvtap0) on testvm1
and testvm2, thus it was easily race-able. The thread would then
determine the IP address parameter for testvm2 but apply the rule set
for testvm1. :-(
I am also introducing a lock for the interface (by name) that the thread
must hold while it listens for the traffic and releases when it
terminates upon VM termination or 0.5 second thereafter. Thus, the new
thread for a newly started VM with the same interface name will not
start while the old one still holds the lock. The only other code that I
see that also needs to grab the lock to serialize operation is the one
that tears down the firewall that were established on behalf of an
interface.

I am moving the code applying the 'basic' firewall rules during the IP
address learning phase inside the thread but won't start the thread
unless it is ensured that the firewall driver has the ability to apply
the 'basic' firewall rules.
2010-04-22 14:58:57 -04:00
Stefan Berger
abce152a49 nwfilter: add support for connlimit match
This patch adds support for the connlimit match in iptables that is used
to limit the number of outgoing directions.
2010-04-20 17:14:38 -04:00
Stefan Berger
c8f4dcca6a Extend fwall-drv interface and call functions via interface
I am moving some of the eb/iptables related functions into the interface
of the firewall driver and am making them only accessible via the driver's
interface. Otherwise exsiting code is adapted where needed. I am adding one
new function to the interface that checks whether the 'basic' rules can be
applied,  which will then be used by a subsequent patch.
2010-04-20 17:07:15 -04:00
Matthias Bolte
051df19e0e Replace printf with logging macros 2010-04-17 15:02:28 +02:00
Jiri Denemark
7a2c6222a9 Use virCheckFlags for APIs added in 0.8.0 2010-04-16 14:05:50 +02:00
Stefan Berger
d2327278fb nwfilter: Clear all state tracking from a drop rule
Don't use state-matching in a drop rule.
2010-04-16 07:34:36 -04:00
Stefan Berger
41b087198d nwfilter: fix tear down order and consolidate functions
To avoid race-conditions, the tear down of a filter has to happen before
the tap interface disappears and another tap interface with the same
name can re-appear. This patch tries to fix this. In one place, where
communication with the qemu monitor may fail, I am only tearing the
filters down after knowing that the function did not fail.

I am also moving the tear down functions into an include file for other
drivers to reuse.
2010-04-15 10:49:24 -04:00
Stefan Berger
c41873f40e Trivial fix: Add braces to for statement to avoid crashes
I am adding braces around the for statement that are now needed to due the
new sa_assert immediately following the for statement.
2010-04-14 21:24:21 -04:00
Jim Meyering
b6719eab9e nwfilter_ebiptables_driver.c: avoid NULL dereference
* src/nwfilter/nwfilter_ebiptables_driver.c (ebiptablesApplyNewRules):
Don't dereference a NULL or uninitialized pointer when given
an empty list of rules.  Add an sa_assert(inst) in each loop to
tell clang that the uses of "inst[i]" are valid.
2010-04-14 20:10:18 +02:00
Stefan Berger
274f09cbc5 nwfilter: use virFindFileInPath for needed CLI tools
I am getting rid of determining the path to necessary CLI tools at
compile time. Instead, now the firewall driver has an initialization
function that uses virFindFileInPath() to determine the path to
necessary CLI tools and a shutdown function to free allocated memory.
The rest of the patch mostly deals with availability of the CLI tools
and to not call certain code blocks if a tool is not available and that
strings now have to be built slightly differently.
2010-04-14 06:29:55 -04:00
Stefan Berger
5174b02fb9 Consolidate interface related functions in interface.c
Changes from v1 to v2:
- changed function name prefixes to 'iface' from previous 'Iface'

- Further to make make syntax-check pass:
 - indentation fix in interface.h
 - added entry to POTFILES.in

I am consolidating network interface related functions used in nwfilter
and macvtap code in utils/interface.c. All function names are prefixed
with 'Iface'. The following functions are now available through
interface.h:

int ifaceCtrl(const char *name, bool up);
int ifaceUp(const char *name);
int ifaceDown(const char *name);

int ifaceCheck(bool reportError, const char *ifname,
               const unsigned char *macaddr, int ifindex);

int ifaceGetIndex(bool reportError, const char *ifname, int *ifindex);

I added 'int ifindex' as parameter to ifaceCheck to the original
function and modified the code accordingly.
2010-04-13 10:57:11 -04:00
Stefan Berger
c5337e8e43 nwfilter: Fix memory leak on daemon init and shutdown
This patch fixes a memory leak on daemon init and shutdown. The module
was initialized twice and not shut down.
2010-04-12 08:19:11 -04:00
Stefan Berger
55d444cc10 nwfilter: Process DHCP option to determine whether packet is a DHCP_OFFER
I mistakenly took the op field in the DHCP message as the DHCP_OFFER
type. Rather than basing the decision to read the VM's IP address on
that field, process the appended DHCP options where option 53 indicates
the actual type of the packet. I am also reading the broadcast address
of the VM, but don't use it so far.
2010-04-09 15:54:29 -04:00
Stefan Berger
9fd54a78dc nwfilter: fix for directionality of ICMP traffic
Changes from V1 to V2 of this patch
- I had reversed the logic thinking that icmp type 0 is a echo
request,but it's reply -- needed to reverse the logic
- Found that ebtables takes the --ip-tos argument only as a hex number

This patch enables the skipping of some of the ICMP traffic rules on the
iptables level under certain circumstances so that the following filter
properly enables unidirectional pings:

<filter name='testcase'>
    <uuid>d6b1a2af-def6-2898-9f8d-4a74e3c39558</uuid>
    <!-- allow incoming ICMP Echo Request -->
    <rule action='accept' direction='in' priority='500'>
        <icmp type='8'/>
    </rule>
    <!-- allow outgoing ICMP Echo Reply -->
    <rule action='accept' direction='out' priority='500'>
        <icmp type='0'/>
    </rule>
    <!-- drop all other ICMP traffic -->
    <rule action='drop' direction='inout' priority='600'>
        <icmp/>
    </rule>
</filter>
2010-04-08 06:25:38 -04:00
Stefan Berger
3bf24abc8c nwfilter: Support for learning a VM's IP address
This patch implements support for learning a VM's IP address. It uses
the pcap library to listen on the VM's backend network interface (tap)
or the physical ethernet device (macvtap) and tries to capture packets
with source or destination MAC address of the VM and learn from DHCP
Offers, ARP traffic, or first-sent IPv4 packet what the IP address of
the VM's interface is. This then allows to instantiate the network
traffic filtering rules without the user having to provide the IP
parameter somewhere in the filter description or in the interface
description as a parameter. This only supports to detect the parameter
IP, which is for the assumed single IPv4 address of a VM. There is not
support for interfaces that may have multiple  IP addresses (IP
aliasing) or IPv6 that may then require more than one valid IP address
to be detected. A VM can have multiple independent interfaces that each
uses a different IP address and in that case it will be attempted to
detect each one of the address independently.

So, when for example an interface description in the domain XML has
looked like this up to now:

    <interface type='bridge'>
      <source bridge='mybridge'/>
      <model type='virtio'/>
      <filterref filter='clean-traffic'>
        <parameter name='IP' value='10.2.3.4'/>
      </filterref>
    </interface>

you may omit the IP parameter:

    <interface type='bridge'>
      <source bridge='mybridge'/>
      <model type='virtio'/>
      <filterref filter='clean-traffic'/>
    </interface>

Internally I am walking the 'tree' of a VM's referenced network filters
and determine with the given variables which variables are missing. Now,
the above IP parameter may be missing and this causes a libvirt-internal
thread to be started that uses the pcap library's API to listen to the
backend interface  (in case of macvtap to the physical interface) in an
attempt to determine the missing IP parameter. If the backend interface
disappears the thread terminates assuming the VM was brought down. In
case of a macvtap device a timeout is being used to wait for packets
from the given VM (filtering by VM's interface MAC address). If the VM's
macvtap device disappeared the thread also terminates. In all other
cases it tries to determine the IP address of the VM and will then apply
the rules late on the given interface, which would have happened
immediately if the IP parameter had been explicitly given. In case an
error happens while the firewall rules are applied, the VM's backend
interface is 'down'ed preventing it to communicate. Reasons for failure
for applying the network firewall rules may that an ebtables/iptables
command failes or OOM errors. Essentially the same failure reasons may
occur as when the firewall rules are applied immediately on VM start,
except that due to the late application of the filtering rules the VM
now is already running and cannot be hindered anymore from starting.
Bringing down the whole VM would probably be considered too drastic.
While a VM's IP address is attempted to be determined only limited
updates to network filters are allowed. In particular it is prevented
that filters are modified in such a way that they would introduce new
variables.

A caveat: The algorithm does not know which one is the appropriate IP
address of a VM. If the VM spoofs an IP address in its first ARP traffic
or IPv4 packets its filtering rules will be instantiated for this IP
address, thus 'locking' it to the found IP address. So, it's still
'safer' to explicitly provide the IP address of a VM's interface in the
filter description if it is known beforehand.

* configure.ac: detect libpcap
* libvirt.spec.in: require libpcap[-devel] if qemu is built
* src/internal.h: add the new ATTRIBUTE_PACKED define
* src/Makefile.am src/libvirt_private.syms: add the new modules and symbols
* src/nwfilter/nwfilter_learnipaddr.[ch]: new module being added
* src/nwfilter/nwfilter_driver.c src/conf/nwfilter_conf.[ch]
  src/nwfilter/nwfilter_ebiptables_driver.[ch]
  src/nwfilter/nwfilter_gentech_driver.[ch]: plu the new functionality in
* tests/nwfilterxml2xmltest: extend testing
2010-04-07 23:12:21 +02:00
Stefan Berger
f8352e221f nwfiler: fix due to non-symmetric src mac address match in iptables
The attached patch fixes a problem due to the mac match in iptables only
supporting --mac-source and no --mac-destination, thus it not being
symmetric. Therefore a rule like this one

<rule action='drop' direction='out'>
  <all match='no' srcmacaddr='$MAC'/>
</rule>

should only have the MAC match on traffic leaving the VM and not test
for the same source MAC address on traffic that the VM receives.
2010-04-07 06:28:16 -04:00
Stefan Berger
552bdb9b35 nwfilter: Fix instantiated layer 2 rules for 'inout' direction
With Eric Blake's suggestions applied.

The following rule for direction 'in'

<rule direction='in' action='drop'>
  <mac srcmacaddr='1:2:3:4:5:6'/>
</rule>

drops all traffic from the given mac address.
The following rule for direction 'out'

<rule direction='out' action='drop'>
  <mac dstmacaddr='1:2:3:4:5:6'/>
</rule>

drops all traffic to the given mac address.
The following rule in direction 'inout'

<rule direction='inout' action='drop'>
  <mac srcmacaddr='1:2:3:4:5:6'/>
</rule>

now drops all traffic from and to the given MAC address.
So far it would have dropped traffic from the given MAC address
and outgoing traffic with the given source MAC address, which is not useful
since the packets will always have the VM's MAC address as source
MAC address. The attached patch fixes this.

This is the last bug I currently know of and want to fix.
2010-04-06 10:40:35 -04:00
Matthias Bolte
49411f029a Remove unnecessary trailing \n in log messages 2010-04-06 01:41:58 +02:00
Stefan Berger
45274d4121 This patch removes the virConnectPtr parameter from all functions where it's not necessary starting out with removing it as a parameter to the error reporting function. 2010-04-05 12:34:55 -04:00
Laine Stump
5dac5970a5 Eliminate compiler warning about non-const format string 2010-04-04 22:58:33 -04:00
Stefan Berger
b3e8f9f415 The following issues are fixed in the patch below:
- ebtables requires that some of the command line parameters are passed as hex numbers; so have those attributes call a function that prints 16 and 8 bit integers as hex nunbers.

- ip6tables requires '--icmpv6-type' rather than '--icmp-type'

- ebtables complains about protocol identifiers lower than 0x600, so already discard anything lower than 0x600 in the parser

- make the protocol entry types more readable using a #define for its entries

- continue parsing a filtering rule even if a faulty entry is encountered; return an error value at the end and let the caller decide what to do with the rule's object

- fix an error message
2010-04-02 13:21:10 -04:00
Laine Stump
78151ec96e Eliminate compile warnings in nwfilter error log calls 2010-04-02 09:39:00 -04:00
Stefan Berger
e813200714 While writing a couple of test cases for the nwfilter's XML parser I
found some cases where the output ended up not looking as expected. So
the following changes are in the patch below:

- if the protocol ID in the MAC header is an integer, just write it into
the datastructure without trying to find a corresponding string for it
and if none is found failing
- when writing the protocol ID as string, simply write it as integer if
no corresponding string can be found
- same changes for arpOpcode parsing and printing
- same changes for protocol ID in an IP packet
- DSCP value needs to be written into the data structure
- IP protocol version number is redundant at this level, so remove it
- parse the protocol ID found inside an IP packet not only as string but
also as uint8
- arrange the display of the src and destination masks to be shown after
the src and destination ip address respectively in the XML
- the existing libvirt IP address parser accepts for example '25' as an
IP address. I want this to be parsed as a CIDR type netmask. So try to
parse it as an integer first (CIDR netmask) and if that doesn't work as
a dotted IP address style netmask.
- instantiation of rules with MAC masks didn't work because they weren't
printed into a buffer, yet.
2010-04-01 06:37:26 -04:00
Stefan Berger
0e0f6021ce Use libvirt's existing ipv6/ipv4 parser/printer rather than self-written ones
This patch changes the network filtering code to use libvirt's existing
IPv4 and IPv6 address parsers/printers rather than my self-written ones.

I am introducing a new function in network.c that counts the number of
bits in a netmask and ensures that the given address is indeed a netmask,
return -1 on error or values of 0-32 for IPv4 addresses and 0-128 for
IPv6 addresses. I then based the function checking for valid netmask
on invoking this function.
2010-03-30 11:18:04 -04:00
Stefan Berger
bc2102104f Add ip6tables support for IPv6 filtering
This patch adds IPv6 filtering support for the following protocols:
- tcp-ipv6
- udp-ipv6
- udplite-ipv6
- esp-ipv6
- ah-ipv6
- sctp-ipv6
- all-ipv6
- icmpv6

Many of the IPv4 data structure could be re-used for IPv6 support.
Since ip6tables also supports pretty much the same command line parameters
as iptables does, also much of the code could be re-used and now
command lines are invoked with the ip(6)tables tool parameter passed
through the functions as a parameter.
2010-03-30 10:36:35 -04:00
Stefan Berger
0af0ded038 Remove driver dependency from nwfilter_conf.c
This patch removes the driver dependency from nwfilter_conf.c and moves
a callback function calling into the driver into
nwfilter_gentech_driver.c and passes a pointer to that callback function
upon initialization of nwfilter_conf.c.
2010-03-30 10:25:22 -04:00
Stefan Berger
285d38931f Add support for so-far missing protocols for iptables filtering
This patch adds filtering support for the so-far missing protocols 'ah',
'esp' and 'udplite'.
2010-03-30 10:16:40 -04:00
Jim Meyering
19a863c435 filter new files through cppi, so syntax-check passes once again
* src/conf/nwfilter_conf.h: Indent cpp directives.
* src/conf/nwfilter_params.h: Likewise.
* src/datatypes.h: Likewise.
* src/nwfilter/nwfilter_driver.h: Likewise.
* src/nwfilter/nwfilter_ebiptables_driver.h: Likewise.
* src/nwfilter/nwfilter_gentech_driver.h: Likewise.
2010-03-26 22:47:30 +01:00
Stefan Berger
1130085cf0 Extensions for iptables rules
This patch adds support for L3/L4 filtering using iptables. This adds
support for 'tcp', 'udp', 'icmp', 'igmp', 'sctp' etc. filtering.

As mentioned in the introduction, a .c file provided by this patch
is #include'd into a .c file. This will need work, but should be alright
for review.

Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
2010-03-26 18:01:17 +00:00
Stefan Berger
f85208eec6 Add IPv6 support for the ebtables layer
This patch adds IPv6 support for the ebtables layer. Since the parser
etc. are all parameterized, it was fairly easy to add this...

Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
2010-03-26 18:01:17 +00:00
Stefan Berger
065b6571bf Core driver implementation with ebtables support
This patch implements the core driver and provides
- management functionality for managing the filter XMLs
- compiling the internal filter representation into ebtables rules
- applying ebtables rules on a network (tap,macvtap) interface
- tearing down ebtables rules that were applied on behalf of an
interface
- updating of filters while VMs are running and causing the firewalls to
be rebuilt
- other bits and pieces

Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
2010-03-26 18:01:16 +00:00