Code

Reorder daemonizing (creation of PID file)
[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 try:
42         config['ip']   = cfgread.get('server', 'ip')
43         config['port'] = cfgread.getint('server', 'port')
44         config['ssl']  = cfgread.getboolean('server', 'ssl')
45         config['cert'] = cfgread.get('server', 'sslcert')
47         config['conf_dir']         = cfgread.get('server', 'conf_dir')
49 except ConfigParser.NoOptionError, e:
50         print 'Config file error: %s ' % e
51         sys.exit(1)
53 users = {}
54 for u in cfgread.options('users'):
55         users[u] = cfgread.get('users', u)
57 ##############################################################################
59 class Conf2HTTPHandler(MyHTTPRequestHandler):
61         def http_error(self, code, output):
62                 self.send_response(code)
63                 self.send_header('Content-Type', 'text/plain')
64                 self.end_headers()
65                 self.wfile.write(output)
66                 return
69         def do_GET(self):
70                 path = self.path.split('/')
72                 # Check Basic Auth
73                 try:
74                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
75                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
76                                 raise Exception
77                 except:
78                         self.send_response(401)
79                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
80                         self.send_header('Content-Type', 'text/plain')
81                         self.end_headers()
82                         self.wfile.write('Sorry! No action without login!')
83                         return
86                 if len(path) >= 4:
87                         service = path[3]
88                 else:
89                         service = None
91                 if len(path) >= 3:
92                         host = path[2]
93                 else:
94                         host = None
96                 if len(path) >= 2:
97                         configfile = path[1] + '.conf'
98                 else:
99                         self.http_error(500, 'No config file specified')
100                         return
102                 if re.search('\.\.', configfile):
103                         self.http_error(500, 'Found ".." in config file name')
104                         return
105                 if not re.search('^[a-zA-Z0-9-_]+.conf$', configfile):
106                         self.http_error(500, 'Config file name contains invalid characters')
107                         return
109                 check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
110                 if not check_config:
111                         self.http_error(500, 'Could not read config file "%s"' % configfile)
112                         return
114                 checks = conf2dict(check_config, host, service)
115                 if not checks:
116                         self.http_error(500, 'No checks executed')
117                         return
119                 self.send_response(200)
120                 self.send_header('Content-Type', 'text/xml')
121                 self.end_headers()
122                 self.wfile.write(xml_from_dict(checks))
124                 return
128 def main():
129         if options.nossl:
130                 config['ssl'] = False
132         if config['ssl'] and not os.path.isfile(config['cert']):
133                 print 'SSL certificate "%s" not found!' % config['cert']
134                 sys.exit(127)
136         if options.daemon:
137                 daemonize(pidfile='/var/run/nagixsc_conf2http.pid')
139         server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['cert'])
140         try:
141                 server.serve_forever()
142         except:
143                 server.socket.close()
145 if __name__ == '__main__':
146         main()