summaryrefslogtreecommitdiff
blob: 6ef89c948d7f7e8ae2888281fc7882b109b998e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python

import certgen
import os
import getopt
import sys
import traceback
from SecureXMLRPCServer import SecureXMLRPCServer
from ScireDB import *
from adodb import *

bind_address = "0.0.0.0"
bind_port = 9876
config_dir = "/etc/scire"
private_key = None
public_key = None
pubkey_obj = None
module_dir = "modules"

modules = {}
xmlrpc_functions = {}

class ScireXMLRPCServer(SecureXMLRPCServer):

	def verify_client_cert(self, conn, cert, errnum, depth, ok):
		self.client_digest = cert.digest("sha1")
#		print "Client CN: " + str(cert.get_subject().commonName)
#		print "Client digest: " + self.client_digest
		return True

	def _dispatch(self, method, params):
		print 'Method: %s' % method

		regfunc = xmlrpc_functions['register_client']['func']
		status = regfunc(self.client_digest)
#		print 'Status: %s' % status

		if not status:
#			print 'Client is not in the table:\n %s' % self.client_digest
			registered = False
		else:
#			print 'Found the client in the database!'
			registered = True
		
		
		try:
			module = modules[xmlrpc_functions[method]['module_name']]
			module_mtime = os.stat(module['path']).st_mtime
			if module_mtime > module['mtime']:
				reload_module(xmlrpc_functions[method]['module_name'])
			func = xmlrpc_functions[method]['func']
		except AttributeError:
			raise Exception('method "%s" is not implemented' % method)
		try:
			if status == 'Active': 
				print 'Client is accepted, proceeding as requested.'
				return func(self.client_digest, *params)
			elif method in ['add_client', 'register_client']:
				return func(self.client_digest, *params)
			else:
				print "Client is not accepted. Exiting.  They were trying to call method \"%s\"" % method
				sys.exit(1)
		except:
			print "==========================="
			print "Error during function call!"
			display_traceback()
			raise

	def db_version(self):
		db = ScireDB()
		value = db.version()
		db.Close()
		return value

#	def Close(self):
#		db.close()

def display_traceback():
	etype, value, tb = sys.exc_info()
	s = traceback.format_exception(etype, value, tb)
	for line in s:
		print line.strip()
	
def generate_cert_and_key(keytype="RSA", keylength=1024):
	# Generate CA cert/key
#	sys.stdout.write("Generating CA certificate...")
#	certgen.certgen(keytype, keylength, "Certificate Authority", config_dir + '/CA.key', config_dir + '/CA.cert')
#	print "done"
	# Generate server cert/key
	sys.stdout.write("Generating server certificate...")
	certgen.certgen(keytype, keylength, "Scire Server", config_dir + '/server.key', config_dir + '/server.cert')
	print "done"

def load_modules(module_dir):
	sys.path.insert(0, module_dir)
	for f in os.listdir(os.path.abspath(module_dir)):
		if f.endswith('.py'): # We only want .py files
			load_module(f.rsplit(".", 1)[0], module_dir + "/" + f)

def load_module(module_name, module_path):
	global modules
	try:
		module = __import__(module_name)
		modules[module_name] = {
		                        'mtime': os.stat(module_path).st_mtime,
		                        'module': module,
		                        'path': module_path
		                       }
		register_module(module_name)
	except:
		print "Couldn't load module %s...continuing" % module_path
		display_traceback()

def reload_module(module_name):
	global modules
	try:
		modules[module_name]['module'] = reload(modules[module_name]['module'])
		modules[module_name]['mtime'] = os.stat(modules[module_name]['path']).st_mtime
		register_module(module_name)
	except:
		print "Couldn't reload module %s...continuing" % modules[module_name]['path']

def register_module(module_name):
	global xmlrpc_functions, modules
	# Remove any previously registered functions from this module
	remove_funcs = []
	for func in xmlrpc_functions:
		if xmlrpc_functions[func]['module_name'] == module_name:
			remove_funcs.append(func)
	for func in remove_funcs:
		del xmlrpc_functions[func]
	try:
		for func in getattr(modules[module_name]['module'], 'register')():
			xmlrpc_functions[func] = {
			                          'func': getattr(modules[module_name]['module'], func),
			                          'module_name': module_name
			                         }
	except:
		print "Couldn't register functions in module %s...continuing" % module_name
		del modules[module_name]

if __name__ == "__main__":

	try:
		opts, args = getopt.getopt(sys.argv[1:], 'dh:p:c:')
	except getopt.error, msg:
		print msg
		print """usage: python %s [-d] [-h host] [-p port] [-c configdir]
		[-d] Turn on debugging
		[-h host] Define the bind IP address/host
		[-p port] Set the port to run on.
		[-c configdir] Set the config directory. (defaults to /etc/scire)
		""" % sys.argv[0]
		sys.exit(2)
	for o, a in opts:
		if o == '-h': bind_address = a
		elif o == '-p' : bind_port = int(a)
		elif o == '-c' : 
			if os.path.isdir(a): 
				config_dir = a 
			else :
				print "ERROR: Config dir doesn't exist\n"
				sys.exit(2)
		elif o == '-d': debug = True

	# Load modules
	load_modules(module_dir)

	# Check for public/private keypair and generate if they don't exist
	if not os.path.isfile(config_dir + "/server.key") or not os.path.isfile(config_dir + "/server.cert"):
		generate_cert_and_key()

	xmlrpc_server = ScireXMLRPCServer((bind_address, bind_port), config_dir + "/server.cert", config_dir + "/server.key")

	try:
		xmlrpc_server.serve_forever()
	finally:
		xmlrpc_server.server_close()