Code

Rebuild config file parsing, added defaults
[nagixsc.git] / nagixsc_conf2http.py
1 #!/usr/bin/python
3 import ConfigParser
4 import base64
5 import optparse
6 import os
7 import re
8 import subprocess
9 import sys
11 try:
12         from hashlib import md5
13 except ImportError:
14         from md5 import md5
16 ##############################################################################
18 from nagixsc import *
20 ##############################################################################
22 parser = optparse.OptionParser()
24 parser.add_option('-c', '', dest='cfgfile', help='Config file')
25 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', help='Daemonize, go to background')
26 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
28 parser.set_defaults(cfgfile='conf2http.cfg')
30 (options, args) = parser.parse_args()
32 cfgread = ConfigParser.SafeConfigParser()
33 cfgread.optionxform = str # We need case-sensitive options
34 cfg_list = cfgread.read(options.cfgfile)
36 if cfg_list == []:
37         print 'Config file "%s" could not be read!' % options.cfgfile
38         sys.exit(1)
40 config = {
41                         'ip': '0.0.0.0',
42                         'port': '15666',
43                         'ssl': False,
44                         'sslcert': None,
45                         'conf_dir': '',
46                         'pidfile': '/var/run/nagixsc_conf2http.pid'
47                 }
49 if 'ip' in cfgread.items('server'):
50         config['ip'] = cfgread.get('server', 'ip')
52 if 'port' in cfgread.items('server'):
53         config['port'] = cfgread.get('server', 'port')
54 try:
55         config['port'] = int(config['port'])
56 except ValueError:
57         print 'Port "%s" not an integer!' % config['port']
58         sys.exit(127)
60 if 'ssl' in cfgread.items('server'):
61         try:
62                 config['ssl'] = cfgread.getboolean('server', 'ssl')
63         except ValueError:
64                 print 'Value for "ssl" ("%s") not boolean!' % config['ssl']
65                 sys.exit(127)
67 if config['ssl']:
68         if 'sslcert' in cfgread.items('server'):
69                 config['sslcert'] = cfgread.get('server', 'sslcert')
70         else:
71                 print 'SSL but no certificate file specified!'
72                 sys.exit(127)
74 try:
75         config['conf_dir'] = cfgread.get('server', 'conf_dir')
76 except ConfigParser.NoOptionError:
77         print 'No "conf_dir" specified!'
78         sys.exit(127)
80 if 'pidfile' in cfgread.items('server'):
81         config['pidfile'] = cfgread.get('server', 'pidfile')
84 users = {}
85 for u in cfgread.options('users'):
86         users[u] = cfgread.get('users', u)
88 ##############################################################################
90 class Conf2HTTPHandler(MyHTTPRequestHandler):
92         def http_error(self, code, output):
93                 self.send_response(code)
94                 self.send_header('Content-Type', 'text/plain')
95                 self.end_headers()
96                 self.wfile.write(output)
97                 return
100         def do_GET(self):
101                 path = self.path.split('/')
103                 # Check Basic Auth
104                 try:
105                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
106                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
107                                 raise Exception
108                 except:
109                         self.send_response(401)
110                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
111                         self.send_header('Content-Type', 'text/plain')
112                         self.end_headers()
113                         self.wfile.write('Sorry! No action without login!')
114                         return
117                 if len(path) >= 4:
118                         service = path[3]
119                 else:
120                         service = None
122                 if len(path) >= 3:
123                         host = path[2]
124                 else:
125                         host = None
127                 if len(path) >= 2:
128                         configfile = path[1] + '.conf'
129                 else:
130                         self.http_error(500, 'No config file specified')
131                         return
133                 if re.search('\.\.', configfile):
134                         self.http_error(500, 'Found ".." in config file name')
135                         return
136                 if not re.search('^[a-zA-Z0-9-_]+.conf$', configfile):
137                         self.http_error(500, 'Config file name contains invalid characters')
138                         return
140                 check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
141                 if not check_config:
142                         self.http_error(500, 'Could not read config file "%s"' % configfile)
143                         return
145                 checks = conf2dict(check_config, host, service)
146                 if not checks:
147                         self.http_error(500, 'No checks executed')
148                         return
150                 self.send_response(200)
151                 self.send_header('Content-Type', 'text/xml')
152                 self.end_headers()
153                 self.wfile.write(xml_from_dict(checks))
155                 return
159 def main():
160         if options.nossl:
161                 config['ssl'] = False
163         if config['ssl'] and not os.path.isfile(config['sslcert']):
164                 print 'SSL certificate "%s" not found!' % config['sslcert']
165                 sys.exit(127)
167         if not os.path.isdir(config['conf_dir']):
168                 print 'Not a config file directory: "%s"' % config['conf_dir']
169                 sys.exit(127)
171         if options.daemon:
172                 daemonize(pidfile=config['pidfile'])
174         server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
175         try:
176                 server.serve_forever()
177         except:
178                 server.socket.close()
180 if __name__ == '__main__':
181         main()