Index: fedd/fedd.py
===================================================================
--- fedd/fedd.py	(revision 7a8d667972e8db4da477c0270c54dab48255d853)
+++ fedd/fedd.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -15,5 +15,6 @@
 
 from fedd_util import fedd_ssl_context, fedid
-from fedd_proj import new_feddservice
+from fedd_deter_impl import new_feddservice
+from service_error import *
 
 # The SSL server here is based on the implementation described at
@@ -27,8 +28,9 @@
 	SSLServer.__init__(self, ME, handler, ssl_ctx)
 	self.impl = impl
+	self.soap_methods = impl.get_soap_services()
+	self.xmlrpc_methods = impl.get_xmlrpc_services()
 
 class fedd_soap_handler(BaseHTTPRequestHandler):
     server_version = "ZSI/2.0 fedd/0.1 " + BaseHTTPRequestHandler.server_version
-
 
     def send_xml(self, text, code=200):
@@ -80,5 +82,5 @@
 	if not self.check_method(ps): return
 	try:
-	    resp = self.server.impl.soap_dispatch(ps.body_root.localName, ps,
+	    resp = self.soap_dispatch(ps.body_root.localName, ps,
 		    fedid(cert=self.request.get_peer_cert()))
 	except Fault, f:
@@ -91,4 +93,23 @@
 	    self.send_xml(str(sw))
 
+    def soap_dispatch(self, method, req, fid):
+	if self.server.soap_methods.has_key(method):
+	    try:
+		return self.server.soap_methods[method](req, fid)
+	    except service_error, e:
+		de = ns0.faultType_Def(
+			(ns0.faultType_Def.schema,
+			    "FeddFaultBody")).pyclass()
+		de._code=e.code
+		de._errstr=e.code_string()
+		de._desc=e.desc
+		if  e.is_server_error():
+		    raise Fault(Fault.Server, e.code_string(), detail=de)
+		else:
+		    raise Fault(Fault.Client, e.code_string(), detail=de)
+	else:
+	    raise Fault(Fault.Client, "Unknown method: %s" % method)
+
+
 class fedd_xmlrpc_handler(BaseHTTPRequestHandler):
     server_version = "ZSI/2.0 fedd/0.1 " + BaseHTTPRequestHandler.server_version
@@ -120,5 +141,5 @@
 	if method != None:
 	    try:
-		resp = self.server.impl.xmlrpc_dispatch(method, params,
+		resp = self.xmlrpc_dispatch(method, params,
 			    fedid(cert=self.request.get_peer_cert()))
 		data = xmlrpclib.dumps((resp,), encoding='UTF-8', 
@@ -129,4 +150,13 @@
 	self.send_xml(data)
 
+
+    def xmlrpc_dispatch(self, method, req, fid):
+	if self.server.xmlrpc_methods.has_key(method):
+	    try:
+		return self.server.xmlrpc_methods[method](req, fid)
+	    except service_error, e:
+		raise xmlrpclib.Fault(e.code_string(), e.desc)
+	else:
+	    raise xmlrpclib.Fault(100, "Unknown method: %s" % method)
 
 class fedd_opts(OptionParser):
Index: fedd/fedd_access.py
===================================================================
--- fedd/fedd_access.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
+++ fedd/fedd_access.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -0,0 +1,488 @@
+#!/usr/local/bin/python
+
+import os,sys
+
+from BaseHTTPServer import BaseHTTPRequestHandler
+from ZSI import *
+from M2Crypto import SSL
+from M2Crypto.m2xmlrpclib import SSL_Transport
+from M2Crypto.SSL.SSLServer import SSLServer
+import M2Crypto.httpslib
+import xmlrpclib
+
+import re
+import string
+import copy
+
+from fedd_config_file import config_file
+from fedd_access_project import access_project
+from fedd_services import *
+from fedd_util import *
+from fedd_allocate_project import *
+import parse_detail
+from service_error import *
+
+class fedd_access:
+    """
+    The implementation of access control based on mapping users to projects.
+
+    Users can be mapped to existing projects or have projects created
+    dynamically.  This implements both direct requests and proxies.
+    """
+
+    def __init__(self, config=None):
+	"""
+	Initializer.  Parses a configuration if one is given.
+	"""
+
+	# Read the configuration
+	if not config: raise RunTimeError("No config to fedd_allocate")
+
+	# Create instance attributes from the static lists
+	for a in config_file.bool_attrs:
+	    setattr(self, a, getattr(config, a, False))
+
+	for a in config_file.emulab_attrs + config_file.id_attrs:
+	    setattr(self, a, getattr(config, a, None))
+
+
+	self.attrs = copy.deepcopy(config.attrs);
+	self.access = copy.deepcopy(config.access);
+	self.fedid_category = copy.deepcopy(config.fedid_category)
+	self.fedid_default = config.fedid_default
+	self.restricted = copy.copy(config.restricted)
+
+	# Certs are promoted from the generic to the specific, so without a
+	# specific proxy certificate, the main certificates are used for
+	# proxy interactions. If no dynamic project certificates, then
+	# proxy certs are used, and if none of those the main certs.
+
+	if config.proxy_cert_file:
+	    if not self.dynamic_projects_cert_file:
+		self.dynamic_projects_cert_file = config.proxy_cert_file
+		self.dynamic_projects_cert_pwd = config.proxy_cert_pwd
+
+	if config.proxy_trusted_certs:
+	    if not self.dynamic_projects_trusted_certs:
+		self.dynamic_projects_trusted_certs =\
+			config.proxy_trusted_certs
+
+	if config.cert_file:
+	    if not self.dynamic_projects_cert_file:
+		self.dynamic_projects_cert_file = config.cert_file
+		self.dynamic_projects_cert_pwd = config.cert_pwd
+	    if not self.proxy_cert_file:
+		self.proxy_cert_file = config.cert_file
+		self.proxy_cert_pwd = config.cert_pwd
+
+	if config.trusted_certs:
+	    if not self.proxy_trusted_certs:
+		self.proxy_trusted_certs = config.trusted_certs
+	    if not self.dynamic_projects_trusted_certs:
+		self.dynamic_projects_trusted_certs = config.trusted_certs
+
+	proj_certs = (self.dynamic_projects_cert_file, 
+		self.dynamic_projects_trusted_certs,
+		self.dynamic_projects_cert_pwd)
+
+
+	if config.dynamic_projects_url == None:
+	    self.allocate_project = \
+		fedd_allocate_project_local(config.dynamic_projects, 
+			config.dynamic_projects_url, proj_certs)
+	else:
+	    self.allocate_project = \
+		fedd_allocate_project_remote(config.dynamic_projects, 
+			config.dynamic_projects_url, proj_certs)
+
+	self.soap_handlers = {\
+	    'RequestAccess': make_soap_handler(\
+		RequestAccessRequestMessage.typecode,\
+		self.RequestAccess, RequestAccessResponseMessage,\
+		"RequestAccessResponseBody")\
+	    }
+	self.xmlrpc_handlers =  {\
+	    'RequestAccess': make_xmlrpc_handler(\
+		self.RequestAccess, "RequestAccessResponseBody")\
+	    }
+
+    def dump_state(self):
+	"""
+	Dump the state read from a configuration file.  Mostly for debugging.
+	"""
+	for a in fedd_proj.bool_attrs:
+	    print "%s: %s" % (a, getattr(self, a ))
+	for a in fedd_proj.emulab_attrs + fedd_proj.id_attrs:
+	    print "%s: %s" % (a, getattr(self, a))
+	for k, v in self.attrs.iteritems():
+	    print "%s %s" % (k, v)
+	print "Access DB:"
+	for k, v in self.access.iteritems():
+	    print "%s %s" % (k, v)
+	print "Trust DB:"
+	for k, v in self.fedid_category.iteritems():
+	    print "%s %s" % (k, v)
+	print "Restricted: %s" % str(',').join(sorted(self.restricted))
+
+    def get_users(self, obj):
+	"""
+	Return a list of the IDs of the users in dict
+	"""
+	if obj.has_key('user'):
+	    return [ unpack_id(u['userID']) \
+		    for u in obj['user'] if u.has_key('userID') ]
+	else:
+	    return None
+
+    def strip_unicode(self, obj):
+	"""Loosly de-unicode an object"""
+	if isinstance(obj, dict):
+	    for k in obj.keys():
+		obj[k] = self.strip_unicode(obj[k])
+	    return obj
+	elif isinstance(obj, basestring):
+	    return str(obj)
+	elif getattr(obj, "__iter__", None):
+	    return [ self.strip_unicode(x) for x in obj]
+	else:
+	    return obj
+
+    def proxy_xmlrpc_request(self, dt, req):
+	"""Send an XMLRPC proxy request.  Called if the SOAP RPC fails"""
+
+	# No retry loop here.  Proxy servers must correctly authenticate
+	# themselves without help
+	try:
+	    ctx = fedd_ssl_context(self.proxy_cert_file, 
+		    self.proxy_trusted_certs, password=self.proxy_cert_pwd)
+	except SSL.SSLError:
+	    raise service_error(service_error.server_config,
+		    "Server certificates misconfigured")
+
+	# Of all the dumbass things.  The XMLRPC library in use here won't
+	# properly encode unicode strings, so we make a copy of req with the
+	# unicode objects converted.  We also convert the destination testbed
+	# to a basic string if it isn't one already.
+	if isinstance(dt, str): url = dt
+	else: url = str(dt)
+
+	r = copy.deepcopy(req)
+	self.strip_unicode(r)
+	
+	transport = SSL_Transport(ctx)
+	port = xmlrpclib.ServerProxy(url, transport=transport)
+
+	# Reconstruct the full request message
+	try:
+	    resp = port.RequestAccess(
+		    { "RequestAccessRequestBody": r})
+	    resp, method = xmlrpclib.loads(resp)
+	except xmlrpclib.Fault, f:
+	    se = service_error(None, f.faultString, f.faultCode)
+	    raise se
+	except xmlrpclib.Error, e:
+	    raise service_error(service_error.proxy, 
+		    "Remote XMLRPC Fault: %s" % e)
+	
+	if resp[0].has_key('RequestAccessResponseBody'):
+	    return resp[0]['RequestAccessResponseBody']
+	else:
+	    raise service_error(service_error.proxy, 
+		    "Bad proxy response")
+
+    def proxy_request(self, dt, req):
+	"""
+	Send req on to the real destination in dt and return the response
+
+	Req is just the requestType object.  This function re-wraps it.  It
+	also rethrows any faults.
+	"""
+	# No retry loop here.  Proxy servers must correctly authenticate
+	# themselves without help
+	try:
+	    ctx = fedd_ssl_context(self.proxy_cert_file, 
+		    self.proxy_trusted_certs, password=self.proxy_cert_pwd)
+	except SSL.SSLError:
+	    raise service_error(service_error.server_config, 
+		    "Server certificates misconfigured")
+
+	loc = feddServiceLocator();
+	port = loc.getfeddPortType(dt,
+		transport=M2Crypto.httpslib.HTTPSConnection, 
+		transdict={ 'ssl_context' : ctx })
+
+	# Reconstruct the full request message
+	msg = RequestAccessRequestMessage()
+	msg.set_element_RequestAccessRequestBody(
+		pack_soap(msg, "RequestAccessRequestBody", req))
+	try:
+	    resp = port.RequestAccess(msg)
+	except ZSI.ParseException, e:
+	    raise service_error(service_error.proxy,
+		    "Bad format message (XMLRPC??): %s" %
+		    str(e))
+	r = unpack_soap(resp)
+
+	if r.has_key('RequestAccessResponseBody'):
+	    return r['RequestAccessResponseBody']
+	else:
+	    raise service_error(service_error.proxy,
+		    "Bad proxy response")
+
+    def permute_wildcards(self, a, p):
+	"""Return a copy of a with various fields wildcarded.
+
+	The bits of p control the wildcards.  A set bit is a wildcard
+	replacement with the lowest bit being user then project then testbed.
+	"""
+	if p & 1: user = ["<any>"]
+	else: user = a[2]
+	if p & 2: proj = "<any>"
+	else: proj = a[1]
+	if p & 4: tb = "<any>"
+	else: tb = a[0]
+
+	return (tb, proj, user)
+
+    def find_access(self, search):
+	"""
+	Search the access DB for a match on this tuple.  Return the matching
+	access tuple and the user that matched.
+	
+	NB, if the initial tuple fails to match we start inserting wildcards in
+	an order determined by self.project_priority.  Try the list of users in
+	order (when wildcarded, there's only one user in the list).
+	"""
+	if self.project_priority: perm = (0, 1, 2, 3, 4, 5, 6, 7)
+	else: perm = (0, 2, 1, 3, 4, 6, 5, 7)
+
+	for p in perm: 
+	    s = self.permute_wildcards(search, p)
+	    # s[2] is None on an anonymous, unwildcarded request
+	    if s[2] != None:
+		for u in s[2]:
+		    if self.access.has_key((s[0], s[1], u)):
+			return (self.access[(s[0], s[1], u)], u)
+	    else:
+		if self.access.has_key(s):
+		    return (self.access[s], None)
+	return None, None
+
+    def lookup_access(self, req, fid):
+	"""
+	Determine the allowed access for this request.  Return the access and
+	which fields are dynamic.
+
+	The fedid is needed to construct the request
+	"""
+	# Search keys
+	tb = None
+	project = None
+	user = None
+	# Return values
+	rp = access_project(None, ())
+	ru = None
+
+
+	principal_type = self.fedid_category.get(fid, self.fedid_default)
+
+	if principal_type == "testbed": tb = fid
+
+	if req.has_key('project'):
+	    p = req['project']
+	    if p.has_key('name'):
+		project = unpack_id(p['name'])
+	    user = self.get_users(p)
+	else:
+	    user = self.get_users(req)
+
+	# Now filter by prinicpal type
+	if principal_type == "user":
+	    if user != None:
+		fedids = [ u for u in user if isinstance(u, type(fid))]
+		if len(fedids) > 1:
+		    raise service_error(service_error.req,
+			    "User asserting multiple fedids")
+		elif len(fedids) == 1 and fedids[0] != fid:
+		    raise service_error(service_error.req,
+			    "User asserting different fedid")
+	    project = None
+	    tb = None
+	elif principal_type == "project":
+	    if isinstance(project, type(fid)) and fid != project:
+		raise service_error(service_error.req,
+			"Project asserting different fedid")
+	    tb = None
+
+	# Ready to look up access
+	found, user_match = self.find_access((tb, project, user))
+	
+	if found == None:
+	    raise service_error(service_error.access,
+		    "Access denied")
+
+	# resolve <dynamic> and <same> in found
+	dyn_proj = False
+	dyn_user = False
+
+	if found[0].name == "<same>":
+	    if project != None:
+		rp.name = project
+	    else : 
+		raise service_error(\
+			service_error.server_config,
+			"Project matched <same> when no project given")
+	elif found[0].name == "<dynamic>":
+	    rp.name = None
+	    dyn_proj = True
+	else:
+	    rp.name = found[0].name
+	rp.node_types = found[0].node_types;
+
+	if found[1] == "<same>":
+	    if user_match == "<any>":
+		if user != None: ru = user[0]
+		else: raise service_error(\
+			service_error.server_config,
+			"Matched <same> on anonymous request")
+	    else:
+		ru = user_match
+	elif found[1] == "<dynamic>":
+	    ru = None
+	    dyn_user = True
+	
+	return (rp, ru), (dyn_user, dyn_proj)
+
+    def build_response(self, alloc_id, ap):
+	"""
+	Create the SOAP response.
+
+	Build the dictionary description of the response and use
+	fedd_utils.pack_soap to create the soap message.  NB that alloc_id is
+	a fedd_services_types.IDType_Holder pulled from the incoming message.
+	ap is the allocate project message returned from a remote project
+	allocation (even if that allocation was done locally).
+	"""
+	# Because alloc_id is already a fedd_services_types.IDType_Holder,
+	# there's no need to repack it
+	msg = { 
+		'allocID': alloc_id,
+		'emulab': { 
+		    'domain': self.domain,
+		    'boss': self.boss,
+		    'ops': self.ops,
+		    'fileServer': self.fileserver,
+		    'eventServer': self.eventserver,
+		    'project': ap['project']
+		},
+	    }
+	if len(self.attrs) > 0:
+	    msg['emulab']['fedAttr'] = \
+		[ { 'attribute': x, 'value' : y } \
+			for x,y in self.attrs.iteritems()]
+	return msg
+
+    def RequestAccess(self, req, fid):
+
+	print "in get access"
+	if req.has_key('RequestAccessRequestBody'):
+	    req = req['RequestAccessRequestBody']
+	else:
+	    raise service_error(service_error.req, "No request!?")
+
+	if req.has_key('destinationTestbed'):
+	    dt = unpack_id(req['destinationTestbed'])
+
+	print dt, " ", self.testbed
+
+	if dt == None or dt == self.testbed:
+	    # Request for this fedd
+	    found, dyn = self.lookup_access(req, fid)
+	    restricted = None
+	    ap = None
+
+	    # Check for access to restricted nodes
+	    if req.has_key('resources') and req['resources'].has_key('node'):
+		resources = req['resources']
+		restricted = [ t for n in resources['node'] \
+				if n.has_key('hardware') \
+				    for t in n['hardware'] \
+					if t in self.restricted ]
+		inaccessible = [ t for t in restricted \
+				    if t not in found[0].node_types]
+		if len(inaccessible) > 0:
+		    raise service_error(service_error.access,
+			    "Access denied (nodetypes %s)" % \
+			    str(', ').join(inaccessible))
+
+	    ssh = [ x['sshPubkey'] \
+		    for x in req['access'] if x.has_key('sshPubkey')]
+
+	    if len(ssh) > 0: 
+		if dyn[1]: 
+		    # Compose the dynamic project request 
+		    # (only dynamic, dynamic currently allowed)
+		    preq = { 'AllocateProjectRequestBody': \
+				{ 'project' : {\
+				    'user': [ \
+				    { 'access': [ { 'sshPubkey': s } ] } \
+					for s in ssh ] \
+				    }\
+				}\
+			    }
+		    if restricted != None and len(restricted) > 0:
+			preq['AllocateProjectRequestBody']['resources'] = \
+			    [ {'node': { 'hardware' :  [ h ] } } \
+				    for h in restricted ]
+				
+		    ap = self.allocate_project.dynamic_project(preq)
+		else:
+		    # XXX ssh key additions
+		    ap = { 'project': \
+			    { 'name' : { 'localname' : found[0].name },\
+			      'user' : [ {\
+				'userID': { 'localname' : found[1] }, \
+				'access': [ { 'sshPubkey': s } for s in ssh]}\
+				]\
+			    }\
+		    }
+	    else:
+		raise service_error(service_error.req, 
+			"SSH access parameters required")
+
+	    resp = self.build_response(req['allocID'], ap)
+	    return resp
+	else:
+	    p_fault = None	# Any SOAP failure (sent unless XMLRPC works)
+	    try:
+		# Proxy the request using SOAP
+		return self.proxy_request(dt, req)
+	    except service_error, e:
+		if e.code == service_error.proxy: p_fault = None
+		else: raise
+	    except ZSI.FaultException, f:
+		p_fault = f.fault.detail[0]
+		    
+
+	    # If we could not get a valid SOAP response to the request above,
+	    # try the same address using XMLRPC and let any faults flow back
+	    # out.
+	    if p_fault == None:
+		return self.proxy_xmlrpc_request(dt, req)
+	    else:
+		# Build the fault
+		body = p_fault.get_element_FeddFaultBody()
+		if body != None:
+		    raise service_error(body.get_element_code(),
+				body.get_element_desc());
+		else:
+		    raise service_error(\
+			    service_error.proxy,
+			    "Undefined fault from proxy??");
+    
+    def get_soap_services(self):
+	return self.soap_handlers
+
+    def get_xmlrpc_services(self):
+	return self.xmlrpc_handlers
+
Index: fedd/fedd_access_project.py
===================================================================
--- fedd/fedd_access_project.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
+++ fedd/fedd_access_project.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -0,0 +1,20 @@
+#!/usr/local/bin/python
+
+class access_project:
+    """
+    A project description used to grant access to this testbed.
+
+    The description includes a name and a list of node types to which the
+    project will be granted access.
+    """
+    def __init__(self, name, nt):
+	self.name = name
+	self.node_types = list(nt)
+
+    def __repr__(self):
+	if len(self.node_types) > 0:
+	    return "access_proj('%s', ['%s'])" % \
+		    (self.name, str("','").join(self.node_types))
+	else:
+	    return "access_proj('%s', [])" % self.name
+
Index: fedd/fedd_allocate_project.py
===================================================================
--- fedd/fedd_allocate_project.py	(revision 7a8d667972e8db4da477c0270c54dab48255d853)
+++ fedd/fedd_allocate_project.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -16,5 +16,4 @@
 import subprocess
 import tempfile
-import copy
 
 from fedd_services import *
Index: fedd/fedd_config_file.py
===================================================================
--- fedd/fedd_config_file.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
+++ fedd/fedd_config_file.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -0,0 +1,227 @@
+#!/usr/local/bin/python
+
+import os,sys
+
+import re
+import string
+
+from fedd_util import *
+from fedd_access_project import access_project
+
+# Used to report errors parsing the configuration files, not in providing
+# service
+class parse_error(RuntimeError): pass
+
+class config_file:
+    """
+    The implementation of access control based on mapping users to projects.
+
+    Users can be mapped to existing projects or have projects created
+    dynamically.  This implements both direct requests and proxies.
+    """
+    # Attributes that can be parsed from the configuration file
+    bool_attrs = ("dynamic_projects", "project_priority", "create_debug")
+    emulab_attrs = ("boss", "ops", "domain", "fileserver", "eventserver")
+    id_attrs = ("testbed", "cert_file", "cert_pwd", "trusted_certs", "proxy",
+	    "proxy_cert_file", "proxy_cert_pwd", "proxy_trusted_certs",
+	    "dynamic_projects_url", "dynamic_projects_cert_file", 
+	    "dynamic_projects_cert_pwd", "dynamic_projects_trusted_certs",
+	    "create_experiment_cert_file", "create_experiment_cert_pwd",
+	    "create_experiment_trusted_certs", "federation_script_dir",
+	    "ssh_pubkey_file")
+
+
+    def __init__(self, config=None):
+	"""
+	Initializer.  Parses a configuration if one is given.
+	"""
+
+	# Create instance attributes from the static lists
+	for a in config_file.bool_attrs:
+	    setattr(self, a, False)
+
+	for a in config_file.emulab_attrs + config_file.id_attrs:
+	    setattr(self, a, None)
+
+	self.attrs = { }
+	self.fedid_category = { }
+	self.fedid_default = "user"
+	self.access = { }
+	self.restricted = []
+
+	if config:
+	    self.read_config(config)
+
+    def read_trust(self, trust):
+	"""
+	Read a trust file that splits fedids into testbeds, users or projects
+
+	Format is:
+
+	[type]
+	fedid
+	fedid
+	default: type
+	"""
+	lineno = 0;
+	cat = None
+	cat_re = re.compile("\[(user|testbed|project)\]$", re.IGNORECASE)
+	fedid_re = re.compile("[" + string.hexdigits + "]+$")
+	default_re = re.compile("default:\s*(user|testbed|project)$", 
+		re.IGNORECASE)
+
+	f = open(trust, "r")
+	for line in f:
+	    lineno += 1
+	    line = line.strip()
+	    if len(line) == 0 or line.startswith("#"):
+		continue
+	    # Category line
+	    m = cat_re.match(line)
+	    if m != None:
+		cat = m.group(1).lower()
+		continue
+	    # Fedid line
+	    m = fedid_re.match(line)
+	    if m != None:
+		if cat != None:
+		    self.fedid_category[fedid(hexstr=m.string)] = cat
+		else:
+		    raise parse_error(\
+			    "Bad fedid in trust file (%s) line: %d" % \
+			    (trust, lineno))
+		continue
+	    # default line
+	    m = default_re.match(line)
+	    if m != None:
+		self.fedid_default = m.group(1).lower()
+		continue
+	    # Nothing matched - bad line, raise exception
+	    f.close()
+	    raise parse_error(\
+		    "Unparsable line in trustfile %s line %d" % (trust, lineno))
+	f.close()
+
+    def read_config(self, config):
+	"""
+	Read a configuration file and set internal parameters.
+
+	The format is more complex than one might hope.  The basic format is
+	attribute value pairs separated by colons(:) on a signle line.  The
+	attributes in bool_attrs, emulab_attrs and id_attrs can all be set
+	directly using the name: value syntax.  E.g. 
+	boss: hostname
+	sets self.boss to hostname.  In addition, there are access lines of the
+	form (tb, proj, user) -> (aproj, auser) that map the first tuple of
+	names to the second for access purposes.  Names in the key (left side)
+	can include "<NONE> or <ANY>" to act as wildcards or to require the
+	fields to be empty.  Similarly aproj or auser can be <SAME> or
+	<DYNAMIC> indicating that either the matching key is to be used or a
+	dynamic user or project will be created.  These names can also be
+	federated IDs (fedid's) if prefixed with fedid:.  Finally, the aproj
+	can be followed with a colon-separated list of node types to which that
+	project has access (or will have access if dynamic).
+	Testbed attributes outside the forms above can be given using the
+	format attribute: name value: value.  The name is a single word and the
+	value continues to the end of the line.  Empty lines and lines startin
+	with a # are ignored.
+
+	Parsing errors result in a parse_error exception being raised.
+	"""
+	lineno=0
+	name_expr = "["+string.ascii_letters + string.digits + "\.\-_]+"
+	fedid_expr = "fedid:[" + string.hexdigits + "]+"
+	key_name = "(<ANY>|<NONE>|"+fedid_expr + "|"+ name_expr + ")"
+	access_proj = "(<DYNAMIC>(?::" + name_expr +")*|"+ \
+		"<SAME>" + "(?::" + name_expr + ")*|" + \
+		fedid_expr + "(?::" + name_expr + ")*|" + \
+		name_expr + "(?::" + name_expr + ")*)"
+	access_name = "(<DYNAMIC>|<SAME>|" + fedid_expr + "|"+ name_expr + ")"
+
+	bool_re = re.compile('(' + '|'.join(config_file.bool_attrs) + 
+		'):\s+(true|false)', re.IGNORECASE)
+	string_re = re.compile( "(" + \
+		'|'.join(config_file.emulab_attrs + config_file.id_attrs) + \
+		'):\s*(.*)', re.IGNORECASE)
+	attr_re = re.compile('attribute:\s*([\._\-a-z0-9]+)\s+value:\s*(.*)',
+		re.IGNORECASE)
+	access_re = re.compile('\('+key_name+'\s*,\s*'+key_name+'\s*,\s*'+
+		key_name+'\s*\)\s*->\s*\('+access_proj + '\s*,\s*' + 
+		access_name + '\s*\)', re.IGNORECASE)
+	trustfile_re = re.compile("trustfile:\s*(.*)", re.IGNORECASE)
+	restricted_re = re.compile("restricted:\s*(.*)", re.IGNORECASE)
+
+	def parse_name(n):
+	    if n.startswith('fedid:'): return fedid(n[len('fedid:'):])
+	    else: return n
+
+	f = open(config, "r");
+	for line in f:
+	    lineno += 1
+	    line = line.strip();
+	    if len(line) == 0 or line.startswith('#'):
+		continue
+
+	    # Boolean attribute line
+	    m = bool_re.match(line);
+	    if m != None:
+		attr, val = m.group(1,2)
+		setattr(self, attr.lower(), bool(val.lower() == "true"))
+		continue
+
+	    # String attribute line
+	    m = string_re.match(line)
+	    if m != None:
+		attr, val = m.group(1,2)
+		setattr(self, attr.lower(), val)
+		continue
+
+	    # Extended (attribute: x value: y) attribute line
+	    m = attr_re.match(line)
+	    if m != None:
+		attr, val = m.group(1,2)
+		self.attrs[attr] = val
+		continue
+
+	    # Access line (t, p, u) -> (ap, au) line
+	    m = access_re.match(line)
+	    if m != None:
+		access_key = tuple([ parse_name(x) for x in m.group(1,2,3)])
+		aps = m.group(4).split(":");
+		if aps[0] == 'fedid:':
+		    del aps[0]
+		    aps[0] = fedid(hexstr=aps[0])
+
+		au = m.group(5)
+		if au.startswith("fedid:"):
+		    au = fedid(hexstr=aus[len("fedid:"):])
+
+		access_val = (access_project(aps[0], aps[1:]), au)
+
+		self.access[access_key] = access_val
+		continue
+
+	    # Trustfile inclusion
+	    m = trustfile_re.match(line)
+	    if m != None:
+		self.read_trust(m.group(1))
+		continue
+	    # Restricted node types
+
+	    m = restricted_re.match(line)
+	    if m != None:
+		self.restricted.append(m.group(1))
+		continue
+
+	    # Nothing matched to here: unknown line - raise exception
+	    f.close()
+	    raise parse_error("Unknown statement at line %d of %s" % \
+		    (lineno, config))
+	f.close()
+
+if __name__ == '__main__':
+    if sys.argv[1]:
+	config = config_file(sys.argv[1])
+	for a in [ a for a in dir(config) if a[0] != '_'  \
+		and not callable(getattr(config,a))]:
+	    print "%s: %s" % (a, getattr(config, a))
Index: fedd/fedd_create_experiment.py
===================================================================
--- fedd/fedd_create_experiment.py	(revision 7a8d667972e8db4da477c0270c54dab48255d853)
+++ 	(revision )
@@ -1,1524 +1,0 @@
-#!/usr/local/bin/python
-
-import os,sys
-
-from ZSI import *
-from M2Crypto import SSL
-from M2Crypto.SSL.SSLServer import SSLServer
-import M2Crypto.httpslib
-
-import xml.parsers.expat
-
-import re
-import random
-import string
-import subprocess
-import tempfile
-import copy
-
-import traceback
-
-from threading import *
-
-from subprocess import *
-
-from fedd_services import *
-from fedd_internal_services import *
-from fedd_util import *
-import parse_detail
-from service_error import *
-
-class fedd_create_experiment_local:
-    scripts = ["fed_bootstrap", "federate.sh", "smbmount.FreeBSD.pl",
-	"smbmount.Linux.pl", "make_hosts", "fed-tun.pl", "fed-tun.ucb.pl",
-	"fed_evrepeater", "rc.accounts.patch"]
-    
-    def __init__(self, 
-	    cert_file=None,
-	    cert_pwd=None,
-	    exp_stem="fed-stem",
-	    debug=False,
-	    muxmax=2,
-	    nthreads=2,
-	    randomize_experiments=False,
-	    scp_exec="/usr/bin/scp",
-	    scripts_dir="./", 
-	    splitter=None,
-	    ssh_exec="/usr/bin/ssh",
-	    ssh_identity_file=None,
-	    ssh_keygen="/usr/bin/ssh-keygen",
-	    ssh_pubkey_file=None,
-	    ssh_type="rsa",
-	    tbmap=None,
-	    tclsh="/usr/local/bin/otclsh",
-	    tcl_splitter="/usr/testbed/lib/ns2ir/parse.tcl",
-	    trace_file=None,
-	    trusted_certs=None,
-	    ):
-	self.scripts = fedd_create_experiment_local.scripts
-	self.thread_with_rv = fedd_create_experiment_local.pooled_thread
-	self.thread_pool = fedd_create_experiment_local.thread_pool
-
-	self.cert_file = cert_file
-	self.cert_pwd = cert_pwd
-	self.exp_stem = exp_stem
-	self.debug = debug
-	self.muxmax = muxmax
-	self.nthreads = nthreads
-	self.randomize_experiments = randomize_experiments
-	self.scp_exec = scp_exec
-	self.scripts_dir = scripts_dir
-	self.splitter = splitter
-	self.ssh_exec=ssh_exec
-	self.ssh_keygen = ssh_keygen
-	self.ssh_identity_file = ssh_identity_file
-	self.ssh_type = ssh_type
-	self.state = { }
-	self.tclsh = tclsh
-	self.tcl_splitter = tcl_splitter
-	self.tbmap = tbmap
-	self.trace_file = trace_file
-	self.trusted_certs=trusted_certs
-
-	self.def_expstart = \
-		"sudo -H /bin/sh FEDDIR/fed_bootstrap >& /tmp/federate";
-	self.def_mexpstart = "sudo -H FEDDIR/make_hosts FEDDIR/hosts";
-	self.def_gwstart = \
-		"sudo -H FEDDIR/fed-tun.pl -f GWCONF>& /tmp/bridge.log";
-	self.def_mgwstart = \
-		"sudo -H FEDDIR/fed-tun.pl -f GWCONF >& /tmp/bridge.log";
-	self.def_gwimage = "FBSD61-TUNNEL2";
-	self.def_gwtype = "pc";
-
-
-	if ssh_pubkey_file:
-	    try:
-		f = open(ssh_pubkey_file, 'r')
-		self.ssh_pubkey = f.read()
-		f.close()
-	    except IOError:
-		raise service_error(service_error.internal,
-			"Cannot read sshpubkey")
-
-	# Confirm federation scripts in the right place
-	for s in self.scripts:
-	    if not os.path.exists(self.scripts_dir + "/" + s):
-		raise service_error(service_error.server_config,
-			"%s/%s not in local script dir" % (self.scripts_dir, s))
-    class thread_pool:
-	def __init__(self):
-	    self.changed = Condition()
-	    self.started = 0
-	    self.terminated = 0
-
-	def acquire(self):
-	    self.changed.acquire()
-
-	def release(self):
-	    self.changed.release()
-
-	def wait(self, timeout = None):
-	    self.changed.wait(timeout)
-
-	def start(self):
-	    self.changed.acquire()
-	    self.started += 1
-	    self.changed.notifyAll()
-	    self.changed.release()
-
-	def terminate(self):
-	    self.changed.acquire()
-	    self.terminated += 1
-	    self.changed.notifyAll()
-	    self.changed.release()
-
-	def clear(self):
-	    self.changed.acquire()
-	    self.started = 0
-	    self.terminated =0
-	    self.changed.notifyAll()
-	    self.changed.release()
-
-
-
-    class pooled_thread(Thread):
-	def __init__(self, group=None, target=None, name=None, args=(), 
-		kwargs={}, pdata=None, trace_file=None):
-	    Thread.__init__(self, group, target, name, args, kwargs)
-	    self.rv = None
-	    self.exception = None
-	    self.target=target
-	    self.args = args
-	    self.kwargs = kwargs
-	    self.pdata = pdata
-	    self.trace_file = trace_file
-	
-	def run(self):
-	    if self.pdata:
-		self.pdata.start()
-
-	    if self.target:
-		try:
-		    self.rv = self.target(*self.args, **self.kwargs)
-		except service_error, s:
-		    self.exception = s
-		    if self.trace_file:
-			print >>self.trace_file, "Thread exception: %s %s" % \
-				(s.code_string(), s.desc)
-		    
-		except:
-		    self.exception = sys.exc_info()[1]
-		    if self.trace_file:
-			print >>self.trace_file, \
-				"Unexpected thread exception: %s" % \
-				self.exception
-			print >>self.trace_file, "Trace: %s" % \
-				traceback.format_exc()
-	    if self.pdata:
-		self.pdata.terminate()
-
-    def copy_file(self, src, dest, size=1024):
-	"""
-	Exceedingly simple file copy.
-	"""
-	s = open(src,'r')
-	d = open(dest, 'w')
-
-	buf = "x"
-	while buf != "":
-	    buf = s.read(size)
-	    d.write(buf)
-	s.close()
-	d.close()
-
-    def scp_file(self, file, user, host, dest=""):
-	"""
-	scp a file to the remote host.
-	"""
-
-	scp_cmd = [self.scp_exec, file, "%s@%s:%s" % (user, host, dest)]
-
-	trace = self.trace_file
-	if not trace:
-	    try:
-		trace = open("/dev/null", "w")
-	    except IOError:
-		raise service_error(service_error.internal,
-			"Cannot open /dev/null??");
-
-	if not self.debug:
-	    rv = call(scp_cmd, stdout=trace, stderr=trace)
-	else:
-	    if self.trace_file: 
-		print >>self.trace_file, "debug [scp_file]: %s" % \
-			" ".join(scp_cmd)
-	    rv = 0
-
-	return rv == 0
-
-    def ssh_cmd(self, user, host, cmd, wname=None):
-	sh_str = "%s %s@%s %s" % (self.ssh_exec, user, host, cmd)
-
-	trace = self.trace_file
-	if not trace:
-	    try:
-		trace = open("/dev/null", "w")
-	    except IOError:
-		raise service_error(service_error.internal,
-			"Cannot open /dev/null??");
-
-	if not self.debug:
-	    sub = Popen(sh_str, shell=True, stdout=trace, stderr=trace)
-	    return sub.wait() == 0
-	else:
-	    if self.trace_file:
-		print >>self.trace_file,"debug [ssh_cmd]: %s" % sh_str 
-	    return True
-
-    def ship_scripts(self, host, user, dest_dir):
-	if self.ssh_cmd(user, host, "mkdir -p %s" % dest_dir):
-	    for s in self.scripts:
-		if not self.scp_file("%s/%s" % (self.scripts_dir, s),
-			user, host, dest_dir):
-		    return False
-	    return True
-	else:
-	    return False
-
-    def ship_configs(self, host, user, src_dir, dest_dir):
-	if not self.ssh_cmd(user, host, "mkdir -p %s" % dest_dir):
-	    return False
-	if not self.ssh_cmd(user, host, "chmod 770 %s" % dest_dir):
-	    return False
-
-	for f in os.listdir(src_dir):
-	    if os.path.isdir(f):
-		if not self.ship_configs(host, user, "%s/%s" % (src_dir, f), 
-			"%s/%s" % (dest_dir, f)):
-		    return False
-	    else:
-		if not self.scp_file("%s/%s" % (src_dir, f), 
-			user, host, dest_dir):
-		    return False
-	return True
-
-    def start_segment(self, tb, eid, tbparams, tmpdir, timeout=0):
-	host = "%s%s" % (tbparams[tb]['host'], tbparams[tb]['domain'])
-	user = tbparams[tb]['user']
-	pid = tbparams[tb]['project']
-	# XXX
-	base_confs = ( "hosts",)
-	tclfile = "%s.%s.tcl" % (eid, tb)
-	expinfo_exec = "/usr/testbed/bin/expinfo"
-	proj_dir = "/proj/%s/exp/%s/tmp" % (pid, eid)
-	tarfiles_dir = "/proj/%s/tarfiles/%s" % (pid, eid)
-	rpms_dir = "/proj/%s/rpms/%s" % (pid, eid)
-	state_re = re.compile("State:\s+(\w+)")
-	no_exp_re = re.compile("^No\s+such\s+experiment")
-	state = None
-	cmd = [self.ssh_exec, "%s@%s" % (user, host), expinfo_exec, pid, eid]
-
-
-	if self.trace_file:
-	    print >>self.trace_file, "status request: %s" % " ".join(cmd)
-	
-	if not self.trace_file:
-	    try:
-		st_file = open("/dev/null", "w")
-	    except IOError:
-		raise service_error(service_error.internal, 
-			"Cannot open /dev/null!?")
-	else:
-	    st_file = self.trace_file
-
-	status = Popen(cmd, stdout=PIPE, stderr=st_file)
-	for line in status.stdout:
-	    m = state_re.match(line)
-	    if m: state = m.group(1)
-	    else:
-		m = no_exp_re.match(line)
-		if m: state = "none"
-	rv = status.wait()
-	# If the experiment is not present the subcommand returns a non-zero
-	# return value.  If we successfully parsed a "none" outcome, ignore the
-	# return code.
-	if rv != 0 and state != "none":
-	    raise service_error(service_error.internal,
-		    "Cannot get status of segment %s:%s/%s" % (tb, pid, eid))
-	if self.trace_file:
-	    print >>self.trace_file, "%s: %s" % (tb, state)
-	    print >>self.trace_file, "transferring experiment to %s" % tb
-
-	if not self.scp_file("%s/%s/%s" % (tmpdir, tb, tclfile), user, host):
-	    return False
-	# Clear the federation files
-	if not self.ssh_cmd(user, host, 
-		"/bin/sh -c \"'/bin/rm -rf %s'\"" % proj_dir):
-	    return False
-	if not self.ssh_cmd(user, host, 
-		"/bin/sh -c \"'mkdir -p %s'\"" % proj_dir):
-	    return False
-	# Clear and create the tarfiles and rpm directories
-	for d in (tarfiles_dir, rpms_dir):
-	    if not self.ssh_cmd(user, host, 
-		    "/bin/sh -c \"'/bin/rm -rf %s/*'\"" % d):
-		return False
-	    if not self.ssh_cmd(user, host, "mkdir -p %s" % d, 
-		    "create tarfiles"):
-		return False
-	
-	if state == 'active':
-	    # Remote experiment is active.  Modify it.
-	    for f in base_confs:
-		if not self.scp_file("%s/%s" % (tmpdir, f), user, host,
-			"%s/%s" % (proj_dir, f)):
-		    return False
-	    if not self.ship_scripts(host, user, proj_dir):
-		return False
-	    if not self.ship_configs(host, user, "%s/%s" % (tmpdir, tb),
-		    proj_dir):
-		return False
-	    if os.path.isdir("%s/tarfiles" % tmpdir):
-		if not self.ship_configs(host, user,
-			"%s/tarfiles" % tmpdir, tarfiles_dir):
-		    return False
-	    if os.path.isdir("%s/rpms" % tmpdir):
-		if not self.ship_configs(host, user,
-			"%s/rpms" % tmpdir, tarfiles_dir):
-		    return False
-	    if self.trace_file:
-		print >>self.trace_file, "Modifying %s on %s" % (eid, tb)
-	    if not self.ssh_cmd(user, host,
-		    "/usr/testbed/bin/modexp -r -s -w %s %s %s" % \
-			    (pid, eid, tclfile), "modexp"):
-		return False
-	    return True
-	elif state == "swapped":
-	    # Remote experiment swapped out.  Modify it and swap it in.
-	    for f in base_confs:
-		if not self.scp_file("%s/%s" % (tmpdir, f), user, host,
-			"%s/%s" % (proj_dir, f)):
-		    return False
-	    if not self.ship_scripts(host, user, proj_dir):
-		return False
-	    if not self.ship_configs(host, user, "%s/%s" % (tmpdir, tb),
-		    proj_dir):
-		return False
-	    if os.path.isdir("%s/tarfiles" % tmpdir):
-		if not self.ship_configs(host, user,
-			"%s/tarfiles" % tmpdir, tarfiles_dir):
-		    return False
-	    if os.path.isdir("%s/rpms" % tmpdir):
-		if not self.ship_configs(host, user,
-			"%s/rpms" % tmpdir, tarfiles_dir):
-		    return False
-	    if self.trace_file:
-		print >>self.trace_file, "Modifying %s on %s" % (eid, tb)
-	    if not self.ssh_cmd(user, host,
-		    "/usr/testbed/bin/modexp -w %s %s %s" % (pid, eid, tclfile),
-		    "modexp"):
-		return False
-	    if self.trace_file:
-		print >>self.trace_file, "Swapping %s in on %s" % (eid, tb)
-	    if not self.ssh_cmd(user, host,
-		    "/usr/testbed/bin/swapexp -w %s %s in" % (pid, eid),
-		    "swapexp"):
-		return False
-	    return True
-	elif state == "none":
-	    # No remote experiment.  Create one.  We do this in 2 steps so we
-	    # can put the configuration files and scripts into the new
-	    # experiment directories.
-
-	    # Tarfiles must be present for creation to work
-	    if os.path.isdir("%s/tarfiles" % tmpdir):
-		if not self.ship_configs(host, user,
-			"%s/tarfiles" % tmpdir, tarfiles_dir):
-		    return False
-	    if os.path.isdir("%s/rpms" % tmpdir):
-		if not self.ship_configs(host, user,
-			"%s/rpms" % tmpdir, tarfiles_dir):
-		    return False
-	    if self.trace_file:
-		print >>self.trace_file, "Creating %s on %s" % (eid, tb)
-	    if not self.ssh_cmd(user, host,
-		    "/usr/testbed/bin/startexp -i -f -w -p %s -e %s %s" % \
-			    (pid, eid, tclfile), "startexp"):
-		return False
-	    # After startexp the per-experiment directories exist
-	    for f in base_confs:
-		if not self.scp_file("%s/%s" % (tmpdir, f), user, host,
-			"%s/%s" % (proj_dir, f)):
-		    return False
-	    if not self.ship_scripts(host, user, proj_dir):
-		return False
-	    if not self.ship_configs(host, user, "%s/%s" % (tmpdir, tb),
-		    proj_dir):
-		return False
-	    if self.trace_file:
-		print >>self.trace_file, "Swapping %s in on %s" % (eid, tb)
-	    if not self.ssh_cmd(user, host,
-		    "/usr/testbed/bin/swapexp -w %s %s in" % (pid, eid),
-		    "swapexp"):
-		return False
-	    return True
-	else:
-	    if self.trace_file:
-		print >>self.trace_file, "unknown state %s" % state
-	    return False
-
-    def stop_segment(self, tb, eid, tbparams):
-	user = tbparams[tb]['user']
-	host = "%s%s" % (tbparams[tb]['host'], tbparams[tb]['domain'])
-	pid = tbparams[tb]['project']
-
-	if self.trace_file:
-	    print >>self.trace_file, "Stopping %s on %s" % (eid, tb)
-	return self.ssh_cmd(user, host,
-		"/usr/testbed/bin/swapexp -w %s %s out" % (pid, eid))
-
-	
-    def generate_ssh_keys(self, dest, type="rsa" ):
-	"""
-	Generate a set of keys for the gateways to use to talk.
-
-	Keys are of type type and are stored in the required dest file.
-	"""
-	valid_types = ("rsa", "dsa")
-	t = type.lower();
-	if t not in valid_types: raise ValueError
-
-	trace = self.trace_file
-	if not trace:
-	    try:
-		trace = open("/dev/null", "w")
-	    except IOError:
-		raise service_error(service_error.internal,
-			"Cannot open /dev/null??");
-
-	# May raise CalledProcessError
-	rv = call([self.ssh_keygen, '-t', t, '-N', '', '-f', dest],
-		stdout=trace, stderr=trace)
-	if rv != 0:
-	    raise service_error(service_error.internal, 
-		    "Cannot generate nonce ssh keys.  %s return code %d" \
-			    % (self.ssh_keygen, rv))
-
-    def gentopo(self, str):
-	class topo_parse:
-	    def __init__(self):
-		self.str_subelements = ('vname', 'vnode', 'ips', 'ip', 'member')
-		self.int_subelements = ( 'bandwidth',)
-		self.float_subelements = ( 'delay',)
-		self.nodes = [ ]
-		self.lans =  [ ]
-		self.element = { }
-		self.topo = { \
-			'node': self.nodes,\
-			'lan' : self.lans,\
-		    }
-		self.chars = ""
-
-	    def end_element(self, name):
-		if name == 'node':
-		    self.nodes.append(self.element)
-		    self.element = { }
-		elif name == 'lan':
-		    self.lans.append(self.element)
-		    self.element = { }
-		elif name in self.str_subelements:
-		    self.element[name] = self.chars
-		    self.chars = ""
-		elif name in self.int_subelements:
-		    self.element[name] = int(self.chars)
-		    self.chars = ""
-		elif name in self.float_subelements:
-		    self.element[name] = float(self.chars)
-		    self.chars = ""
-
-	    def found_chars(self, data):
-		self.chars += data.rstrip()
-
-
-	tp = topo_parse();
-	parser = xml.parsers.expat.ParserCreate()
-	parser.EndElementHandler = tp.end_element
-	parser.CharacterDataHandler = tp.found_chars
-
-	parser.Parse(str)
-
-	return tp.topo
-	
-
-    def genviz(self, topo):
-	"""
-	Generate the visualization the virtual topology
-	"""
-
-	neato = "/usr/local/bin/neato"
-	# These are used to parse neato output and to create the visualization
-	# file.
-	vis_re = re.compile('^\s*"?([\w\-]+)"?\s+\[.*pos="(\d+),(\d+)"')
-	vis_fmt = "<node><name>%s</name><x>%s</x><y>%s</y><type>" + \
-		"%s</type></node>"
-
-	try:
-	    # Node names
-	    nodes = [ n['vname'] for n in topo['node'] ]
-	    topo_lans = topo['lan']
-	except KeyError:
-	    raise service_error(service_error.internal, "Bad topology")
-
-	lans = { }
-	links = { }
-
-	# Walk through the virtual topology, organizing the connections into
-	# 2-node connections (links) and more-than-2-node connections (lans).
-	# When a lan is created, it's added to the list of nodes (there's a
-	# node in the visualization for the lan).
-	for l in topo_lans:
-	    if links.has_key(l['vname']):
-		if len(links[l['vname']]) < 2:
-		    links[l['vname']].append(l['vnode'])
-		else:
-		    nodes.append(l['vname'])
-		    lans[l['vname']] = links[l['vname']]
-		    del links[l['vname']]
-		    lans[l['vname']].append(l['vnode'])
-	    elif lans.has_key(l['vname']):
-		lans[l['vname']].append(l['vnode'])
-	    else:
-		links[l['vname']] = [ l['vnode'] ]
-
-
-	# Open up a temporary file for dot to turn into a visualization
-	try:
-	    df, dotname = tempfile.mkstemp()
-	    dotfile = os.fdopen(df, 'w')
-	except IOError:
-	    raise service_error(service_error.internal,
-		    "Failed to open file in genviz")
-
-	# Generate a dot/neato input file from the links, nodes and lans
-	try:
-	    print >>dotfile, "graph G {"
-	    for n in nodes:
-		print >>dotfile, '\t"%s"' % n
-	    for l in links.keys():
-		print >>dotfile, '\t"%s" -- "%s"' %  tuple(links[l])
-	    for l in lans.keys():
-		for n in lans[l]:
-		    print >>dotfile, '\t "%s" -- "%s"' % (n,l)
-	    print >>dotfile, "}"
-	    dotfile.close()
-	except TypeError:
-	    raise service_error(service_error.internal,
-		    "Single endpoint link in vtopo")
-	except IOError:
-	    raise service_error(service_error.internal, "Cannot write dot file")
-
-	# Use dot to create a visualization
-	dot = Popen([neato, '-Gstart=rand', '-Gepsilon=0.005', '-Gmaxiter=2000',
-		'-Gpack=true', dotname], stdout=PIPE)
-
-	# Translate dot to vis format
-	vis_nodes = [ ]
-	vis = { 'node': vis_nodes }
-	for line in dot.stdout:
-	    m = vis_re.match(line)
-	    if m:
-		vn = m.group(1)
-		vis_node = {'name': vn, \
-			'x': float(m.group(2)),\
-			'y' : float(m.group(3)),\
-		    }
-		if vn in links.keys() or vn in lans.keys():
-		    vis_node['type'] = 'lan'
-		else:
-		    vis_node['type'] = 'node'
-		vis_nodes.append(vis_node)
-	rv = dot.wait()
-
-	os.remove(dotname)
-	if rv == 0 : return vis
-	else: return None
-
-
-    def get_access(self, tb, nodes, user, tbparam):
-	"""
-	Get access to testbed through fedd and set the parameters for that tb
-	"""
-
-	translate_attr = {
-	    'slavenodestartcmd': 'expstart',
-	    'slaveconnectorstartcmd': 'gwstart',
-	    'masternodestartcmd': 'mexpstart',
-	    'masterconnectorstartcmd': 'mgwstart',
-	    'connectorimage': 'gwimage',
-	    'connectortype': 'gwtype',
-	    'tunnelcfg': 'tun',
-	    'smbshare': 'smbshare',
-	}
-
-	# XXX multi-level access
-	uri = self.tbmap.get(tb, None)
-	if not uri:
-	    raise service_error(serice_error.server_config, 
-		    "Unknown testbed: %s" % tb)
-
-	# The basic request
-	req = {\
-		'destinationTestbed' : { 'uri' : uri },
-		'user':  user,
-		'allocID' : { 'localname': 'test' },
-		'access' : [ { 'sshPubkey' : self.ssh_pubkey } ]
-	    }
-	
-	# node resources if any
-	if nodes != None and len(nodes) > 0:
-	    rnodes = [ ]
-	    for n in nodes:
-		rn = { }
-		image, hw, count = n.split(":")
-		if image: rn['image'] = [ image ]
-		if hw: rn['hardware'] = [ hw ]
-		if count: rn['count'] = int(count)
-		rnodes.append(rn)
-	    req['resources']= { }
-	    req['resources']['node'] = rnodes
-
-	# No retry loop here.  Proxy servers must correctly authenticate
-	# themselves without help
-	try:
-	    ctx = fedd_ssl_context(self.cert_file, 
-		    self.trusted_certs, password=self.cert_pwd)
-	except SSL.SSLError:
-	    raise service_error(service_error.server_config, 
-		    "Server certificates misconfigured")
-
-	loc = feddServiceLocator();
-	port = loc.getfeddPortType(uri,
-		transport=M2Crypto.httpslib.HTTPSConnection, 
-		transdict={ 'ssl_context' : ctx })
-
-	# Reconstruct the full request message
-	msg = RequestAccessRequestMessage()
-	msg.set_element_RequestAccessRequestBody(
-		pack_soap(msg, "RequestAccessRequestBody", req))
-	try:
-	    resp = port.RequestAccess(msg)
-	except ZSI.ParseException, e:
-	    raise service_error(service_error.req,
-		    "Bad format message (XMLRPC??): %s" %
-		    str(e))
-	r = unpack_soap(resp)
-
-	if r.has_key('RequestAccessResponseBody'):
-	    r = r['RequestAccessResponseBody']
-	else:
-	    raise service_error(service_error.proxy,
-		    "Bad proxy response")
-
-
-	e = r['emulab']
-	p = e['project']
-	tbparam[tb] = { 
-		"boss": e['boss'],
-		"host": e['ops'],
-		"domain": e['domain'],
-		"fs": e['fileServer'],
-		"eventserver": e['eventServer'],
-		"project": unpack_id(p['name']),
-		"emulab" : e
-		}
-	# Make the testbed name be the label the user applied
-	p['testbed'] = {'localname': tb }
-
-	for u in p['user']:
-	    tbparam[tb]['user'] = unpack_id(u['userID'])
-
-	for a in e['fedAttr']:
-	    if a['attribute']:
-		key = translate_attr.get(a['attribute'].lower(), None)
-		if key:
-		    tbparam[tb][key]= a['value']
-	
-    class current_testbed:
-	def __init__(self, eid, tmpdir):
-	    self.begin_testbed = re.compile("^#\s+Begin\s+Testbed\s+\((\w+)\)")
-	    self.end_testbed = re.compile("^#\s+End\s+Testbed\s+\((\w+)\)")
-	    self.current_testbed = None
-	    self.testbed_file = None
-
-	    self.def_expstart = \
-		    "sudo -H /bin/sh FEDDIR/fed_bootstrap >& /tmp/federate";
-	    self.def_mexpstart = "sudo -H FEDDIR/make_hosts FEDDIR/hosts";
-	    self.def_gwstart = \
-		    "sudo -H FEDDIR/fed-tun.pl -f GWCONF>& /tmp/bridge.log";
-	    self.def_mgwstart = \
-		    "sudo -H FEDDIR/fed-tun.pl -f GWCONF >& /tmp/bridge.log";
-	    self.def_gwimage = "FBSD61-TUNNEL2";
-	    self.def_gwtype = "pc";
-
-	    self.eid = eid
-	    self.tmpdir = tmpdir
-
-	def __call__(self, line, master, allocated, tbparams):
-	    # Capture testbed topology descriptions
-	    if self.current_testbed == None:
-		m = self.begin_testbed.match(line)
-		if m != None:
-		    self.current_testbed = m.group(1)
-		    if self.current_testbed == None:
-			raise service_error(service_error.req,
-				"Bad request format (unnamed testbed)")
-		    allocated[self.current_testbed] = \
-			    allocated.get(self.current_testbed,0) + 1
-		    tb_dir = "%s/%s" % (self.tmpdir, self.current_testbed)
-		    if not os.path.exists(tb_dir):
-			try:
-			    os.mkdir(tb_dir)
-			except IOError:
-			    raise service_error(service_error.internal,
-				    "Cannot create %s" % tb_dir)
-		    try:
-			self.testbed_file = open("%s/%s.%s.tcl" %
-				(tb_dir, self.eid, self.current_testbed), 'w')
-		    except IOError:
-			self.testbed_file = None
-		    return True
-		else: return False
-	    else:
-		m = self.end_testbed.match(line)
-		if m != None:
-		    if m.group(1) != self.current_testbed:
-			raise service_error(service_error.internal, 
-				"Mismatched testbed markers!?")
-		    if self.testbed_file != None: 
-			self.testbed_file.close()
-			self.testbed_file = None
-		    self.current_testbed = None
-		elif self.testbed_file:
-		    # Substitute variables and put the line into the local
-		    # testbed file.
-		    gwtype = tbparams[self.current_testbed].get('gwtype', 
-			    self.def_gwtype)
-		    gwimage = tbparams[self.current_testbed].get('gwimage', 
-			    self.def_gwimage)
-		    mgwstart = tbparams[self.current_testbed].get('mgwstart', 
-			    self.def_mgwstart)
-		    mexpstart = tbparams[self.current_testbed].get('mexpstart', 
-			    self.def_mexpstart)
-		    gwstart = tbparams[self.current_testbed].get('gwstart', 
-			    self.def_gwstart)
-		    expstart = tbparams[self.current_testbed].get('expstart', 
-			    self.def_expstart)
-		    project = tbparams[self.current_testbed].get('project')
-		    line = re.sub("GWTYPE", gwtype, line)
-		    line = re.sub("GWIMAGE", gwimage, line)
-		    if self.current_testbed == master:
-			line = re.sub("GWSTART", mgwstart, line)
-			line = re.sub("EXPSTART", mexpstart, line)
-		    else:
-			line = re.sub("GWSTART", gwstart, line)
-			line = re.sub("EXPSTART", expstart, line)
-		    # XXX: does `` embed without doing enything else?
-		    line = re.sub("GWCONF", "FEDDIR`hostname`.gw.conf", line)
-		    line = re.sub("PROJDIR", "/proj/%s/" % project, line)
-		    line = re.sub("EID", self.eid, line)
-		    line = re.sub("FEDDIR", "/proj/%s/exp/%s/tmp/" % \
-			    (project, self.eid), line)
-		    print >>self.testbed_file, line
-		return True
-
-    class allbeds:
-	def __init__(self, get_access):
-	    self.begin_allbeds = re.compile("^#\s+Begin\s+Allbeds")
-	    self.end_allbeds = re.compile("^#\s+End\s+Allbeds")
-	    self.in_allbeds = False
-	    self.get_access = get_access
-
-	def __call__(self, line, user, tbparams):
-	    # Testbed access parameters
-	    if not self.in_allbeds:
-		if self.begin_allbeds.match(line):
-		    self.in_allbeds = True
-		    return True
-		else:
-		    return False
-	    else:
-		if self.end_allbeds.match(line):
-		    self.in_allbeds = False
-		else:
-		    nodes = line.split('|')
-		    tb = nodes.pop(0)
-		    self.get_access(tb, nodes, user, tbparams)
-		return True
-
-    class gateways:
-	def __init__(self, eid, master, tmpdir, gw_pubkey,
-		gw_secretkey, copy_file):
-	    self.begin_gateways = \
-		    re.compile("^#\s+Begin\s+gateways\s+\((\w+)\)")
-	    self.end_gateways = re.compile("^#\s+End\s+gateways\s+\((\w+)\)")
-	    self.current_gateways = None
-	    self.control_gateway = None
-	    self.active_end = { }
-
-	    self.eid = eid
-	    self.master = master
-	    self.tmpdir = tmpdir
-	    self.gw_pubkey_base = gw_pubkey
-	    self.gw_secretkey_base = gw_secretkey
-
-	    self.copy_file = copy_file
-
-
-	def gateway_conf_file(self, gw, master, eid, pubkey, privkey,
-		active_end, tbparams, dtb, myname, desthost, type):
-	    """
-	    Produce a gateway configuration file from a gateways line. 
-	    """
-
-	    sproject = tbparams[gw].get('project', 'project')
-	    dproject = tbparams[dtb].get('project', 'project')
-	    sdomain = ".%s.%s%s" % (eid, sproject,
-		    tbparams[gw].get('domain', ".example.com"))
-	    ddomain = ".%s.%s%s" % (eid, dproject,
-		    tbparams[dtb].get('domain', ".example.com"))
-	    boss = tbparams[master].get('boss', "boss")
-	    fs = tbparams[master].get('fs', "fs")
-	    event_server = "%s%s" % \
-		    (tbparams[gw].get('eventserver', "event_server"),
-			    tbparams[gw].get('domain', "example.com"))
-	    remote_event_server = "%s%s" % \
-		    (tbparams[dtb].get('eventserver', "event_server"),
-			    tbparams[dtb].get('domain', "example.com"))
-	    seer_control = "%s%s" % \
-		    (tbparams[gw].get('control', "control"), sdomain)
-	    remote_script_dir = "/proj/%s/exp/%s/tmp" % ( dproject, eid)
-	    local_script_dir = "/proj/%s/exp/%s/tmp" % ( sproject, eid)
-	    tunnel_cfg = tbparams[gw].get("tun", "false")
-
-	    conf_file = "%s%s.gw.conf" % (myname, sdomain)
-	    remote_conf_file = "%s%s.gw.conf" % (desthost, ddomain)
-
-	    # translate to lower case so the `hostname` hack for specifying
-	    # configuration files works.
-	    conf_file = conf_file.lower();
-	    remote_conf_file = remote_conf_file.lower();
-
-	    if dtb == master:
-		active = "false"
-	    elif gw == master:
-		active = "true"
-	    elif active_end.has_key['%s-%s' % (dtb, gw)]:
-		active = "false"
-	    else:
-		active_end['%s-%s' % (gw, dtb)] = 1
-		active = "true"
-
-	    gwconfig = open("%s/%s/%s" % (self.tmpdir, gw, conf_file), "w")
-	    print >>gwconfig, "Active: %s" % active
-	    print >>gwconfig, "TunnelCfg: %s" % tunnel_cfg
-	    print >>gwconfig, "BossName: %s" % boss
-	    print >>gwconfig, "FsName: %s" % fs
-	    print >>gwconfig, "EventServerName: %s" % event_server
-	    print >>gwconfig, "RemoteEventServerName: %s" % remote_event_server
-	    print >>gwconfig, "SeerControl: %s" % seer_control
-	    print >>gwconfig, "Type: %s" % type
-	    print >>gwconfig, "RemoteScriptDir: %s" % remote_script_dir
-	    print >>gwconfig, "EventRepeater: %s/fed_evrepeater" % \
-		    local_script_dir
-	    print >>gwconfig, "RemoteExperiment: %s/%s" % (dproject, eid)
-	    print >>gwconfig, "LocalExperiment: %s/%s" % (sproject, eid)
-	    print >>gwconfig, "RemoteConfigFile: %s/%s" % \
-		    (remote_script_dir, remote_conf_file)
-	    print >>gwconfig, "Peer: %s%s" % (desthost, ddomain)
-	    print >>gwconfig, "Pubkeys: %s/%s" % (local_script_dir, pubkey)
-	    print >>gwconfig, "Privkeys: %s/%s" % (local_script_dir, privkey)
-	    gwconfig.close()
-
-	    return active == "true"
-
-	def __call__(self, line, allocated, tbparams):
-	    # Process gateways
-	    if not self.current_gateways:
-		m = self.begin_gateways.match(line)
-		if m:
-		    self.current_gateways = m.group(1)
-		    if allocated.has_key(self.current_gateways):
-			# This test should always succeed
-			tb_dir = "%s/%s" % (self.tmpdir, self.current_gateways)
-			if not os.path.exists(tb_dir):
-			    try:
-				os.mkdir(tb_dir)
-			    except IOError:
-				raise service_error(service_error.internal,
-					"Cannot create %s" % tb_dir)
-		    else:
-			# XXX
-			print >>sys.stderr, \
-			    "Ignoring gateways for unknown testbed %s" \
-				    % self.current_gateways
-			self.current_gateways = None
-		    return True
-		else:
-		    return False
-	    else:
-		m = self.end_gateways.match(line)
-		if m :
-		    if m.group(1) != self.current_gateways:
-			raise service_error(service_error.internal,
-				"Mismatched gateway markers!?")
-		    if self.control_gateway:
-			try:
-			    cc = open("%s/%s/client.conf" %
-				    (self.tmpdir, self.current_gateways), 'w')
-			    print >>cc, "ControlGateway: %s" % \
-				    self.control_gateway
-			    if tbparams[self.master].has_key('smbshare'):
-				print >>cc, "SMBSHare: %s" % \
-					tbparams[self.master]['smbshare']
-			    print >>cc, "ProjectUser: %s" % \
-				    tbparams[self.master]['user']
-			    print >>cc, "ProjectName: %s" % \
-				    tbparams[self.master]['project']
-			    cc.close()
-			except IOError:
-			    raise service_error(service_error.internal,
-				    "Error creating client config")
-			try:
-			    cc = open("%s/%s/seer.conf" %
-				    (self.tmpdir, self.current_gateways),
-				    'w')
-			    if self.current_gateways != self.master:
-				print >>cc, "ControlNode: %s" % \
-					self.control_gateway
-			    print >>cc, "ExperimentID: %s/%s" % \
-				    ( tbparams[self.master]['project'], \
-				    self.eid )
-			    cc.close()
-			except IOError:
-			    raise service_error(service_error.internal,
-				    "Error creating seer config")
-		    else:
-			if self.trace_file:
-			    print >>sys.stderr, "No control gateway for %s" %\
-				    self.current_gateways
-		    self.current_gateways = None
-		else:
-		    dtb, myname, desthost, type = line.split(" ")
-
-		    if type == "control" or type == "both":
-			self.control_gateway = "%s.%s.%s%s" % (myname, 
-				self.eid, 
-				tbparams[self.current_gateways]['project'],
-				tbparams[self.current_gateways]['domain'])
-		    try:
-			active = self.gateway_conf_file(self.current_gateways,
-				self.master, self.eid, self.gw_pubkey_base,
-				self.gw_secretkey_base,
-				self.active_end, tbparams, dtb, myname,
-				desthost, type)
-		    except IOError, e:
-			raise service_error(service_error.internal,
-				"Failed to write config file for %s" % \
-					self.current_gateway)
-	    
-		    gw_pubkey = "%s/keys/%s" % \
-			    (self.tmpdir, self.gw_pubkey_base)
-		    gw_secretkey = "%s/keys/%s" % \
-			    (self.tmpdir, self.gw_secretkey_base)
-
-		    pkfile = "%s/%s/%s" % \
-			    ( self.tmpdir, self.current_gateways, 
-				    self.gw_pubkey_base)
-		    skfile = "%s/%s/%s" % \
-			    ( self.tmpdir, self.current_gateways, 
-				    self.gw_secretkey_base)
-
-		    if not os.path.exists(pkfile):
-			try:
-			    self.copy_file(gw_pubkey, pkfile)
-			except IOError:
-			    service_error(service_error.internal,
-				    "Failed to copy pubkey file")
-
-		    if active and not os.path.exists(skfile):
-			try:
-			    self.copy_file(gw_secretkey, skfile)
-			except IOError:
-			    service_error(service_error.internal,
-				    "Failed to copy secretkey file")
-		return True
-
-    class shunt_to_file:
-	def __init__(self, begin, end, filename):
-	    self.begin = re.compile(begin)
-	    self.end = re.compile(end)
-	    self.in_shunt = False
-	    self.file = None
-	    self.filename = filename
-
-	def __call__(self, line):
-	    if not self.in_shunt:
-		if self.begin.match(line):
-		    self.in_shunt = True
-		    try:
-			self.file = open(self.filename, "w")
-		    except:
-			self.file = None
-			raise
-		    return True
-		else:
-		    return False
-	    else:
-		if self.end.match(line):
-		    if self.file: 
-			self.file.close()
-			self.file = None
-		    self.in_shunt = False
-		else:
-		    if self.file:
-			print >>self.file, line
-		return True
-
-    class shunt_to_list:
-	def __init__(self, begin, end):
-	    self.begin = re.compile(begin)
-	    self.end = re.compile(end)
-	    self.in_shunt = False
-	    self.list = [ ]
-	
-	def __call__(self, line):
-	    if not self.in_shunt:
-		if self.begin.match(line):
-		    self.in_shunt = True
-		    return True
-		else:
-		    return False
-	    else:
-		if self.end.match(line):
-		    self.in_shunt = False
-		else:
-		    self.list.append(line)
-		return True
-
-    class shunt_to_string:
-	def __init__(self, begin, end):
-	    self.begin = re.compile(begin)
-	    self.end = re.compile(end)
-	    self.in_shunt = False
-	    self.str = ""
-	
-	def __call__(self, line):
-	    if not self.in_shunt:
-		if self.begin.match(line):
-		    self.in_shunt = True
-		    return True
-		else:
-		    return False
-	    else:
-		if self.end.match(line):
-		    self.in_shunt = False
-		else:
-		    self.str += line
-		return True
-
-    def create_experiment(self, req, fid):
-	try:
-	    tmpdir = tempfile.mkdtemp(prefix="split-")
-	except IOError:
-	    raise service_error(service_error.internal, "Cannot create tmp dir")
-
-	gw_pubkey_base = "fed.%s.pub" % self.ssh_type
-	gw_secretkey_base = "fed.%s" % self.ssh_type
-	gw_pubkey = tmpdir + "/keys/" + gw_pubkey_base
-	gw_secretkey = tmpdir + "/keys/" + gw_secretkey_base
-	tclfile = tmpdir + "/experiment.tcl"
-	tbparams = { }
-
-	pid = "dummy"
-	gid = "dummy"
-	# XXX
-	fail_soft = False
-
-	try:
-	    os.mkdir(tmpdir+"/keys")
-	except OSError:
-	    raise service_error(service_error.internal,
-		    "Can't make temporary dir")
-
-	req = req.get('CreateRequestBody', None)
-	if not req:
-	    raise service_error(service_error.req,
-		    "Bad request format (no CreateRequestBody)")
-	# The tcl parser needs to read a file so put the content into that file
-	file_content=req.get('experimentdescription', None)
-	if file_content:
-	    try:
-		f = open(tclfile, 'w')
-		f.write(file_content)
-		f.close()
-	    except IOError:
-		raise service_error(service_error.internal,
-			"Cannot write temp experiment description")
-	else:
-	    raise service_error(service_error.req, "No experiment description")
-
-	if req.has_key('experimentID') and \
-		req['experimentID'].has_key('localname'):
-	    eid = req['experimentID']['localname']
-	    while (self.state.has_key(eid)):
-		eid += random.choice(string.ascii_letters)
-	else:
-	    eid = self.exp_stem
-	    for i in range(0,5):
-		eid += random.choice(string.ascii_letters)
-	    while (self.state.has_key(eid)):
-		eid = self.exp_stem
-		for i in range(0,5):
-		    eid += random.choice(string.ascii_letters)
-
-	try:
-	    self.generate_ssh_keys(gw_secretkey, self.ssh_type)
-	except ValueError:
-	    raise service_error(service_error.server_config, 
-		    "Bad key type (%s)" % self.ssh_type)
-
-	user = req.get('user', None)
-	if user == None:
-	    raise service_error(service_error.req, "No user")
-
-	master = req.get('master', None)
-	if master == None:
-	    raise service_error(service_error.req, "No master testbed label")
-	
-	
-	tclcmd = [self.tclsh, self.tcl_splitter, '-s', '-x', 
-	    str(self.muxmax), '-m', master, pid, gid, eid, tclfile]
-	tclparser = Popen(tclcmd, stdout=PIPE)
-
-	allocated = { }
-	started = { }
-
-	parse_current_testbed = self.current_testbed(eid, tmpdir)
-	parse_allbeds = self.allbeds(self.get_access)
-	parse_gateways = self.gateways(eid, master, tmpdir,
-		gw_pubkey_base, gw_secretkey_base, self.copy_file)
-	parse_vtopo = self.shunt_to_string("^#\s+Begin\s+Vtopo",
-		    "^#\s+End\s+Vtopo")
-	parse_hostnames = self.shunt_to_file("^#\s+Begin\s+hostnames",
-		    "^#\s+End\s+hostnames", tmpdir + "/hosts")
-	parse_tarfiles = self.shunt_to_list("^#\s+Begin\s+tarfiles",
-		"^#\s+End\s+tarfiles")
-	parse_rpms = self.shunt_to_list("^#\s+Begin\s+rpms",
-		"^#\s+End\s+rpms")
-
-	for line in tclparser.stdout:
-	    line = line.rstrip()
-	    if parse_current_testbed(line, master, allocated, tbparams):
-		continue
-	    elif parse_allbeds(line, user, tbparams):
-		continue
-	    elif parse_gateways(line, allocated, tbparams):
-		continue
-	    elif parse_vtopo(line):
-		continue
-	    elif parse_hostnames(line):
-		continue
-	    elif parse_tarfiles(line):
-		continue
-	    elif parse_rpms(line):
-		continue
-	    else:
-		raise service_error(service_error.internal, 
-			"Bad tcl parse? %s" % line)
-
-	vtopo = self.gentopo(parse_vtopo.str)
-	if not vtopo:
-	    raise service_error(service_error.internal, 
-		    "Failed to generate virtual topology")
-
-	vis = self.genviz(vtopo)
-	if not vis:
-	    raise service_error(service_error.internal, 
-		    "Failed to generate visualization")
-
-	# save federant information
-	for k in allocated.keys():
-	    tbparams[k]['federant'] = {\
-		    'name': [ { 'localname' : eid} ],\
-		    'emulab': tbparams[k]['emulab'],\
-		    'master' : k == master,\
-		}
-
-
-	# Copy tarfiles and rpms needed at remote sites into a staging area
-	try:
-	    for t in parse_tarfiles.list:
-		if not os.path.exists("%s/tarfiles" % tmpdir):
-		    os.mkdir("%s/tarfiles" % tmpdir)
-		self.copy_file(t, "%s/tarfiles/%s" % \
-			(tmpdir, os.path.basename(t)))
-	    for r in parse_rpms.list:
-		if not os.path.exists("%s/rpms" % tmpdir):
-		    os.mkdir("%s/rpms" % tmpdir)
-		self.copy_file(r, "%s/rpms/%s" % \
-			(tmpdir, os.path.basename(r)))
-	except IOError, e:
-	    raise service_error(service_error.internal, 
-		    "Cannot stage tarfile/rpm: %s" % e.strerror)
-
-	thread_pool_info = self.thread_pool()
-	threads = [ ]
-
-	for tb in [ k for k in allocated.keys() if k != master]:
-	    # Wait until we have a free slot to start the next testbed load
-	    thread_pool_info.acquire()
-	    while thread_pool_info.started - \
-		    thread_pool_info.terminated >= self.nthreads:
-		thread_pool_info.wait()
-	    thread_pool_info.release()
-
-	    # Create and start a thread to start the segment, and save it to
-	    # get the return value later
-	    t  = self.pooled_thread(target=self.start_segment, 
-		    args=(tb, eid, tbparams, tmpdir, 0), name=tb,
-		    pdata=thread_pool_info, trace_file=self.trace_file)
-	    threads.append(t)
-	    t.start()
-
-	# Wait until all finish (the first clause of the while is to make sure
-	# one starts)
-	thread_pool_info.acquire()
-	while thread_pool_info.started == 0 or \
-		thread_pool_info.started > thread_pool_info.terminated:
-	    thread_pool_info.wait()
-	thread_pool_info.release()
-
-	# If none failed, start the master
-	failed = [ t.getName() for t in threads if not t.rv ]
-
-	if len(failed) == 0:
-	    if not self.start_segment(master, eid, tbparams, tmpdir):
-		failed.append(master)
-
-	# If one failed clean up
-	if len(failed) > 0:
-	    succeeded = [tb for tb in allocated.keys() if tb not in failed]
-	    if fail_soft:
-		raise service_error(service_error.partial, \
-			"Partial swap in on %s" % ",".join(succeeded))
-	    else:
-		for tb in succeeded:
-		    self.stop_segment(tb, eid, tbparams)
-		raise service_error(service_error.federant,
-		    "Swap in failed on %s" % ",".join(failed))
-	else:
-	    if self.trace_file:
-		print >>self.trace_file, "Experiment started"
-
-	# Generate an ID for the experiment (slice) and a certificate that the
-	# allocator can use to prove they own it.  We'll ship it back through
-	# the encrypted connection.
-	(expid, expcert) = generate_fedid("test", dir=tmpdir, 
-		trace=self.trace_file)
-
-	if self.trace_file:
-	    print >>self.trace_file, "removing %s" % tmpdir
-
-	# Walk up tmpdir, deleting as we go
-	for path, dirs, files in os.walk(tmpdir, topdown=False):
-	    for f in files:
-		os.remove(os.path.join(path, f))
-	    for d in dirs:
-		os.rmdir(os.path.join(path, d))
-	os.rmdir(tmpdir)
-
-	resp = { 'federant' : [ tbparams[tb]['federant'] \
-		for tb in tbparams.keys() \
-		    if tbparams[tb].has_key('federant') ],\
-		    'vtopo': vtopo,\
-		    'vis' : vis,
-		    'experimentID' : [\
-			    { 'fedid': copy.copy(expid) }, \
-			    { 'localname': eid },\
-			],\
-		    'experimentAccess': { 'X509' : expcert },\
-		}
-	
-	self.state[expid] = { 'federant' : [ tbparams[tb]['federant'] \
-		for tb in tbparams.keys() \
-		    if tbparams[tb].has_key('federant') ],\
-		    'vtopo': vtopo,\
-		    'vis' : vis,
-		    'experimentID' : [\
-			    { 'fedid': expid }, { 'localname': eid },\
-			],\
-		}
-	self.state[eid] = self.state[expid]
-	return resp
-
-    def get_vtopo(self, req, fid):
-
-	req = req.get('VtopoRequestBody', None)
-	if not req:
-	    raise service_error(service_error.req,
-		    "Bad request format (no VtopoRequestBody)")
-	exp = req.get('experiment', None)
-	if exp:
-	    if exp.has_key('fedid'):
-		key = fedid(bits=exp['fedid'])
-		keytype = "fedid"
-	    elif exp.has_key('localname'):
-		key = exp['localname']
-		keytype = "localname"
-	    else:
-		raise service_error(service_error.req, "Unknown lookup type")
-	else:
-	    raise service_error(service_error.req, "No request?")
-
-	if self.state.has_key(key):
-	    return { 'experiment' : {keytype: key },\
-		    'vtopo': self.state[key]['vtopo'],\
-		    }
-	else:
-	    raise service_error(service_error.req, "No such experiment")
-
-    def get_vis(self, req, fid):
-
-	req = req.get('VisRequestBody', None)
-	if not req:
-	    raise service_error(service_error.req,
-		    "Bad request format (no VisRequestBody)")
-	exp = req.get('experiment', None)
-	if exp:
-	    if exp.has_key('fedid'):
-		key = fedid(bits=exp['fedid'])
-		keytype = "fedid"
-	    elif exp.has_key('localname'):
-		key = exp['localname']
-		keytype = "localname"
-	    else:
-		raise service_error(service_error.req, "Unknown lookup type")
-	else:
-	    raise service_error(service_error.req, "No request?")
-
-	if self.state.has_key(key):
-	    return { 'experiment' : {keytype: key },\
-		    'vis': self.state[key]['vis'],\
-		    }
-	else:
-	    raise service_error(service_error.req, "No such experiment")
-
-    def get_info(self, req, fid):
-
-	req = req.get('InfoRequestBody', None)
-	if not req:
-	    raise service_error(service_error.req,
-		    "Bad request format (no VisRequestBody)")
-	exp = req.get('experiment', None)
-	if exp:
-	    if exp.has_key('fedid'):
-		key = fedid(bits=exp['fedid'])
-		keytype = "fedid"
-	    elif exp.has_key('localname'):
-		key = exp['localname']
-		keytype = "localname"
-	    else:
-		raise service_error(service_error.req, "Unknown lookup type")
-	else:
-	    raise service_error(service_error.req, "No request?")
-
-	# The state may be massaged by the service function that called
-	# get_info (e.g., encoded for XMLRPC transport) so send a copy of the
-	# state.
-	if self.state.has_key(key):
-	    return copy.deepcopy(self.state[key])
-	else:
-	    raise service_error(service_error.req, "No such experiment")
-
-
-
-    def terminate_experiment(self, req, fid):
-	tbparams = { }
-	req = req.get('TerminateRequestBody', None)
-	if not req:
-	    raise service_error(service_error.req,
-		    "Bad request format (no TerminateRequestBody)")
-	exp = req.get('experiment', None)
-	if exp:
-	    if exp.has_key('fedid'):
-		key = fedid(bits=exp['fedid'])
-		keytype = "fedid"
-	    elif exp.has_key('localname'):
-		key = exp['localname']
-		keytype = "localname"
-	    else:
-		raise service_error(service_error.req, "Unknown lookup type")
-	else:
-	    raise service_error(service_error.req, "No request?")
-
-	fed_exp = self.state.get(key, None)
-
-	if fed_exp:
-	    # Construct enough of the tbparams to make the stop_segment calls
-	    # work
-	    for fed in fed_exp['federant']:
-		try:
-		    for e in fed['name']:
-			eid = e.get('localname', None)
-			if eid: break
-		    else:
-			continue
-
-		    p = fed['emulab']['project']
-
-		    project = p['name']['localname']
-		    tb = p['testbed']['localname']
-		    user = p['user'][0]['userID']['localname']
-
-		    domain = fed['emulab']['domain']
-		    host  = "%s%s" % (fed['emulab']['ops'], domain)
-		except KeyError, e:
-		    continue
-		tbparams[tb] = {\
-			'user': user,\
-			'domain': domain,\
-			'project': project,\
-			'host': host,\
-			'eid': eid,\
-		    }
-	    # Stop everyone.
-	    for tb in tbparams.keys():
-		self.stop_segment(tb, tbparams[tb]['eid'], tbparams)
-	    return { 'experiment': exp }
-	else:
-	    raise service_error(service_error.req, "No saved state")
-
-
-
-
-if __name__ == '__main__':
-    from optparse import OptionParser
-    
-    parser = OptionParser()
-    parser.add_option('-d', '--debug', dest='debug', default=False,
-	    action='store_true', help='print actions rather than take them')
-    parser.add_option('-f', '--file', dest='tcl', help='tcl file to parse')
-    parser.add_option('-m', '--master', dest='master', 
-	    help='testbed label for matster testbd')
-    parser.add_option('-t', '--trace', dest='trace', default=None, 
-	    help='file to print intermediate messages to')
-    parser.add_option('-T', '--trace-stderr', dest='trace', 
-	    action='store_const',const=sys.stderr,
-	    help='file to print intermediate messages to')
-    opts, args  = parser.parse_args()
-
-    trace_file = None
-    if opts.trace:
-	try:
-	    trace_file = open(opts.trace, 'w')
-	except IOError:
-	    print >>sys.stderr, "Can't open trace file"
-
-    if opts.debug:
-	if not trace_file:
-	    trace_file = sys.stderr
-
-    if opts.tcl != None:
-	try:
-	    f = open(opts.tcl, 'r')
-	    content = ''.join(f)
-	    f.close()
-	except IOError, e:
-	    sys.exit("Can't read %s: %s" % (opts.tcl, e))
-    else:
-	sys.exit("Must specify a file name")
-
-    if not opts.master:
-	sys.exit("Must supply master tb label (--master)");
-
-    obj = fedd_create_experiment_local(
-	    debug=opts.debug,
-	    scripts_dir="/users/faber/testbed/federation",
-	    cert_file="./fedd_client.pem", cert_pwd="faber", 
-	    ssh_pubkey_file='/users/faber/.ssh/id_rsa.pub',
-	    trusted_certs="./cacert.pem",
-	    tbmap = { 
-		'deter':'https://users.isi.deterlab.net:23235',
-		'emulab':'https://users.isi.deterlab.net:23236',
-		'ucb':'https://users.isi.deterlab.net:23237',
-		},
-	    trace_file=trace_file
-	) 
-    rv = obj.create_experiment( {\
-	    'experimentdescription' : content, 
-	    'master' : opts.master, 
-	    'user': [ {'userID' : { 'localname' : 'faber' } } ],
-	    },
-	    None)
-
-    print rv
Index: fedd/fedd_deter_impl.py
===================================================================
--- fedd/fedd_deter_impl.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
+++ fedd/fedd_deter_impl.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -0,0 +1,47 @@
+#!/usr/local/bin/python
+
+from fedd_access import *
+from fedd_experiment_control import *
+from fedd_config_file import *
+
+class fedd_deter_impl:
+    """
+    The implementation of access control based on mapping users to projects.
+
+    Users can be mapped to existing projects or have projects created
+    dynamically.  This implements both direct requests and proxies.
+    """
+    # Used by the SOAP caller
+    soap_namespaces = ('http://www.isi.edu/faber/fedd.wsdl',
+	    'http://www.isi.edu/faber/fedd_internal.wsdl')
+
+    def __init__(self, config_path=None):
+	"""
+	Initializer.  Parses a configuration if one is given.
+	"""
+	if config_path:
+	    self.soap_methods = { }
+	    self.xmlrpc_methods = { }
+	    config = config_file(config_path)
+
+	    self.cert_file = config.cert_file;
+	    self.cert_pwd = config.cert_pwd;
+	    self.trusted_certs = config.trusted_certs;
+
+	    self.access = fedd_access(config)
+	    self.experiment = fedd_experiment_control_local(config)
+
+	    self.soap_methods.update(self.access.get_soap_services()) 
+	    self.soap_methods.update(self.experiment.get_soap_services()) 
+
+	    self.xmlrpc_methods.update(self.access.get_xmlrpc_services()) 
+	    self.xmlrpc_methods.update(self.experiment.get_xmlrpc_services()) 
+
+    def get_soap_services(self):
+	return self.soap_methods
+
+    def get_xmlrpc_services(self):
+	return self.xmlrpc_methods
+
+def new_feddservice(configfile):
+    return fedd_deter_impl(configfile)
Index: fedd/fedd_experiment_control.py
===================================================================
--- fedd/fedd_experiment_control.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
+++ fedd/fedd_experiment_control.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -0,0 +1,1585 @@
+#!/usr/local/bin/python
+
+import os,sys
+
+from ZSI import *
+from M2Crypto import SSL
+from M2Crypto.SSL.SSLServer import SSLServer
+import M2Crypto.httpslib
+
+import xml.parsers.expat
+
+import re
+import random
+import string
+import subprocess
+import tempfile
+import copy
+
+import traceback
+
+from threading import *
+
+from subprocess import *
+
+from fedd_services import *
+from fedd_internal_services import *
+from fedd_util import *
+import parse_detail
+from service_error import *
+
+class fedd_experiment_control_local:
+    scripts = ["fed_bootstrap", "federate.sh", "smbmount.FreeBSD.pl",
+	"smbmount.Linux.pl", "make_hosts", "fed-tun.pl", "fed-tun.ucb.pl",
+	"fed_evrepeater", "rc.accounts.patch"]
+    
+    class thread_pool:
+	def __init__(self):
+	    self.changed = Condition()
+	    self.started = 0
+	    self.terminated = 0
+
+	def acquire(self):
+	    self.changed.acquire()
+
+	def release(self):
+	    self.changed.release()
+
+	def wait(self, timeout = None):
+	    self.changed.wait(timeout)
+
+	def start(self):
+	    self.changed.acquire()
+	    self.started += 1
+	    self.changed.notifyAll()
+	    self.changed.release()
+
+	def terminate(self):
+	    self.changed.acquire()
+	    self.terminated += 1
+	    self.changed.notifyAll()
+	    self.changed.release()
+
+	def clear(self):
+	    self.changed.acquire()
+	    self.started = 0
+	    self.terminated =0
+	    self.changed.notifyAll()
+	    self.changed.release()
+
+    class pooled_thread(Thread):
+	def __init__(self, group=None, target=None, name=None, args=(), 
+		kwargs={}, pdata=None, trace_file=None):
+	    Thread.__init__(self, group, target, name, args, kwargs)
+	    self.rv = None
+	    self.exception = None
+	    self.target=target
+	    self.args = args
+	    self.kwargs = kwargs
+	    self.pdata = pdata
+	    self.trace_file = trace_file
+	
+	def run(self):
+	    if self.pdata:
+		self.pdata.start()
+
+	    if self.target:
+		try:
+		    self.rv = self.target(*self.args, **self.kwargs)
+		except service_error, s:
+		    self.exception = s
+		    if self.trace_file:
+			print >>self.trace_file, "Thread exception: %s %s" % \
+				(s.code_string(), s.desc)
+		    
+		except:
+		    self.exception = sys.exc_info()[1]
+		    if self.trace_file:
+			print >>self.trace_file, \
+				"Unexpected thread exception: %s" % \
+				self.exception
+			print >>self.trace_file, "Trace: %s" % \
+				traceback.format_exc()
+	    if self.pdata:
+		self.pdata.terminate()
+
+    def __init__(self, config=None):
+	self.scripts = fedd_experiment_control_local.scripts
+	self.thread_with_rv = fedd_experiment_control_local.pooled_thread
+	self.thread_pool = fedd_experiment_control_local.thread_pool
+
+	self.cert_file = None
+	self.cert_pwd = None
+	self.trusted_certs = None
+
+	if config.create_experiment_cert_file:
+	    self.cert_file = config.create_experiment_cert_file
+	    self.cert_pwd = config.create_experiment_cert_pwd
+	if config.create_experiment_trusted_certs:
+	    self.trusted_certs = config.create_experiment_trusted_certs
+
+	if config.proxy_cert_file:
+	    if not self.cert_file:
+		self.cert_file = config.proxy_cert_file
+		self.cert_pwd = config.proxy_cert_pwd
+	if config.proxy_trusted_certs:
+	    if not self.trusted_certs:
+		self.trusted_certs = config.proxy_trusted_certs
+
+	if config.cert_file:
+	    if not self.cert_file:
+		self.cert_file = config.cert_file
+		self.cert_pwd = config.cert_pwd
+	if config.trusted_certs:
+	    if not self.trusted_certs:
+		self.trusted_certs = config.trusted_certs
+
+	self.exp_stem = "fed-stem"
+	self.debug = config.create_debug
+	self.muxmax = 2
+	self.nthreads = 2
+	self.randomize_experiments = False
+	self.scp_exec = "/usr/bin/scp"
+	self.scripts_dir = "/users/faber/testbed/federation"
+	self.splitter = None
+	self.ssh_exec="/usr/bin/ssh"
+	self.ssh_keygen = "/usr/bin/ssh-keygen"
+	self.ssh_identity_file = None
+	# XXX
+	self.ssh_pubkey_file = "/users/faber/.ssh/id_rsa.pub"
+	self.ssh_type = "rsa"
+	self.state = { }
+	self.tclsh = "/usr/local/bin/otclsh"
+	self.tcl_splitter = "/usr/testbed/lib/ns2ir/parse.tcl"
+	self.tbmap = { 
+		'deter':'https://users.isi.deterlab.net:23235',
+		'emulab':'https://users.isi.deterlab.net:23236',
+		'ucb':'https://users.isi.deterlab.net:23237',
+		}
+	self.trace_file = sys.stderr
+
+	self.def_expstart = \
+		"sudo -H /bin/sh FEDDIR/fed_bootstrap >& /tmp/federate";
+	self.def_mexpstart = "sudo -H FEDDIR/make_hosts FEDDIR/hosts";
+	self.def_gwstart = \
+		"sudo -H FEDDIR/fed-tun.pl -f GWCONF>& /tmp/bridge.log";
+	self.def_mgwstart = \
+		"sudo -H FEDDIR/fed-tun.pl -f GWCONF >& /tmp/bridge.log";
+	self.def_gwimage = "FBSD61-TUNNEL2";
+	self.def_gwtype = "pc";
+
+
+	if self.ssh_pubkey_file:
+	    try:
+		f = open(self.ssh_pubkey_file, 'r')
+		self.ssh_pubkey = f.read()
+		f.close()
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot read sshpubkey")
+
+	# Confirm federation scripts in the right place
+	for s in self.scripts:
+	    if not os.path.exists(self.scripts_dir + "/" + s):
+		raise service_error(service_error.server_config,
+			"%s/%s not in local script dir" % (self.scripts_dir, s))
+
+	self.soap_handlers = {\
+		'Create': make_soap_handler(\
+			CreateRequestMessage.typecode,
+			getattr(self, "create_experiment"), 
+			CreateResponseMessage,
+			"CreateResponseBody"),
+		'Vtopo': make_soap_handler(\
+			VtopoRequestMessage.typecode,
+			getattr(self, "get_vtopo"),
+			VtopoResponseMessage,
+			"VtopoResponseBody"),
+		'Vis': make_soap_handler(\
+			VisRequestMessage.typecode,
+			getattr(self, "get_vis"),
+			VisResponseMessage,
+			"VisResponseBody"),
+		'Info': make_soap_handler(\
+			InfoRequestMessage.typecode,
+			getattr(self, "get_info"),
+			InfoResponseMessage,
+			"InfoResponseBody"),
+		'Terminate': make_soap_handler(\
+			TerminateRequestMessage.typecode,
+			getattr(self, "terminate_experiment"),
+			TerminateResponseMessage,
+			"TerminateResponseBody"),
+	}
+
+	self.xmlrpc_handlers = {\
+		'Create': make_xmlrpc_handler(\
+			getattr(self, "create_experiment"), 
+			"CreateResponseBody"),
+		'Vtopo': make_xmlrpc_handler(\
+			getattr(self, "get_vtopo"),
+			"VtopoResponseBody"),
+		'Vis': make_xmlrpc_handler(\
+			getattr(self, "get_vis"),
+			"VisResponseBody"),
+		'Info': make_xmlrpc_handler(\
+			getattr(self, "get_info"),
+			"InfoResponseBody"),
+		'Terminate': make_xmlrpc_handler(\
+			getattr(self, "terminate_experiment"),
+			"TerminateResponseBody"),
+	}
+
+    def get_soap_services(self):
+	return self.soap_handlers
+
+    def get_xmlrpc_services(self):
+	return self.xmlrpc_handlers
+
+    def copy_file(self, src, dest, size=1024):
+	"""
+	Exceedingly simple file copy.
+	"""
+	s = open(src,'r')
+	d = open(dest, 'w')
+
+	buf = "x"
+	while buf != "":
+	    buf = s.read(size)
+	    d.write(buf)
+	s.close()
+	d.close()
+
+    def scp_file(self, file, user, host, dest=""):
+	"""
+	scp a file to the remote host.
+	"""
+
+	scp_cmd = [self.scp_exec, file, "%s@%s:%s" % (user, host, dest)]
+
+	trace = self.trace_file
+	if not trace:
+	    try:
+		trace = open("/dev/null", "w")
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot open /dev/null??");
+
+	if not self.debug:
+	    rv = call(scp_cmd, stdout=trace, stderr=trace)
+	else:
+	    if self.trace_file: 
+		print >>self.trace_file, "debug [scp_file]: %s" % \
+			" ".join(scp_cmd)
+	    rv = 0
+
+	return rv == 0
+
+    def ssh_cmd(self, user, host, cmd, wname=None):
+	sh_str = "%s %s@%s %s" % (self.ssh_exec, user, host, cmd)
+
+	trace = self.trace_file
+	if not trace:
+	    try:
+		trace = open("/dev/null", "w")
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot open /dev/null??");
+
+	if not self.debug:
+	    sub = Popen(sh_str, shell=True, stdout=trace, stderr=trace)
+	    return sub.wait() == 0
+	else:
+	    if self.trace_file:
+		print >>self.trace_file,"debug [ssh_cmd]: %s" % sh_str 
+	    return True
+
+    def ship_scripts(self, host, user, dest_dir):
+	if self.ssh_cmd(user, host, "mkdir -p %s" % dest_dir):
+	    for s in self.scripts:
+		if not self.scp_file("%s/%s" % (self.scripts_dir, s),
+			user, host, dest_dir):
+		    return False
+	    return True
+	else:
+	    return False
+
+    def ship_configs(self, host, user, src_dir, dest_dir):
+	if not self.ssh_cmd(user, host, "mkdir -p %s" % dest_dir):
+	    return False
+	if not self.ssh_cmd(user, host, "chmod 770 %s" % dest_dir):
+	    return False
+
+	for f in os.listdir(src_dir):
+	    if os.path.isdir(f):
+		if not self.ship_configs(host, user, "%s/%s" % (src_dir, f), 
+			"%s/%s" % (dest_dir, f)):
+		    return False
+	    else:
+		if not self.scp_file("%s/%s" % (src_dir, f), 
+			user, host, dest_dir):
+		    return False
+	return True
+
+    def start_segment(self, tb, eid, tbparams, tmpdir, timeout=0):
+	host = "%s%s" % (tbparams[tb]['host'], tbparams[tb]['domain'])
+	user = tbparams[tb]['user']
+	pid = tbparams[tb]['project']
+	# XXX
+	base_confs = ( "hosts",)
+	tclfile = "%s.%s.tcl" % (eid, tb)
+	expinfo_exec = "/usr/testbed/bin/expinfo"
+	proj_dir = "/proj/%s/exp/%s/tmp" % (pid, eid)
+	tarfiles_dir = "/proj/%s/tarfiles/%s" % (pid, eid)
+	rpms_dir = "/proj/%s/rpms/%s" % (pid, eid)
+	state_re = re.compile("State:\s+(\w+)")
+	no_exp_re = re.compile("^No\s+such\s+experiment")
+	state = None
+	cmd = [self.ssh_exec, "%s@%s" % (user, host), expinfo_exec, pid, eid]
+
+
+	if self.trace_file:
+	    print >>self.trace_file, "status request: %s" % " ".join(cmd)
+	
+	if not self.trace_file:
+	    try:
+		st_file = open("/dev/null", "w")
+	    except IOError:
+		raise service_error(service_error.internal, 
+			"Cannot open /dev/null!?")
+	else:
+	    st_file = self.trace_file
+
+	status = Popen(cmd, stdout=PIPE, stderr=st_file)
+	for line in status.stdout:
+	    m = state_re.match(line)
+	    if m: state = m.group(1)
+	    else:
+		m = no_exp_re.match(line)
+		if m: state = "none"
+	rv = status.wait()
+	# If the experiment is not present the subcommand returns a non-zero
+	# return value.  If we successfully parsed a "none" outcome, ignore the
+	# return code.
+	if rv != 0 and state != "none":
+	    raise service_error(service_error.internal,
+		    "Cannot get status of segment %s:%s/%s" % (tb, pid, eid))
+	if self.trace_file:
+	    print >>self.trace_file, "%s: %s" % (tb, state)
+	    print >>self.trace_file, "transferring experiment to %s" % tb
+
+	if not self.scp_file("%s/%s/%s" % (tmpdir, tb, tclfile), user, host):
+	    return False
+	# Clear the federation files
+	if not self.ssh_cmd(user, host, 
+		"/bin/sh -c \"'/bin/rm -rf %s'\"" % proj_dir):
+	    return False
+	if not self.ssh_cmd(user, host, 
+		"/bin/sh -c \"'mkdir -p %s'\"" % proj_dir):
+	    return False
+	# Clear and create the tarfiles and rpm directories
+	for d in (tarfiles_dir, rpms_dir):
+	    if not self.ssh_cmd(user, host, 
+		    "/bin/sh -c \"'/bin/rm -rf %s/*'\"" % d):
+		return False
+	    if not self.ssh_cmd(user, host, "mkdir -p %s" % d, 
+		    "create tarfiles"):
+		return False
+	
+	if state == 'active':
+	    # Remote experiment is active.  Modify it.
+	    for f in base_confs:
+		if not self.scp_file("%s/%s" % (tmpdir, f), user, host,
+			"%s/%s" % (proj_dir, f)):
+		    return False
+	    if not self.ship_scripts(host, user, proj_dir):
+		return False
+	    if not self.ship_configs(host, user, "%s/%s" % (tmpdir, tb),
+		    proj_dir):
+		return False
+	    if os.path.isdir("%s/tarfiles" % tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/tarfiles" % tmpdir, tarfiles_dir):
+		    return False
+	    if os.path.isdir("%s/rpms" % tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/rpms" % tmpdir, tarfiles_dir):
+		    return False
+	    if self.trace_file:
+		print >>self.trace_file, "Modifying %s on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/modexp -r -s -w %s %s %s" % \
+			    (pid, eid, tclfile), "modexp"):
+		return False
+	    return True
+	elif state == "swapped":
+	    # Remote experiment swapped out.  Modify it and swap it in.
+	    for f in base_confs:
+		if not self.scp_file("%s/%s" % (tmpdir, f), user, host,
+			"%s/%s" % (proj_dir, f)):
+		    return False
+	    if not self.ship_scripts(host, user, proj_dir):
+		return False
+	    if not self.ship_configs(host, user, "%s/%s" % (tmpdir, tb),
+		    proj_dir):
+		return False
+	    if os.path.isdir("%s/tarfiles" % tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/tarfiles" % tmpdir, tarfiles_dir):
+		    return False
+	    if os.path.isdir("%s/rpms" % tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/rpms" % tmpdir, tarfiles_dir):
+		    return False
+	    if self.trace_file:
+		print >>self.trace_file, "Modifying %s on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/modexp -w %s %s %s" % (pid, eid, tclfile),
+		    "modexp"):
+		return False
+	    if self.trace_file:
+		print >>self.trace_file, "Swapping %s in on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/swapexp -w %s %s in" % (pid, eid),
+		    "swapexp"):
+		return False
+	    return True
+	elif state == "none":
+	    # No remote experiment.  Create one.  We do this in 2 steps so we
+	    # can put the configuration files and scripts into the new
+	    # experiment directories.
+
+	    # Tarfiles must be present for creation to work
+	    if os.path.isdir("%s/tarfiles" % tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/tarfiles" % tmpdir, tarfiles_dir):
+		    return False
+	    if os.path.isdir("%s/rpms" % tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/rpms" % tmpdir, tarfiles_dir):
+		    return False
+	    if self.trace_file:
+		print >>self.trace_file, "Creating %s on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/startexp -i -f -w -p %s -e %s %s" % \
+			    (pid, eid, tclfile), "startexp"):
+		return False
+	    # After startexp the per-experiment directories exist
+	    for f in base_confs:
+		if not self.scp_file("%s/%s" % (tmpdir, f), user, host,
+			"%s/%s" % (proj_dir, f)):
+		    return False
+	    if not self.ship_scripts(host, user, proj_dir):
+		return False
+	    if not self.ship_configs(host, user, "%s/%s" % (tmpdir, tb),
+		    proj_dir):
+		return False
+	    if self.trace_file:
+		print >>self.trace_file, "Swapping %s in on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/swapexp -w %s %s in" % (pid, eid),
+		    "swapexp"):
+		return False
+	    return True
+	else:
+	    if self.trace_file:
+		print >>self.trace_file, "unknown state %s" % state
+	    return False
+
+    def stop_segment(self, tb, eid, tbparams):
+	user = tbparams[tb]['user']
+	host = "%s%s" % (tbparams[tb]['host'], tbparams[tb]['domain'])
+	pid = tbparams[tb]['project']
+
+	if self.trace_file:
+	    print >>self.trace_file, "Stopping %s on %s" % (eid, tb)
+	return self.ssh_cmd(user, host,
+		"/usr/testbed/bin/swapexp -w %s %s out" % (pid, eid))
+
+	
+    def generate_ssh_keys(self, dest, type="rsa" ):
+	"""
+	Generate a set of keys for the gateways to use to talk.
+
+	Keys are of type type and are stored in the required dest file.
+	"""
+	valid_types = ("rsa", "dsa")
+	t = type.lower();
+	if t not in valid_types: raise ValueError
+
+	trace = self.trace_file
+	if not trace:
+	    try:
+		trace = open("/dev/null", "w")
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot open /dev/null??");
+
+	# May raise CalledProcessError
+	rv = call([self.ssh_keygen, '-t', t, '-N', '', '-f', dest],
+		stdout=trace, stderr=trace)
+	if rv != 0:
+	    raise service_error(service_error.internal, 
+		    "Cannot generate nonce ssh keys.  %s return code %d" \
+			    % (self.ssh_keygen, rv))
+
+    def gentopo(self, str):
+	class topo_parse:
+	    def __init__(self):
+		self.str_subelements = ('vname', 'vnode', 'ips', 'ip', 'member')
+		self.int_subelements = ( 'bandwidth',)
+		self.float_subelements = ( 'delay',)
+		self.nodes = [ ]
+		self.lans =  [ ]
+		self.element = { }
+		self.topo = { \
+			'node': self.nodes,\
+			'lan' : self.lans,\
+		    }
+		self.chars = ""
+
+	    def end_element(self, name):
+		if name == 'node':
+		    self.nodes.append(self.element)
+		    self.element = { }
+		elif name == 'lan':
+		    self.lans.append(self.element)
+		    self.element = { }
+		elif name in self.str_subelements:
+		    self.element[name] = self.chars
+		    self.chars = ""
+		elif name in self.int_subelements:
+		    self.element[name] = int(self.chars)
+		    self.chars = ""
+		elif name in self.float_subelements:
+		    self.element[name] = float(self.chars)
+		    self.chars = ""
+
+	    def found_chars(self, data):
+		self.chars += data.rstrip()
+
+
+	tp = topo_parse();
+	parser = xml.parsers.expat.ParserCreate()
+	parser.EndElementHandler = tp.end_element
+	parser.CharacterDataHandler = tp.found_chars
+
+	parser.Parse(str)
+
+	return tp.topo
+	
+
+    def genviz(self, topo):
+	"""
+	Generate the visualization the virtual topology
+	"""
+
+	neato = "/usr/local/bin/neato"
+	# These are used to parse neato output and to create the visualization
+	# file.
+	vis_re = re.compile('^\s*"?([\w\-]+)"?\s+\[.*pos="(\d+),(\d+)"')
+	vis_fmt = "<node><name>%s</name><x>%s</x><y>%s</y><type>" + \
+		"%s</type></node>"
+
+	try:
+	    # Node names
+	    nodes = [ n['vname'] for n in topo['node'] ]
+	    topo_lans = topo['lan']
+	except KeyError:
+	    raise service_error(service_error.internal, "Bad topology")
+
+	lans = { }
+	links = { }
+
+	# Walk through the virtual topology, organizing the connections into
+	# 2-node connections (links) and more-than-2-node connections (lans).
+	# When a lan is created, it's added to the list of nodes (there's a
+	# node in the visualization for the lan).
+	for l in topo_lans:
+	    if links.has_key(l['vname']):
+		if len(links[l['vname']]) < 2:
+		    links[l['vname']].append(l['vnode'])
+		else:
+		    nodes.append(l['vname'])
+		    lans[l['vname']] = links[l['vname']]
+		    del links[l['vname']]
+		    lans[l['vname']].append(l['vnode'])
+	    elif lans.has_key(l['vname']):
+		lans[l['vname']].append(l['vnode'])
+	    else:
+		links[l['vname']] = [ l['vnode'] ]
+
+
+	# Open up a temporary file for dot to turn into a visualization
+	try:
+	    df, dotname = tempfile.mkstemp()
+	    dotfile = os.fdopen(df, 'w')
+	except IOError:
+	    raise service_error(service_error.internal,
+		    "Failed to open file in genviz")
+
+	# Generate a dot/neato input file from the links, nodes and lans
+	try:
+	    print >>dotfile, "graph G {"
+	    for n in nodes:
+		print >>dotfile, '\t"%s"' % n
+	    for l in links.keys():
+		print >>dotfile, '\t"%s" -- "%s"' %  tuple(links[l])
+	    for l in lans.keys():
+		for n in lans[l]:
+		    print >>dotfile, '\t "%s" -- "%s"' % (n,l)
+	    print >>dotfile, "}"
+	    dotfile.close()
+	except TypeError:
+	    raise service_error(service_error.internal,
+		    "Single endpoint link in vtopo")
+	except IOError:
+	    raise service_error(service_error.internal, "Cannot write dot file")
+
+	# Use dot to create a visualization
+	dot = Popen([neato, '-Gstart=rand', '-Gepsilon=0.005', '-Gmaxiter=2000',
+		'-Gpack=true', dotname], stdout=PIPE)
+
+	# Translate dot to vis format
+	vis_nodes = [ ]
+	vis = { 'node': vis_nodes }
+	for line in dot.stdout:
+	    m = vis_re.match(line)
+	    if m:
+		vn = m.group(1)
+		vis_node = {'name': vn, \
+			'x': float(m.group(2)),\
+			'y' : float(m.group(3)),\
+		    }
+		if vn in links.keys() or vn in lans.keys():
+		    vis_node['type'] = 'lan'
+		else:
+		    vis_node['type'] = 'node'
+		vis_nodes.append(vis_node)
+	rv = dot.wait()
+
+	os.remove(dotname)
+	if rv == 0 : return vis
+	else: return None
+
+
+    def get_access(self, tb, nodes, user, tbparam):
+	"""
+	Get access to testbed through fedd and set the parameters for that tb
+	"""
+
+	translate_attr = {
+	    'slavenodestartcmd': 'expstart',
+	    'slaveconnectorstartcmd': 'gwstart',
+	    'masternodestartcmd': 'mexpstart',
+	    'masterconnectorstartcmd': 'mgwstart',
+	    'connectorimage': 'gwimage',
+	    'connectortype': 'gwtype',
+	    'tunnelcfg': 'tun',
+	    'smbshare': 'smbshare',
+	}
+
+	# XXX multi-level access
+	uri = self.tbmap.get(tb, None)
+	if not uri:
+	    raise service_error(serice_error.server_config, 
+		    "Unknown testbed: %s" % tb)
+
+	# The basic request
+	req = {\
+		'destinationTestbed' : { 'uri' : uri },
+		'user':  user,
+		'allocID' : { 'localname': 'test' },
+		'access' : [ { 'sshPubkey' : self.ssh_pubkey } ]
+	    }
+	
+	# node resources if any
+	if nodes != None and len(nodes) > 0:
+	    rnodes = [ ]
+	    for n in nodes:
+		rn = { }
+		image, hw, count = n.split(":")
+		if image: rn['image'] = [ image ]
+		if hw: rn['hardware'] = [ hw ]
+		if count: rn['count'] = int(count)
+		rnodes.append(rn)
+	    req['resources']= { }
+	    req['resources']['node'] = rnodes
+
+	# No retry loop here.  Proxy servers must correctly authenticate
+	# themselves without help
+
+	try:
+	    ctx = fedd_ssl_context(self.cert_file, 
+		    self.trusted_certs, password=self.cert_pwd)
+	except SSL.SSLError:
+	    raise service_error(service_error.server_config, 
+		    "Server certificates misconfigured")
+
+	loc = feddServiceLocator();
+	port = loc.getfeddPortType(uri,
+		transport=M2Crypto.httpslib.HTTPSConnection, 
+		transdict={ 'ssl_context' : ctx })
+
+	# Reconstruct the full request message
+	msg = RequestAccessRequestMessage()
+	msg.set_element_RequestAccessRequestBody(
+		pack_soap(msg, "RequestAccessRequestBody", req))
+
+	try:
+	    resp = port.RequestAccess(msg)
+	except ZSI.ParseException, e:
+	    raise service_error(service_error.req,
+		    "Bad format message (XMLRPC??): %s" %
+		    str(e))
+	r = unpack_soap(resp)
+
+	if r.has_key('RequestAccessResponseBody'):
+	    r = r['RequestAccessResponseBody']
+	else:
+	    raise service_error(service_error.proxy,
+		    "Bad proxy response")
+
+
+	e = r['emulab']
+	p = e['project']
+	tbparam[tb] = { 
+		"boss": e['boss'],
+		"host": e['ops'],
+		"domain": e['domain'],
+		"fs": e['fileServer'],
+		"eventserver": e['eventServer'],
+		"project": unpack_id(p['name']),
+		"emulab" : e
+		}
+	# Make the testbed name be the label the user applied
+	p['testbed'] = {'localname': tb }
+
+	for u in p['user']:
+	    tbparam[tb]['user'] = unpack_id(u['userID'])
+
+	for a in e['fedAttr']:
+	    if a['attribute']:
+		key = translate_attr.get(a['attribute'].lower(), None)
+		if key:
+		    tbparam[tb][key]= a['value']
+	
+    class current_testbed:
+	def __init__(self, eid, tmpdir):
+	    self.begin_testbed = re.compile("^#\s+Begin\s+Testbed\s+\((\w+)\)")
+	    self.end_testbed = re.compile("^#\s+End\s+Testbed\s+\((\w+)\)")
+	    self.current_testbed = None
+	    self.testbed_file = None
+
+	    self.def_expstart = \
+		    "sudo -H /bin/sh FEDDIR/fed_bootstrap >& /tmp/federate";
+	    self.def_mexpstart = "sudo -H FEDDIR/make_hosts FEDDIR/hosts";
+	    self.def_gwstart = \
+		    "sudo -H FEDDIR/fed-tun.pl -f GWCONF>& /tmp/bridge.log";
+	    self.def_mgwstart = \
+		    "sudo -H FEDDIR/fed-tun.pl -f GWCONF >& /tmp/bridge.log";
+	    self.def_gwimage = "FBSD61-TUNNEL2";
+	    self.def_gwtype = "pc";
+
+	    self.eid = eid
+	    self.tmpdir = tmpdir
+
+	def __call__(self, line, master, allocated, tbparams):
+	    # Capture testbed topology descriptions
+	    if self.current_testbed == None:
+		m = self.begin_testbed.match(line)
+		if m != None:
+		    self.current_testbed = m.group(1)
+		    if self.current_testbed == None:
+			raise service_error(service_error.req,
+				"Bad request format (unnamed testbed)")
+		    allocated[self.current_testbed] = \
+			    allocated.get(self.current_testbed,0) + 1
+		    tb_dir = "%s/%s" % (self.tmpdir, self.current_testbed)
+		    if not os.path.exists(tb_dir):
+			try:
+			    os.mkdir(tb_dir)
+			except IOError:
+			    raise service_error(service_error.internal,
+				    "Cannot create %s" % tb_dir)
+		    try:
+			self.testbed_file = open("%s/%s.%s.tcl" %
+				(tb_dir, self.eid, self.current_testbed), 'w')
+		    except IOError:
+			self.testbed_file = None
+		    return True
+		else: return False
+	    else:
+		m = self.end_testbed.match(line)
+		if m != None:
+		    if m.group(1) != self.current_testbed:
+			raise service_error(service_error.internal, 
+				"Mismatched testbed markers!?")
+		    if self.testbed_file != None: 
+			self.testbed_file.close()
+			self.testbed_file = None
+		    self.current_testbed = None
+		elif self.testbed_file:
+		    # Substitute variables and put the line into the local
+		    # testbed file.
+		    gwtype = tbparams[self.current_testbed].get('gwtype', 
+			    self.def_gwtype)
+		    gwimage = tbparams[self.current_testbed].get('gwimage', 
+			    self.def_gwimage)
+		    mgwstart = tbparams[self.current_testbed].get('mgwstart', 
+			    self.def_mgwstart)
+		    mexpstart = tbparams[self.current_testbed].get('mexpstart', 
+			    self.def_mexpstart)
+		    gwstart = tbparams[self.current_testbed].get('gwstart', 
+			    self.def_gwstart)
+		    expstart = tbparams[self.current_testbed].get('expstart', 
+			    self.def_expstart)
+		    project = tbparams[self.current_testbed].get('project')
+		    line = re.sub("GWTYPE", gwtype, line)
+		    line = re.sub("GWIMAGE", gwimage, line)
+		    if self.current_testbed == master:
+			line = re.sub("GWSTART", mgwstart, line)
+			line = re.sub("EXPSTART", mexpstart, line)
+		    else:
+			line = re.sub("GWSTART", gwstart, line)
+			line = re.sub("EXPSTART", expstart, line)
+		    # XXX: does `` embed without doing enything else?
+		    line = re.sub("GWCONF", "FEDDIR`hostname`.gw.conf", line)
+		    line = re.sub("PROJDIR", "/proj/%s/" % project, line)
+		    line = re.sub("EID", self.eid, line)
+		    line = re.sub("FEDDIR", "/proj/%s/exp/%s/tmp/" % \
+			    (project, self.eid), line)
+		    print >>self.testbed_file, line
+		return True
+
+    class allbeds:
+	def __init__(self, get_access):
+	    self.begin_allbeds = re.compile("^#\s+Begin\s+Allbeds")
+	    self.end_allbeds = re.compile("^#\s+End\s+Allbeds")
+	    self.in_allbeds = False
+	    self.get_access = get_access
+
+	def __call__(self, line, user, tbparams):
+	    # Testbed access parameters
+	    if not self.in_allbeds:
+		if self.begin_allbeds.match(line):
+		    self.in_allbeds = True
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end_allbeds.match(line):
+		    self.in_allbeds = False
+		else:
+		    nodes = line.split('|')
+		    tb = nodes.pop(0)
+		    self.get_access(tb, nodes, user, tbparams)
+		return True
+
+    class gateways:
+	def __init__(self, eid, master, tmpdir, gw_pubkey,
+		gw_secretkey, copy_file):
+	    self.begin_gateways = \
+		    re.compile("^#\s+Begin\s+gateways\s+\((\w+)\)")
+	    self.end_gateways = re.compile("^#\s+End\s+gateways\s+\((\w+)\)")
+	    self.current_gateways = None
+	    self.control_gateway = None
+	    self.active_end = { }
+
+	    self.eid = eid
+	    self.master = master
+	    self.tmpdir = tmpdir
+	    self.gw_pubkey_base = gw_pubkey
+	    self.gw_secretkey_base = gw_secretkey
+
+	    self.copy_file = copy_file
+
+
+	def gateway_conf_file(self, gw, master, eid, pubkey, privkey,
+		active_end, tbparams, dtb, myname, desthost, type):
+	    """
+	    Produce a gateway configuration file from a gateways line. 
+	    """
+
+	    sproject = tbparams[gw].get('project', 'project')
+	    dproject = tbparams[dtb].get('project', 'project')
+	    sdomain = ".%s.%s%s" % (eid, sproject,
+		    tbparams[gw].get('domain', ".example.com"))
+	    ddomain = ".%s.%s%s" % (eid, dproject,
+		    tbparams[dtb].get('domain', ".example.com"))
+	    boss = tbparams[master].get('boss', "boss")
+	    fs = tbparams[master].get('fs', "fs")
+	    event_server = "%s%s" % \
+		    (tbparams[gw].get('eventserver', "event_server"),
+			    tbparams[gw].get('domain', "example.com"))
+	    remote_event_server = "%s%s" % \
+		    (tbparams[dtb].get('eventserver', "event_server"),
+			    tbparams[dtb].get('domain', "example.com"))
+	    seer_control = "%s%s" % \
+		    (tbparams[gw].get('control', "control"), sdomain)
+	    remote_script_dir = "/proj/%s/exp/%s/tmp" % ( dproject, eid)
+	    local_script_dir = "/proj/%s/exp/%s/tmp" % ( sproject, eid)
+	    tunnel_cfg = tbparams[gw].get("tun", "false")
+
+	    conf_file = "%s%s.gw.conf" % (myname, sdomain)
+	    remote_conf_file = "%s%s.gw.conf" % (desthost, ddomain)
+
+	    # translate to lower case so the `hostname` hack for specifying
+	    # configuration files works.
+	    conf_file = conf_file.lower();
+	    remote_conf_file = remote_conf_file.lower();
+
+	    if dtb == master:
+		active = "false"
+	    elif gw == master:
+		active = "true"
+	    elif active_end.has_key['%s-%s' % (dtb, gw)]:
+		active = "false"
+	    else:
+		active_end['%s-%s' % (gw, dtb)] = 1
+		active = "true"
+
+	    gwconfig = open("%s/%s/%s" % (self.tmpdir, gw, conf_file), "w")
+	    print >>gwconfig, "Active: %s" % active
+	    print >>gwconfig, "TunnelCfg: %s" % tunnel_cfg
+	    print >>gwconfig, "BossName: %s" % boss
+	    print >>gwconfig, "FsName: %s" % fs
+	    print >>gwconfig, "EventServerName: %s" % event_server
+	    print >>gwconfig, "RemoteEventServerName: %s" % remote_event_server
+	    print >>gwconfig, "SeerControl: %s" % seer_control
+	    print >>gwconfig, "Type: %s" % type
+	    print >>gwconfig, "RemoteScriptDir: %s" % remote_script_dir
+	    print >>gwconfig, "EventRepeater: %s/fed_evrepeater" % \
+		    local_script_dir
+	    print >>gwconfig, "RemoteExperiment: %s/%s" % (dproject, eid)
+	    print >>gwconfig, "LocalExperiment: %s/%s" % (sproject, eid)
+	    print >>gwconfig, "RemoteConfigFile: %s/%s" % \
+		    (remote_script_dir, remote_conf_file)
+	    print >>gwconfig, "Peer: %s%s" % (desthost, ddomain)
+	    print >>gwconfig, "Pubkeys: %s/%s" % (local_script_dir, pubkey)
+	    print >>gwconfig, "Privkeys: %s/%s" % (local_script_dir, privkey)
+	    gwconfig.close()
+
+	    return active == "true"
+
+	def __call__(self, line, allocated, tbparams):
+	    # Process gateways
+	    if not self.current_gateways:
+		m = self.begin_gateways.match(line)
+		if m:
+		    self.current_gateways = m.group(1)
+		    if allocated.has_key(self.current_gateways):
+			# This test should always succeed
+			tb_dir = "%s/%s" % (self.tmpdir, self.current_gateways)
+			if not os.path.exists(tb_dir):
+			    try:
+				os.mkdir(tb_dir)
+			    except IOError:
+				raise service_error(service_error.internal,
+					"Cannot create %s" % tb_dir)
+		    else:
+			# XXX
+			print >>sys.stderr, \
+			    "Ignoring gateways for unknown testbed %s" \
+				    % self.current_gateways
+			self.current_gateways = None
+		    return True
+		else:
+		    return False
+	    else:
+		m = self.end_gateways.match(line)
+		if m :
+		    if m.group(1) != self.current_gateways:
+			raise service_error(service_error.internal,
+				"Mismatched gateway markers!?")
+		    if self.control_gateway:
+			try:
+			    cc = open("%s/%s/client.conf" %
+				    (self.tmpdir, self.current_gateways), 'w')
+			    print >>cc, "ControlGateway: %s" % \
+				    self.control_gateway
+			    if tbparams[self.master].has_key('smbshare'):
+				print >>cc, "SMBSHare: %s" % \
+					tbparams[self.master]['smbshare']
+			    print >>cc, "ProjectUser: %s" % \
+				    tbparams[self.master]['user']
+			    print >>cc, "ProjectName: %s" % \
+				    tbparams[self.master]['project']
+			    cc.close()
+			except IOError:
+			    raise service_error(service_error.internal,
+				    "Error creating client config")
+			try:
+			    cc = open("%s/%s/seer.conf" %
+				    (self.tmpdir, self.current_gateways),
+				    'w')
+			    if self.current_gateways != self.master:
+				print >>cc, "ControlNode: %s" % \
+					self.control_gateway
+			    print >>cc, "ExperimentID: %s/%s" % \
+				    ( tbparams[self.master]['project'], \
+				    self.eid )
+			    cc.close()
+			except IOError:
+			    raise service_error(service_error.internal,
+				    "Error creating seer config")
+		    else:
+			if self.trace_file:
+			    print >>sys.stderr, "No control gateway for %s" %\
+				    self.current_gateways
+		    self.current_gateways = None
+		else:
+		    dtb, myname, desthost, type = line.split(" ")
+
+		    if type == "control" or type == "both":
+			self.control_gateway = "%s.%s.%s%s" % (myname, 
+				self.eid, 
+				tbparams[self.current_gateways]['project'],
+				tbparams[self.current_gateways]['domain'])
+		    try:
+			active = self.gateway_conf_file(self.current_gateways,
+				self.master, self.eid, self.gw_pubkey_base,
+				self.gw_secretkey_base,
+				self.active_end, tbparams, dtb, myname,
+				desthost, type)
+		    except IOError, e:
+			raise service_error(service_error.internal,
+				"Failed to write config file for %s" % \
+					self.current_gateway)
+	    
+		    gw_pubkey = "%s/keys/%s" % \
+			    (self.tmpdir, self.gw_pubkey_base)
+		    gw_secretkey = "%s/keys/%s" % \
+			    (self.tmpdir, self.gw_secretkey_base)
+
+		    pkfile = "%s/%s/%s" % \
+			    ( self.tmpdir, self.current_gateways, 
+				    self.gw_pubkey_base)
+		    skfile = "%s/%s/%s" % \
+			    ( self.tmpdir, self.current_gateways, 
+				    self.gw_secretkey_base)
+
+		    if not os.path.exists(pkfile):
+			try:
+			    self.copy_file(gw_pubkey, pkfile)
+			except IOError:
+			    service_error(service_error.internal,
+				    "Failed to copy pubkey file")
+
+		    if active and not os.path.exists(skfile):
+			try:
+			    self.copy_file(gw_secretkey, skfile)
+			except IOError:
+			    service_error(service_error.internal,
+				    "Failed to copy secretkey file")
+		return True
+
+    class shunt_to_file:
+	def __init__(self, begin, end, filename):
+	    self.begin = re.compile(begin)
+	    self.end = re.compile(end)
+	    self.in_shunt = False
+	    self.file = None
+	    self.filename = filename
+
+	def __call__(self, line):
+	    if not self.in_shunt:
+		if self.begin.match(line):
+		    self.in_shunt = True
+		    try:
+			self.file = open(self.filename, "w")
+		    except:
+			self.file = None
+			raise
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end.match(line):
+		    if self.file: 
+			self.file.close()
+			self.file = None
+		    self.in_shunt = False
+		else:
+		    if self.file:
+			print >>self.file, line
+		return True
+
+    class shunt_to_list:
+	def __init__(self, begin, end):
+	    self.begin = re.compile(begin)
+	    self.end = re.compile(end)
+	    self.in_shunt = False
+	    self.list = [ ]
+	
+	def __call__(self, line):
+	    if not self.in_shunt:
+		if self.begin.match(line):
+		    self.in_shunt = True
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end.match(line):
+		    self.in_shunt = False
+		else:
+		    self.list.append(line)
+		return True
+
+    class shunt_to_string:
+	def __init__(self, begin, end):
+	    self.begin = re.compile(begin)
+	    self.end = re.compile(end)
+	    self.in_shunt = False
+	    self.str = ""
+	
+	def __call__(self, line):
+	    if not self.in_shunt:
+		if self.begin.match(line):
+		    self.in_shunt = True
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end.match(line):
+		    self.in_shunt = False
+		else:
+		    self.str += line
+		return True
+
+    def create_experiment(self, req, fid):
+	try:
+	    tmpdir = tempfile.mkdtemp(prefix="split-")
+	except IOError:
+	    raise service_error(service_error.internal, "Cannot create tmp dir")
+
+	gw_pubkey_base = "fed.%s.pub" % self.ssh_type
+	gw_secretkey_base = "fed.%s" % self.ssh_type
+	gw_pubkey = tmpdir + "/keys/" + gw_pubkey_base
+	gw_secretkey = tmpdir + "/keys/" + gw_secretkey_base
+	tclfile = tmpdir + "/experiment.tcl"
+	tbparams = { }
+
+	pid = "dummy"
+	gid = "dummy"
+	# XXX
+	fail_soft = False
+
+	try:
+	    os.mkdir(tmpdir+"/keys")
+	except OSError:
+	    raise service_error(service_error.internal,
+		    "Can't make temporary dir")
+
+	req = req.get('CreateRequestBody', None)
+	if not req:
+	    raise service_error(service_error.req,
+		    "Bad request format (no CreateRequestBody)")
+	# The tcl parser needs to read a file so put the content into that file
+	file_content=req.get('experimentdescription', None)
+	if file_content:
+	    try:
+		f = open(tclfile, 'w')
+		f.write(file_content)
+		f.close()
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot write temp experiment description")
+	else:
+	    raise service_error(service_error.req, "No experiment description")
+
+	if req.has_key('experimentID') and \
+		req['experimentID'].has_key('localname'):
+	    eid = req['experimentID']['localname']
+	    while (self.state.has_key(eid)):
+		eid += random.choice(string.ascii_letters)
+	else:
+	    eid = self.exp_stem
+	    for i in range(0,5):
+		eid += random.choice(string.ascii_letters)
+	    while (self.state.has_key(eid)):
+		eid = self.exp_stem
+		for i in range(0,5):
+		    eid += random.choice(string.ascii_letters)
+
+	try:
+	    self.generate_ssh_keys(gw_secretkey, self.ssh_type)
+	except ValueError:
+	    raise service_error(service_error.server_config, 
+		    "Bad key type (%s)" % self.ssh_type)
+
+	user = req.get('user', None)
+	if user == None:
+	    raise service_error(service_error.req, "No user")
+
+	master = req.get('master', None)
+	if master == None:
+	    raise service_error(service_error.req, "No master testbed label")
+	
+	
+	tclcmd = [self.tclsh, self.tcl_splitter, '-s', '-x', 
+	    str(self.muxmax), '-m', master, pid, gid, eid, tclfile]
+	tclparser = Popen(tclcmd, stdout=PIPE)
+
+	allocated = { }
+	started = { }
+
+	parse_current_testbed = self.current_testbed(eid, tmpdir)
+	parse_allbeds = self.allbeds(self.get_access)
+	parse_gateways = self.gateways(eid, master, tmpdir,
+		gw_pubkey_base, gw_secretkey_base, self.copy_file)
+	parse_vtopo = self.shunt_to_string("^#\s+Begin\s+Vtopo",
+		    "^#\s+End\s+Vtopo")
+	parse_hostnames = self.shunt_to_file("^#\s+Begin\s+hostnames",
+		    "^#\s+End\s+hostnames", tmpdir + "/hosts")
+	parse_tarfiles = self.shunt_to_list("^#\s+Begin\s+tarfiles",
+		"^#\s+End\s+tarfiles")
+	parse_rpms = self.shunt_to_list("^#\s+Begin\s+rpms",
+		"^#\s+End\s+rpms")
+
+	for line in tclparser.stdout:
+	    line = line.rstrip()
+	    if parse_current_testbed(line, master, allocated, tbparams):
+		continue
+	    elif parse_allbeds(line, user, tbparams):
+		continue
+	    elif parse_gateways(line, allocated, tbparams):
+		continue
+	    elif parse_vtopo(line):
+		continue
+	    elif parse_hostnames(line):
+		continue
+	    elif parse_tarfiles(line):
+		continue
+	    elif parse_rpms(line):
+		continue
+	    else:
+		raise service_error(service_error.internal, 
+			"Bad tcl parse? %s" % line)
+
+	vtopo = self.gentopo(parse_vtopo.str)
+	if not vtopo:
+	    raise service_error(service_error.internal, 
+		    "Failed to generate virtual topology")
+
+	vis = self.genviz(vtopo)
+	if not vis:
+	    raise service_error(service_error.internal, 
+		    "Failed to generate visualization")
+
+	# save federant information
+	for k in allocated.keys():
+	    tbparams[k]['federant'] = {\
+		    'name': [ { 'localname' : eid} ],\
+		    'emulab': tbparams[k]['emulab'],\
+		    'master' : k == master,\
+		}
+
+
+	# Copy tarfiles and rpms needed at remote sites into a staging area
+	try:
+	    for t in parse_tarfiles.list:
+		if not os.path.exists("%s/tarfiles" % tmpdir):
+		    os.mkdir("%s/tarfiles" % tmpdir)
+		self.copy_file(t, "%s/tarfiles/%s" % \
+			(tmpdir, os.path.basename(t)))
+	    for r in parse_rpms.list:
+		if not os.path.exists("%s/rpms" % tmpdir):
+		    os.mkdir("%s/rpms" % tmpdir)
+		self.copy_file(r, "%s/rpms/%s" % \
+			(tmpdir, os.path.basename(r)))
+	except IOError, e:
+	    raise service_error(service_error.internal, 
+		    "Cannot stage tarfile/rpm: %s" % e.strerror)
+
+	thread_pool_info = self.thread_pool()
+	threads = [ ]
+
+	for tb in [ k for k in allocated.keys() if k != master]:
+	    # Wait until we have a free slot to start the next testbed load
+	    thread_pool_info.acquire()
+	    while thread_pool_info.started - \
+		    thread_pool_info.terminated >= self.nthreads:
+		thread_pool_info.wait()
+	    thread_pool_info.release()
+
+	    # Create and start a thread to start the segment, and save it to
+	    # get the return value later
+	    t  = self.pooled_thread(target=self.start_segment, 
+		    args=(tb, eid, tbparams, tmpdir, 0), name=tb,
+		    pdata=thread_pool_info, trace_file=self.trace_file)
+	    threads.append(t)
+	    t.start()
+
+	# Wait until all finish (the first clause of the while is to make sure
+	# one starts)
+	thread_pool_info.acquire()
+	while thread_pool_info.started == 0 or \
+		thread_pool_info.started > thread_pool_info.terminated:
+	    thread_pool_info.wait()
+	thread_pool_info.release()
+
+	# If none failed, start the master
+	failed = [ t.getName() for t in threads if not t.rv ]
+
+	if len(failed) == 0:
+	    if not self.start_segment(master, eid, tbparams, tmpdir):
+		failed.append(master)
+
+	# If one failed clean up
+	if len(failed) > 0:
+	    succeeded = [tb for tb in allocated.keys() if tb not in failed]
+	    if fail_soft:
+		raise service_error(service_error.partial, \
+			"Partial swap in on %s" % ",".join(succeeded))
+	    else:
+		for tb in succeeded:
+		    self.stop_segment(tb, eid, tbparams)
+		raise service_error(service_error.federant,
+		    "Swap in failed on %s" % ",".join(failed))
+	else:
+	    if self.trace_file:
+		print >>self.trace_file, "Experiment started"
+
+	# Generate an ID for the experiment (slice) and a certificate that the
+	# allocator can use to prove they own it.  We'll ship it back through
+	# the encrypted connection.
+	(expid, expcert) = generate_fedid("test", dir=tmpdir, 
+		trace=self.trace_file)
+
+	if self.trace_file:
+	    print >>self.trace_file, "removing %s" % tmpdir
+
+	# Walk up tmpdir, deleting as we go
+	for path, dirs, files in os.walk(tmpdir, topdown=False):
+	    for f in files:
+		os.remove(os.path.join(path, f))
+	    for d in dirs:
+		os.rmdir(os.path.join(path, d))
+	os.rmdir(tmpdir)
+
+	resp = { 'federant' : [ tbparams[tb]['federant'] \
+		for tb in tbparams.keys() \
+		    if tbparams[tb].has_key('federant') ],\
+		    'vtopo': vtopo,\
+		    'vis' : vis,
+		    'experimentID' : [\
+			    { 'fedid': copy.copy(expid) }, \
+			    { 'localname': eid },\
+			],\
+		    'experimentAccess': { 'X509' : expcert },\
+		}
+	
+	self.state[expid] = { 'federant' : [ tbparams[tb]['federant'] \
+		for tb in tbparams.keys() \
+		    if tbparams[tb].has_key('federant') ],\
+		    'vtopo': vtopo,\
+		    'vis' : vis,
+		    'experimentID' : [\
+			    { 'fedid': expid }, { 'localname': eid },\
+			],\
+		}
+	self.state[eid] = self.state[expid]
+	return resp
+
+    def get_vtopo(self, req, fid):
+
+	req = req.get('VtopoRequestBody', None)
+	if not req:
+	    raise service_error(service_error.req,
+		    "Bad request format (no VtopoRequestBody)")
+	exp = req.get('experiment', None)
+	if exp:
+	    if exp.has_key('fedid'):
+		key = fedid(bits=exp['fedid'])
+		keytype = "fedid"
+	    elif exp.has_key('localname'):
+		key = exp['localname']
+		keytype = "localname"
+	    else:
+		raise service_error(service_error.req, "Unknown lookup type")
+	else:
+	    raise service_error(service_error.req, "No request?")
+
+	if self.state.has_key(key):
+	    return { 'experiment' : {keytype: key },\
+		    'vtopo': self.state[key]['vtopo'],\
+		    }
+	else:
+	    raise service_error(service_error.req, "No such experiment")
+
+    def get_vis(self, req, fid):
+
+	req = req.get('VisRequestBody', None)
+	if not req:
+	    raise service_error(service_error.req,
+		    "Bad request format (no VisRequestBody)")
+	exp = req.get('experiment', None)
+	if exp:
+	    if exp.has_key('fedid'):
+		key = fedid(bits=exp['fedid'])
+		keytype = "fedid"
+	    elif exp.has_key('localname'):
+		key = exp['localname']
+		keytype = "localname"
+	    else:
+		raise service_error(service_error.req, "Unknown lookup type")
+	else:
+	    raise service_error(service_error.req, "No request?")
+
+	if self.state.has_key(key):
+	    return { 'experiment' : {keytype: key },\
+		    'vis': self.state[key]['vis'],\
+		    }
+	else:
+	    raise service_error(service_error.req, "No such experiment")
+
+    def get_info(self, req, fid):
+
+	req = req.get('InfoRequestBody', None)
+	if not req:
+	    raise service_error(service_error.req,
+		    "Bad request format (no VisRequestBody)")
+	exp = req.get('experiment', None)
+	if exp:
+	    if exp.has_key('fedid'):
+		key = fedid(bits=exp['fedid'])
+		keytype = "fedid"
+	    elif exp.has_key('localname'):
+		key = exp['localname']
+		keytype = "localname"
+	    else:
+		raise service_error(service_error.req, "Unknown lookup type")
+	else:
+	    raise service_error(service_error.req, "No request?")
+
+	# The state may be massaged by the service function that called
+	# get_info (e.g., encoded for XMLRPC transport) so send a copy of the
+	# state.
+	if self.state.has_key(key):
+	    return copy.deepcopy(self.state[key])
+	else:
+	    raise service_error(service_error.req, "No such experiment")
+
+
+
+    def terminate_experiment(self, req, fid):
+	tbparams = { }
+	req = req.get('TerminateRequestBody', None)
+	if not req:
+	    raise service_error(service_error.req,
+		    "Bad request format (no TerminateRequestBody)")
+	exp = req.get('experiment', None)
+	if exp:
+	    if exp.has_key('fedid'):
+		key = fedid(bits=exp['fedid'])
+		keytype = "fedid"
+	    elif exp.has_key('localname'):
+		key = exp['localname']
+		keytype = "localname"
+	    else:
+		raise service_error(service_error.req, "Unknown lookup type")
+	else:
+	    raise service_error(service_error.req, "No request?")
+
+	fed_exp = self.state.get(key, None)
+
+	if fed_exp:
+	    # Construct enough of the tbparams to make the stop_segment calls
+	    # work
+	    for fed in fed_exp['federant']:
+		try:
+		    for e in fed['name']:
+			eid = e.get('localname', None)
+			if eid: break
+		    else:
+			continue
+
+		    p = fed['emulab']['project']
+
+		    project = p['name']['localname']
+		    tb = p['testbed']['localname']
+		    user = p['user'][0]['userID']['localname']
+
+		    domain = fed['emulab']['domain']
+		    host  = "%s%s" % (fed['emulab']['ops'], domain)
+		except KeyError, e:
+		    continue
+		tbparams[tb] = {\
+			'user': user,\
+			'domain': domain,\
+			'project': project,\
+			'host': host,\
+			'eid': eid,\
+		    }
+	    # Stop everyone.
+	    for tb in tbparams.keys():
+		self.stop_segment(tb, tbparams[tb]['eid'], tbparams)
+	    return { 'experiment': exp }
+	else:
+	    raise service_error(service_error.req, "No saved state")
+
+
+
+
+if __name__ == '__main__':
+    from optparse import OptionParser
+    
+    parser = OptionParser()
+    parser.add_option('-d', '--debug', dest='debug', default=False,
+	    action='store_true', help='print actions rather than take them')
+    parser.add_option('-f', '--file', dest='tcl', help='tcl file to parse')
+    parser.add_option('-m', '--master', dest='master', 
+	    help='testbed label for matster testbd')
+    parser.add_option('-t', '--trace', dest='trace', default=None, 
+	    help='file to print intermediate messages to')
+    parser.add_option('-T', '--trace-stderr', dest='trace', 
+	    action='store_const',const=sys.stderr,
+	    help='file to print intermediate messages to')
+    opts, args  = parser.parse_args()
+
+    trace_file = None
+    if opts.trace:
+	try:
+	    trace_file = open(opts.trace, 'w')
+	except IOError:
+	    print >>sys.stderr, "Can't open trace file"
+
+    if opts.debug:
+	if not trace_file:
+	    trace_file = sys.stderr
+
+    if opts.tcl != None:
+	try:
+	    f = open(opts.tcl, 'r')
+	    content = ''.join(f)
+	    f.close()
+	except IOError, e:
+	    sys.exit("Can't read %s: %s" % (opts.tcl, e))
+    else:
+	sys.exit("Must specify a file name")
+
+    if not opts.master:
+	sys.exit("Must supply master tb label (--master)");
+
+    obj = fedd_create_experiment_local(
+	    debug=opts.debug,
+	    scripts_dir="/users/faber/testbed/federation",
+	    cert_file="./fedd_client.pem", cert_pwd="faber", 
+	    ssh_pubkey_file='/users/faber/.ssh/id_rsa.pub',
+	    trusted_certs="./cacert.pem",
+	    tbmap = { 
+		'deter':'https://users.isi.deterlab.net:23235',
+		'emulab':'https://users.isi.deterlab.net:23236',
+		'ucb':'https://users.isi.deterlab.net:23237',
+		},
+	    trace_file=trace_file
+	) 
+    rv = obj.create_experiment( {\
+	    'experimentdescription' : content, 
+	    'master' : opts.master, 
+	    'user': [ {'userID' : { 'localname' : 'faber' } } ],
+	    },
+	    None)
+
+    print rv
Index: fedd/fedd_proj.py
===================================================================
--- fedd/fedd_proj.py	(revision 7a8d667972e8db4da477c0270c54dab48255d853)
+++ 	(revision )
@@ -1,887 +1,0 @@
-#!/usr/local/bin/python
-
-import os,sys
-
-from BaseHTTPServer import BaseHTTPRequestHandler
-from ZSI import *
-from M2Crypto import SSL
-from M2Crypto.m2xmlrpclib import SSL_Transport
-from M2Crypto.SSL.SSLServer import SSLServer
-import M2Crypto.httpslib
-import xmlrpclib
-
-import re
-import string
-import subprocess
-import tempfile
-import copy
-
-from fedd_services import *
-from fedd_util import *
-from fedd_allocate_project import *
-from fedd_create_experiment import *
-import parse_detail
-from service_error import *
-
-class fedd_proj:
-    """
-    The implementation of access control based on mapping users to projects.
-
-    Users can be mapped to existing projects or have projects created
-    dynamically.  This implements both direct requests and proxies.
-    """
-    # Attributes that can be parsed from the configuration file
-    bool_attrs = ("dynamic_projects", "project_priority", "create_debug")
-    emulab_attrs = ("boss", "ops", "domain", "fileserver", "eventserver")
-    id_attrs = ("testbed", "cert_file", "cert_pwd", "trusted_certs", "proxy",
-	    "proxy_cert_file", "proxy_cert_pwd", "proxy_trusted_certs",
-	    "dynamic_projects_url", "dynamic_projects_cert_file", 
-	    "dynamic_projects_cert_pwd", "dynamic_projects_trusted_certs",
-	    "create_experiment_cert_file", "create_experiment_cert_pwd",
-	    "create_experiment_trusted_certs", "federation_script_dir",
-	    "ssh_pubkey_file")
-
-    # Used by the SOAP caller
-    soap_namespaces = ('http://www.isi.edu/faber/fedd.wsdl',
-	    'http://www.isi.edu/faber/fedd_internal.wsdl')
-    soap_methods = {\
-	    'RequestAccess': 'soap_RequestAccess',\
-	    'Create' : 'soap_Create',\
-	    'Vtopo' : 'soap_Vtopo',\
-	    'Vis' : 'soap_Vis',\
-	    'Info' : 'soap_Info',\
-	    'Terminate' : 'soap_Terminate',\
-	    }
-    xmlrpc_methods = { \
-	    'RequestAccess': 'xmlrpc_RequestAccess',
-	    'Create': 'xmlrpc_Create',
-	    'Vtopo' : 'xmlrpc_Vtopo',\
-	    'Vis' : 'xmlrpc_Vis',\
-	    'Info' : 'xmlrpc_Info',\
-	    'Terminate' : 'xmlrpc_Terminate',\
-	    }
-
-    class access_project:
-	"""
-	A project description used to grant access to this testbed.
-
-	The description includes a name and a list of node types to which the
-	project will be granted access.
-	"""
-	def __init__(self, name, nt):
-	    self.name = name
-	    self.node_types = list(nt)
-
-	def __repr__(self):
-	    if len(self.node_types) > 0:
-		return "access_proj('%s', ['%s'])" % \
-			(self.name, str("','").join(self.node_types))
-	    else:
-		return "access_proj('%s', [])" % self.name
-
-    # Used to report errors parsing the configuration files, not in providing
-    # service
-    class parse_error(RuntimeError): pass
-
-
-    def __init__(self, config=None):
-	"""
-	Initializer.  Parses a configuration if one is given.
-	"""
-
-	# Create instance attributes from the static lists
-	for a in fedd_proj.bool_attrs:
-	    setattr(self, a, False)
-
-	for a in fedd_proj.emulab_attrs + fedd_proj.id_attrs:
-	    setattr(self, a, None)
-
-	# Other attributes
-	self.attrs = {}
-	self.access = {}
-	self.fedid_category = {}
-	self.fedid_default = "user"
-	self.restricted = []
-	self.create_debug = False
-
-	# Read the configuration
-	if config != None: 
-	    self.read_config(config)
-
-	# Certs are promoted from the generic to the specific, so without a
-	# specific proxy certificate, the main certificates are used for proxy
-	# interactions. If no dynamic project certificates, then proxy certs
-	# are used, and if none of those the main certs.
-
-	# init proxy certs
-	if self.proxy_cert_file == None:
-	    self.proxy_cert_file = self.cert_file
-	    self.proxy_cert_pwd = self.cert_pwd
-
-	if self.proxy_trusted_certs == None:
-	    self.proxy_trusted_certs = self.trusted_certs
-
-	# init dynamic project certs
-	if self.dynamic_projects_cert_file == None:
-	    self.dynamic_projects_cert_file = self.proxy_cert_file
-	    self.dynamic_projects_cert_pwd = self.proxy_cert_pwd
-
-	if self.dynamic_projects_trusted_certs == None:
-	    self.dynamic_projects_trusted_certs = self.proxy_trusted_certs
-
-	proj_certs = (self.dynamic_projects_cert_file, 
-		self.dynamic_projects_trusted_certs,
-		self.dynamic_projects_cert_pwd)
-
-	# Initialize create experiment certs
-	if not self.create_experiment_cert_file:
-	    self.create_experiment_cert_file = self.proxy_cert_file
-	    self.create_experiment_cert_pwd = self.proxy_cert_pwd
-
-	if self.create_experiment_trusted_certs == None:
-	    self.create_experiment_trusted_certs = self.proxy_trusted_certs
-
-	if self.dynamic_projects_url == None:
-	    self.allocate_project = \
-		fedd_allocate_project_local(self.dynamic_projects, 
-			self.dynamic_projects_url, proj_certs)
-	    fedd_proj.soap_methods['AllocateProject'] = 'soap_AllocateProject'
-	else:
-	    self.allocate_project = \
-		fedd_allocate_project_remote(self.dynamic_projects, 
-			self.dynamic_projects_url, proj_certs)
-
-	create_kwargs = { }
-	if self.federation_script_dir:
-	    create_kwargs['scripts_dir'] = self.federation_script_dir
-	if self.ssh_pubkey_file:
-	    create_kwargs['ssh_pubkey_file'] = self.ssh_pubkey_file
-	if self.create_experiment_cert_file:
-	    create_kwargs['cert_file'] = self.create_experiment_cert_file
-	if self.create_experiment_cert_pwd:
-	    create_kwargs['cert_pwd'] = self.create_experiment_cert_pwd
-	if self.create_experiment_trusted_certs:
-	    create_kwargs['trusted_certs'] = \
-		    self.create_experiment_trusted_certs
-
-	self.create_experiment = fedd_create_experiment_local(
-	    tbmap = { 
-		'deter':'https://users.isi.deterlab.net:23235',
-		'emulab':'https://users.isi.deterlab.net:23236',
-		'ucb':'https://users.isi.deterlab.net:23237',
-		},
-	    trace_file=sys.stderr,
-	    debug=self.create_debug,
-	    **create_kwargs
-	) 
-
-    def dump_state(self):
-	"""
-	Dump the state read from a configuration file.  Mostly for debugging.
-	"""
-	for a in fedd_proj.bool_attrs:
-	    print "%s: %s" % (a, getattr(self, a ))
-	for a in fedd_proj.emulab_attrs + fedd_proj.id_attrs:
-	    print "%s: %s" % (a, getattr(self, a))
-	for k, v in self.attrs.iteritems():
-	    print "%s %s" % (k, v)
-	print "Access DB:"
-	for k, v in self.access.iteritems():
-	    print "%s %s" % (k, v)
-	print "Trust DB:"
-	for k, v in self.fedid_category.iteritems():
-	    print "%s %s" % (k, v)
-	print "Restricted: %s" % str(',').join(sorted(self.restricted))
-
-    def get_users(self, obj):
-	"""
-	Return a list of the IDs of the users in dict
-	"""
-	if obj.has_key('user'):
-	    return [ unpack_id(u['userID']) \
-		    for u in obj['user'] if u.has_key('userID') ]
-	else:
-	    return None
-
-    def strip_unicode(self, obj):
-	"""Loosly de-unicode an object"""
-	if isinstance(obj, dict):
-	    for k in obj.keys():
-		obj[k] = self.strip_unicode(obj[k])
-	    return obj
-	elif isinstance(obj, basestring):
-	    return str(obj)
-	elif getattr(obj, "__iter__", None):
-	    return [ self.strip_unicode(x) for x in obj]
-	else:
-	    return obj
-
-    def proxy_xmlrpc_request(self, dt, req):
-	"""Send an XMLRPC proxy request.  Called if the SOAP RPC fails"""
-
-	# No retry loop here.  Proxy servers must correctly authenticate
-	# themselves without help
-	try:
-	    ctx = fedd_ssl_context(self.proxy_cert_file, 
-		    self.proxy_trusted_certs, password=self.proxy_cert_pwd)
-	except SSL.SSLError:
-	    raise service_error(service_error.server_config,
-		    "Server certificates misconfigured")
-
-	# Of all the dumbass things.  The XMLRPC library in use here won't
-	# properly encode unicode strings, so we make a copy of req with the
-	# unicode objects converted.  We also convert the destination testbed
-	# to a basic string if it isn't one already.
-	if isinstance(dt, str): url = dt
-	else: url = str(dt)
-
-	r = copy.deepcopy(req)
-	self.strip_unicode(r)
-	
-	transport = SSL_Transport(ctx)
-	port = xmlrpclib.ServerProxy(url, transport=transport)
-
-	# Reconstruct the full request message
-	try:
-	    resp = port.RequestAccess(
-		    { "RequestAccessRequestBody": r})
-	    resp, method = xmlrpclib.loads(resp)
-	except xmlrpclib.Fault, f:
-	    se = service_error(None, f.faultString, f.faultCode)
-	    raise se
-	except xmlrpclib.Error, e:
-	    raise service_error(service_error.proxy, 
-		    "Remote XMLRPC Fault: %s" % e)
-	
-	if resp[0].has_key('RequestAccessResponseBody'):
-	    return resp[0]['RequestAccessResponseBody']
-	else:
-	    raise service_error(service_error.proxy, 
-		    "Bad proxy response")
-
-    def proxy_request(self, dt, req):
-	"""
-	Send req on to the real destination in dt and return the response
-
-	Req is just the requestType object.  This function re-wraps it.  It
-	also rethrows any faults.
-	"""
-	# No retry loop here.  Proxy servers must correctly authenticate
-	# themselves without help
-	try:
-	    ctx = fedd_ssl_context(self.proxy_cert_file, 
-		    self.proxy_trusted_certs, password=self.proxy_cert_pwd)
-	except SSL.SSLError:
-	    raise service_error(service_error.server_config, 
-		    "Server certificates misconfigured")
-
-	loc = feddServiceLocator();
-	port = loc.getfeddPortType(dt,
-		transport=M2Crypto.httpslib.HTTPSConnection, 
-		transdict={ 'ssl_context' : ctx })
-
-	# Reconstruct the full request message
-	msg = RequestAccessRequestMessage()
-	msg.set_element_RequestAccessRequestBody(
-		pack_soap(msg, "RequestAccessRequestBody", req))
-	try:
-	    resp = port.RequestAccess(msg)
-	except ZSI.ParseException, e:
-	    raise service_error(service_error.proxy,
-		    "Bad format message (XMLRPC??): %s" %
-		    str(e))
-	r = unpack_soap(resp)
-
-	if r.has_key('RequestAccessResponseBody'):
-	    return r['RequestAccessResponseBody']
-	else:
-	    raise service_error(service_error.proxy,
-		    "Bad proxy response")
-
-    def permute_wildcards(self, a, p):
-	"""Return a copy of a with various fields wildcarded.
-
-	The bits of p control the wildcards.  A set bit is a wildcard
-	replacement with the lowest bit being user then project then testbed.
-	"""
-	if p & 1: user = ["<any>"]
-	else: user = a[2]
-	if p & 2: proj = "<any>"
-	else: proj = a[1]
-	if p & 4: tb = "<any>"
-	else: tb = a[0]
-
-	return (tb, proj, user)
-
-    def find_access(self, search):
-	"""
-	Search the access DB for a match on this tuple.  Return the matching
-	access tuple and the user that matched.
-	
-	NB, if the initial tuple fails to match we start inserting wildcards in
-	an order determined by self.project_priority.  Try the list of users in
-	order (when wildcarded, there's only one user in the list).
-	"""
-	if self.project_priority: perm = (0, 1, 2, 3, 4, 5, 6, 7)
-	else: perm = (0, 2, 1, 3, 4, 6, 5, 7)
-
-	for p in perm: 
-	    s = self.permute_wildcards(search, p)
-	    # s[2] is None on an anonymous, unwildcarded request
-	    if s[2] != None:
-		for u in s[2]:
-		    if self.access.has_key((s[0], s[1], u)):
-			return (self.access[(s[0], s[1], u)], u)
-	    else:
-		if self.access.has_key(s):
-		    return (self.access[s], None)
-	return None, None
-
-    def lookup_access(self, req, fid):
-	"""
-	Determine the allowed access for this request.  Return the access and
-	which fields are dynamic.
-
-	The fedid is needed to construct the request
-	"""
-	# Search keys
-	tb = None
-	project = None
-	user = None
-	# Return values
-	rp = fedd_proj.access_project(None, ())
-	ru = None
-
-
-	principal_type = self.fedid_category.get(fid, self.fedid_default)
-
-	if principal_type == "testbed": tb = fid
-
-	if req.has_key('project'):
-	    p = req['project']
-	    if p.has_key('name'):
-		project = unpack_id(p['name'])
-	    user = self.get_users(p)
-	else:
-	    user = self.get_users(req)
-
-	# Now filter by prinicpal type
-	if principal_type == "user":
-	    if user != None:
-		fedids = [ u for u in user if isinstance(u, type(fid))]
-		if len(fedids) > 1:
-		    raise service_error(service_error.req,
-			    "User asserting multiple fedids")
-		elif len(fedids) == 1 and fedids[0] != fid:
-		    raise service_error(service_error.req,
-			    "User asserting different fedid")
-	    project = None
-	    tb = None
-	elif principal_type == "project":
-	    if isinstance(project, type(fid)) and fid != project:
-		raise service_error(service_error.req,
-			"Project asserting different fedid")
-	    tb = None
-
-	# Ready to look up access
-	found, user_match = self.find_access((tb, project, user))
-	
-	if found == None:
-	    raise service_error(service_error.access,
-		    "Access denied")
-
-	# resolve <dynamic> and <same> in found
-	dyn_proj = False
-	dyn_user = False
-
-	if found[0].name == "<same>":
-	    if project != None:
-		rp.name = project
-	    else : 
-		raise service_error(\
-			service_error.server_config,
-			"Project matched <same> when no project given")
-	elif found[0].name == "<dynamic>":
-	    rp.name = None
-	    dyn_proj = True
-	else:
-	    rp.name = found[0].name
-	rp.node_types = found[0].node_types;
-
-	if found[1] == "<same>":
-	    if user_match == "<any>":
-		if user != None: ru = user[0]
-		else: raise service_error(\
-			service_error.server_config,
-			"Matched <same> on anonymous request")
-	    else:
-		ru = user_match
-	elif found[1] == "<dynamic>":
-	    ru = None
-	    dyn_user = True
-	
-	return (rp, ru), (dyn_user, dyn_proj)
-
-    def build_response(self, alloc_id, ap):
-	"""
-	Create the SOAP response.
-
-	Build the dictionary description of the response and use
-	fedd_utils.pack_soap to create the soap message.  NB that alloc_id is
-	a fedd_services_types.IDType_Holder pulled from the incoming message.
-	ap is the allocate project message returned from a remote project
-	allocation (even if that allocation was done locally).
-	"""
-	# Because alloc_id is already a fedd_services_types.IDType_Holder,
-	# there's no need to repack it
-	msg = { 
-		'allocID': alloc_id,
-		'emulab': { 
-		    'domain': self.domain,
-		    'boss': self.boss,
-		    'ops': self.ops,
-		    'fileServer': self.fileserver,
-		    'eventServer': self.eventserver,
-		    'project': ap['project']
-		},
-	    }
-	if len(self.attrs) > 0:
-	    msg['emulab']['fedAttr'] = \
-		[ { 'attribute': x, 'value' : y } \
-			for x,y in self.attrs.iteritems()]
-	return msg
-
-    def RequestAccess(self, req, fid):
-
-	if req.has_key('RequestAccessRequestBody'):
-	    req = req['RequestAccessRequestBody']
-	else:
-	    raise service_error(service_error.req, "No request!?")
-
-	if req.has_key('destinationTestbed'):
-	    dt = unpack_id(req['destinationTestbed'])
-	
-	if dt == None or dt == self.testbed:
-	    # Request for this fedd
-	    found, dyn = self.lookup_access(req, fid)
-	    restricted = None
-	    ap = None
-
-	    # Check for access to restricted nodes
-	    if req.has_key('resources') and req['resources'].has_key('node'):
-		resources = req['resources']
-		restricted = [ t for n in resources['node'] \
-				if n.has_key('hardware') \
-				    for t in n['hardware'] \
-					if t in self.restricted ]
-		inaccessible = [ t for t in restricted \
-				    if t not in found[0].node_types]
-		if len(inaccessible) > 0:
-		    raise service_error(service_error.access,
-			    "Access denied (nodetypes %s)" % \
-			    str(', ').join(inaccessible))
-
-	    ssh = [ x['sshPubkey'] \
-		    for x in req['access'] if x.has_key('sshPubkey')]
-
-	    if len(ssh) > 0: 
-		if dyn[1]: 
-		    # Compose the dynamic project request 
-		    # (only dynamic, dynamic currently allowed)
-		    preq = { 'AllocateProjectRequestBody': \
-				{ 'project' : {\
-				    'user': [ \
-				    { 'access': [ { 'sshPubkey': s } ] } \
-					for s in ssh ] \
-				    }\
-				}\
-			    }
-		    if restricted != None and len(restricted) > 0:
-			preq['AllocateProjectRequestBody']['resources'] = \
-			    [ {'node': { 'hardware' :  [ h ] } } \
-				    for h in restricted ]
-				
-		    ap = self.allocate_project.dynamic_project(preq)
-		else:
-		    # XXX ssh key additions
-		    ap = { 'project': \
-			    { 'name' : { 'localname' : found[0].name },\
-			      'user' : [ {\
-				'userID': { 'localname' : found[1] }, \
-				'access': [ { 'sshPubkey': s } for s in ssh]}\
-				]\
-			    }\
-		    }
-	    else:
-		raise service_error(service_error.req, 
-			"SSH access parameters required")
-
-	    resp = self.build_response(req['allocID'], ap)
-	    return resp
-	else:
-	    p_fault = None	# Any SOAP failure (sent unless XMLRPC works)
-	    try:
-		# Proxy the request using SOAP
-		return self.proxy_request(dt, req)
-	    except service_error, e:
-		if e.code == service_error.proxy: p_fault = None
-		else: raise
-	    except ZSI.FaultException, f:
-		p_fault = f.fault.detail[0]
-		    
-
-	    # If we could not get a valid SOAP response to the request above,
-	    # try the same address using XMLRPC and let any faults flow back
-	    # out.
-	    if p_fault == None:
-		return self.proxy_xmlrpc_request(dt, req)
-	    else:
-		# Build the fault
-		body = p_fault.get_element_FeddFaultBody()
-		if body != None:
-		    raise service_error(body.get_element_code(),
-				body.get_element_desc());
-		else:
-		    raise service_error(\
-			    service_error.proxy,
-			    "Undefined fault from proxy??");
-
-
-    def soap_AllocateProject(self, ps, fid):
-	req = ps.Parse(AllocateProjectRequestMessage.typecode)
-
-	msg = self.allocate_project.dynamic_project(unpack_soap(req), fedid)
-
-	resp = AllocateProjectResponseMessage()
-	resp.set_element_AllocateProjectResponseBody(
-		pack_soap(resp, "AllocateProjectResponseBody", msg))
-
-	return resp
-
-    def soap_RequestAccess(self, ps, fid):
-	req = ps.Parse(RequestAccessRequestMessage.typecode)
-
-	msg = self.RequestAccess(unpack_soap(req), fedid)
-
-	resp = RequestAccessResponseMessage()
-	resp.set_element_RequestAccessResponseBody(
-		pack_soap(resp, "RequestAccessResponseBody", msg))
-
-	return resp
-
-    def soap_Create(self, ps, fid):
-	req = ps.Parse(CreateRequestMessage.typecode)
-
-	msg = self.create_experiment.create_experiment(unpack_soap(req), fedid)
-
-	resp = CreateResponseMessage()
-	resp.set_element_CreateResponseBody(
-		pack_soap(resp, "CreateResponseBody", msg))
-
-	return resp
-
-
-    def soap_Vtopo(self, ps, fid):
-	req = ps.Parse(VtopoRequestMessage.typecode)
-
-	msg = self.create_experiment.get_vtopo(unpack_soap(req), fedid)
-
-	resp = VtopoResponseMessage()
-	resp.set_element_VtopoResponseBody(
-		pack_soap(resp, "VtopoResponseBody", msg))
-
-	return resp
-
-    def soap_Vis(self, ps, fid):
-	req = ps.Parse(VisRequestMessage.typecode)
-
-	msg = self.create_experiment.get_vis(unpack_soap(req), fedid)
-
-	resp = VisResponseMessage()
-	resp.set_element_VisResponseBody(
-		pack_soap(resp, "VisResponseBody", msg))
-
-	return resp
-
-    def soap_Info(self, ps, fid):
-	req = ps.Parse(InfoRequestMessage.typecode)
-
-	msg = self.create_experiment.get_info(unpack_soap(req), fedid)
-
-	resp = InfoResponseMessage()
-	resp.set_element_InfoResponseBody(
-		pack_soap(resp, "InfoResponseBody", msg))
-
-	return resp
-
-    def soap_Terminate(self, ps, fid):
-	req = ps.Parse(TerminateRequestMessage.typecode)
-
-	msg = self.create_experiment.terminate_experiment(unpack_soap(req),
-		fedid)
-
-	resp = TerminateResponseMessage()
-	resp.set_element_TerminateResponseBody(
-		pack_soap(resp, "TerminateResponseBody", msg))
-
-	return resp
-
-    def xmlrpc_RequestAccess(self, params, fid):
-	msg = self.RequestAccess(params[0], fedid)
-
-	if msg != None:
-	    return encapsulate_binaries({ "RequestAccessResponseBody": msg },
-		    ('fedid',))
-	else:
-	    raise service_error(service_error.internal,
-		    "No response generated?!");
-
-    def xmlrpc_Create(self, params, fid):
-	msg = self.create_experiment.create_experiment(params[0], fedid)
-
-	if msg != None:
-	    return encapsulate_binaries({ "CreateResponseBody" : msg },
-		    ('fedid',))
-	else:
-	    raise service_error(service_error.internal,
-		    "No response generated?!")
-
-    def xmlrpc_Vtopo(self, params, fid):
-	p = decapsulate_binaries(params[0], ('fedid',))
-	msg = self.create_experiment.get_vtopo(p, fedid)
-
-	if msg != None:
-	    return encapsulate_binaries({ "VtopoResponseBody" : msg },
-		    ('fedid',))
-	else:
-	    raise service_error(service_error.internal,
-		    "No response generated?!")
-
-    def xmlrpc_Vis(self, params, fid):
-	p = decapsulate_binaries(params[0], ('fedid',))
-	msg = self.create_experiment.get_vis(p, fedid)
-
-	if msg != None:
-	    return encapsulate_binaries({ "VisResponseBody" : msg },
-		    ('fedid',))
-	else:
-	    raise service_error(service_error.internal,
-		    "No response generated?!")
-
-    def xmlrpc_Info(self, params, fid):
-	p = decapsulate_binaries(params[0], ('fedid',))
-	msg = self.create_experiment.get_info(p, fedid)
-	if msg != None:
-	    return encapsulate_binaries({ "InfoResponseBody" : msg },
-		    ('fedid',))
-	else:
-	    raise service_error(service_error.internal,
-		    "No response generated?!")
-
-
-    def xmlrpc_Terminate(self, params, fid):
-	p = decapsulate_binaries(params[0], ('fedid',))
-	msg = self.create_experiment.terminate_experiment(p, fedid)
-	if msg != None:
-	    return encapsulate_binaries({ "TerminateResponseBody" : msg },
-		    ('fedid',))
-	else:
-	    raise service_error(service_error.internal,
-		    "No response generated?!")
-
-    def read_trust(self, trust):
-	"""
-	Read a trust file that splits fedids into testbeds, users or projects
-
-	Format is:
-
-	[type]
-	fedid
-	fedid
-	default: type
-	"""
-	lineno = 0;
-	cat = None
-	cat_re = re.compile("\[(user|testbed|project)\]$", re.IGNORECASE)
-	fedid_re = re.compile("[" + string.hexdigits + "]+$")
-	default_re = re.compile("default:\s*(user|testbed|project)$", 
-		re.IGNORECASE)
-
-	f = open(trust, "r")
-	for line in f:
-	    lineno += 1
-	    line = line.strip()
-	    if len(line) == 0 or line.startswith("#"):
-		continue
-	    # Category line
-	    m = cat_re.match(line)
-	    if m != None:
-		cat = m.group(1).lower()
-		continue
-	    # Fedid line
-	    m = fedid_re.match(line)
-	    if m != None:
-		if cat != None:
-		    self.fedid_category[fedid(hexstr=m.string)] = cat
-		else:
-		    raise fedd_proj.parse_error(\
-			    "Bad fedid in trust file (%s) line: %d" % \
-			    (trust, lineno))
-		continue
-	    # default line
-	    m = default_re.match(line)
-	    if m != None:
-		self.fedid_default = m.group(1).lower()
-		continue
-	    # Nothing matched - bad line, raise exception
-	    f.close()
-	    raise fedd_proj.parse_error(\
-		    "Unparsable line in trustfile %s line %d" % (trust, lineno))
-	f.close()
-
-    def read_config(self, config):
-	"""
-	Read a configuration file and set internal parameters.
-
-	The format is more complex than one might hope.  The basic format is
-	attribute value pairs separated by colons(:) on a signle line.  The
-	attributes in bool_attrs, emulab_attrs and id_attrs can all be set
-	directly using the name: value syntax.  E.g. 
-	boss: hostname
-	sets self.boss to hostname.  In addition, there are access lines of the
-	form (tb, proj, user) -> (aproj, auser) that map the first tuple of
-	names to the second for access purposes.  Names in the key (left side)
-	can include "<NONE> or <ANY>" to act as wildcards or to require the
-	fields to be empty.  Similarly aproj or auser can be <SAME> or
-	<DYNAMIC> indicating that either the matching key is to be used or a
-	dynamic user or project will be created.  These names can also be
-	federated IDs (fedid's) if prefixed with fedid:.  Finally, the aproj
-	can be followed with a colon-separated list of node types to which that
-	project has access (or will have access if dynamic).
-	Testbed attributes outside the forms above can be given using the
-	format attribute: name value: value.  The name is a single word and the
-	value continues to the end of the line.  Empty lines and lines startin
-	with a # are ignored.
-
-	Parsing errors result in a parse_error exception being raised.
-	"""
-	lineno=0
-	name_expr = "["+string.ascii_letters + string.digits + "\.\-_]+"
-	fedid_expr = "fedid:[" + string.hexdigits + "]+"
-	key_name = "(<ANY>|<NONE>|"+fedid_expr + "|"+ name_expr + ")"
-	access_proj = "(<DYNAMIC>(?::" + name_expr +")*|"+ \
-		"<SAME>" + "(?::" + name_expr + ")*|" + \
-		fedid_expr + "(?::" + name_expr + ")*|" + \
-		name_expr + "(?::" + name_expr + ")*)"
-	access_name = "(<DYNAMIC>|<SAME>|" + fedid_expr + "|"+ name_expr + ")"
-
-	bool_re = re.compile('(' + '|'.join(fedd_proj.bool_attrs) + 
-		'):\s+(true|false)', re.IGNORECASE)
-	string_re = re.compile( "(" + \
-		'|'.join(fedd_proj.emulab_attrs + fedd_proj.id_attrs) + \
-		'):\s*(.*)', re.IGNORECASE)
-	attr_re = re.compile('attribute:\s*([\._\-a-z0-9]+)\s+value:\s*(.*)',
-		re.IGNORECASE)
-	access_re = re.compile('\('+key_name+'\s*,\s*'+key_name+'\s*,\s*'+
-		key_name+'\s*\)\s*->\s*\('+access_proj + '\s*,\s*' + 
-		access_name + '\s*\)', re.IGNORECASE)
-	trustfile_re = re.compile("trustfile:\s*(.*)", re.IGNORECASE)
-	restricted_re = re.compile("restricted:\s*(.*)", re.IGNORECASE)
-
-	def parse_name(n):
-	    if n.startswith('fedid:'): return fedid(n[len('fedid:'):])
-	    else: return n
-
-	f = open(config, "r");
-	for line in f:
-	    lineno += 1
-	    line = line.strip();
-	    if len(line) == 0 or line.startswith('#'):
-		continue
-
-	    # Boolean attribute line
-	    m = bool_re.match(line);
-	    if m != None:
-		attr, val = m.group(1,2)
-		setattr(self, attr.lower(), bool(val.lower() == "true"))
-		continue
-
-	    # String attribute line
-	    m = string_re.match(line)
-	    if m != None:
-		attr, val = m.group(1,2)
-		setattr(self, attr.lower(), val)
-		continue
-
-	    # Extended (attribute: x value: y) attribute line
-	    m = attr_re.match(line)
-	    if m != None:
-		attr, val = m.group(1,2)
-		self.attrs[attr] = val
-		continue
-
-	    # Access line (t, p, u) -> (ap, au) line
-	    m = access_re.match(line)
-	    if m != None:
-		access_key = tuple([ parse_name(x) for x in m.group(1,2,3)])
-		aps = m.group(4).split(":");
-		if aps[0] == 'fedid:':
-		    del aps[0]
-		    aps[0] = fedid(hexstr=aps[0])
-
-		au = m.group(5)
-		if au.startswith("fedid:"):
-		    au = fedid(hexstr=aus[len("fedid:"):])
-
-		access_val = (fedd_proj.access_project(aps[0], aps[1:]), au)
-
-		self.access[access_key] = access_val
-		continue
-
-	    # Trustfile inclusion
-	    m = trustfile_re.match(line)
-	    if m != None:
-		self.read_trust(m.group(1))
-		continue
-	    # Restricted node types
-
-	    m = restricted_re.match(line)
-	    if m != None:
-		self.restricted.append(m.group(1))
-		continue
-
-	    # Nothing matched to here: unknown line - raise exception
-	    f.close()
-	    raise fedd_proj.parse_error("Unknown statement at line %d of %s" % \
-		    (lineno, config))
-	f.close()
-
-    def soap_dispatch(self, method, req, fid):
-	if fedd_proj.soap_methods.has_key(method):
-	    try:
-		return getattr(self, fedd_proj.soap_methods[method])(req, fid)
-	    except service_error, e:
-		de = ns0.faultType_Def(
-			(ns0.faultType_Def.schema,
-			    "FeddFaultBody")).pyclass()
-		de._code=e.code
-		de._errstr=e.code_string()
-		de._desc=e.desc
-		if  e.is_server_error():
-		    raise Fault(Fault.Server, e.code_string(), detail=de)
-		else:
-		    raise Fault(Fault.Client, e.code_string(), detail=de)
-	else:
-	    raise Fault(Fault.Client, "Unknown method: %s" % method)
-
-    def xmlrpc_dispatch(self, method, req, fid):
-	if fedd_proj.xmlrpc_methods.has_key(method):
-	    try:
-		return getattr(self, fedd_proj.xmlrpc_methods[method])(req, fid)
-	    except service_error, e:
-		raise xmlrpclib.Fault(e.code_string(), e.desc)
-	else:
-	    raise xmlrpclib.Fault(100, "Unknown method: %s" % method)
-
-def new_feddservice(configfile):
-    return fedd_proj(configfile)
Index: fedd/fedd_util.py
===================================================================
--- fedd/fedd_util.py	(revision 7a8d667972e8db4da477c0270c54dab48255d853)
+++ fedd/fedd_util.py	(revision 19cc4080c3ee52afadbaf6ca0be15c2069826221)
@@ -329,2 +329,63 @@
 	if keypath: os.remove(keypath)
 	if certpath: os.remove(certpath)
+
+
+def make_soap_handler(typecode, method, constructor, body_name):
+    """
+    Generate the handler code to unpack and pack SOAP requests and responses
+    and call the given method.
+
+    The code to decapsulate and encapsulate parameters encoded in SOAP is the
+    same modulo a few parameters.  This is basically a stub compiler for
+    calling a fedd service trhough a soap interface.  The parameters are the
+    typecode of the request parameters, the method to call (usually a bound
+    instance of a method on a fedd service providing class), the constructor of
+    a response packet and the name of the body element of that packet.  The
+    handler takes a ParsedSoap object (the request) and returns an instance of
+    the class created by constructor containing the response.  Failures of the
+    constructor or badly created constructors will result in None being
+    returned.
+    """
+    def handler(ps, fid):
+	req = ps.Parse(typecode)
+
+	msg = method(unpack_soap(req), fedid)
+
+	resp = constructor()
+	set_element = getattr(resp, "set_element_%s" % body_name, None)
+	if set_element and callable(set_element):
+	    try:
+		set_element(pack_soap(resp, body_name, msg))
+		return resp
+	    except (NameError, TypeError):
+		return None
+	else:
+	    return None
+
+    return handler
+
+def make_xmlrpc_handler(method, body_name, input_binaries=('fedid',), 
+	output_binaries=('fedid',)):
+    """
+    Generate the handler code to unpack and pack SOAP requests and responses
+    and call the given method.
+
+    The code to marshall and unmarshall XMLRPC parameters to and from a fedd
+    service is largely the same.  This helper creates such a handler.  The
+    parameters are the method name, the name of the body struct that contains
+    the response asn the list of fields that are encoded as Binary objects in
+    the input and in the output.  A handler is created that takes the params
+    response from an xm,lrpclib.loads on the incoming rpc and a fedid and
+    responds with a hash representing the struct ro be returned to the other
+    side.  On error None is returned.
+    """
+    def handler(params, fid):
+	p = decapsulate_binaries(params[0], input_binaries)
+	msg = method(p, fedid)
+
+	if msg != None:
+	    return encapsulate_binaries({ body_name: msg }, output_binaries)
+	else:
+	    return None
+
+    return handler
