1 #!/usr/bin/python
2 #
3 # Nag(ix)SC -- nagixsc_conf2http.py
4 #
5 # Copyright (C) 2009-2010 Sven Velt <sv@teamix.net>
6 #
7 # This program is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by the
9 # Free Software Foundation; only version 2 of the License is applicable.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 import ConfigParser
21 import base64
22 import optparse
23 import os
24 import re
25 import subprocess
26 import sys
28 try:
29 from hashlib import md5
30 except ImportError:
31 from md5 import md5
33 ##############################################################################
35 from nagixsc import *
37 ##############################################################################
39 parser = optparse.OptionParser()
41 parser.add_option('-c', '', dest='cfgfile', help='Config file')
42 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', help='Daemonize, go to background')
43 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
45 parser.set_defaults(cfgfile='conf2http.cfg')
47 (options, args) = parser.parse_args()
49 cfgread = ConfigParser.SafeConfigParser()
50 cfgread.optionxform = str # We need case-sensitive options
51 cfg_list = cfgread.read(options.cfgfile)
53 if cfg_list == []:
54 print 'Config file "%s" could not be read!' % options.cfgfile
55 sys.exit(1)
57 config = {
58 'ip': '0.0.0.0',
59 'port': '15666',
60 'ssl': False,
61 'sslcert': None,
62 'conf_dir': '',
63 'pidfile': '/var/run/nagixsc_conf2http.pid',
64 'livestatus_socket' : None,
65 }
67 if 'ip' in cfgread.options('server'):
68 config['ip'] = cfgread.get('server', 'ip')
70 if 'port' in cfgread.options('server'):
71 config['port'] = cfgread.get('server', 'port')
72 try:
73 config['port'] = int(config['port'])
74 except ValueError:
75 print 'Port "%s" not an integer!' % config['port']
76 sys.exit(127)
78 if 'ssl' in cfgread.options('server'):
79 try:
80 config['ssl'] = cfgread.getboolean('server', 'ssl')
81 except ValueError:
82 print 'Value for "ssl" ("%s") not boolean!' % config['ssl']
83 sys.exit(127)
85 if config['ssl']:
86 if 'sslcert' in cfgread.options('server'):
87 config['sslcert'] = cfgread.get('server', 'sslcert')
88 else:
89 print 'SSL but no certificate file specified!'
90 sys.exit(127)
92 try:
93 config['conf_dir'] = cfgread.get('server', 'conf_dir')
94 except ConfigParser.NoOptionError:
95 print 'No "conf_dir" specified!'
96 sys.exit(127)
98 if 'pidfile' in cfgread.options('server'):
99 config['pidfile'] = cfgread.get('server', 'pidfile')
101 if 'livestatus_socket' in cfgread.options('server'):
102 config['livestatus_socket'] = prepare_socket(cfgread.get('server', 'livestatus_socket'))
105 users = {}
106 for u in cfgread.options('users'):
107 users[u] = cfgread.get('users', u)
109 ##############################################################################
111 class Conf2HTTPHandler(MyHTTPRequestHandler):
113 def http_error(self, code, output):
114 self.send_response(code)
115 self.send_header('Content-Type', 'text/plain')
116 self.end_headers()
117 self.wfile.write(output)
118 return
121 def do_GET(self):
122 path = self.path.split('/')
124 # Check Basic Auth
125 try:
126 authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
127 if not users[authdata[0]] == md5(authdata[1]).hexdigest():
128 raise Exception
129 except:
130 self.send_response(401)
131 self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
132 self.send_header('Content-Type', 'text/plain')
133 self.end_headers()
134 self.wfile.write('Sorry! No action without login!')
135 return
138 if len(path) >= 4:
139 service = path[3]
140 else:
141 service = None
143 if len(path) >= 3:
144 host = path[2]
145 else:
146 host = None
148 if len(path) >= 2:
149 configfile = path[1] + '.conf'
150 else:
151 self.http_error(500, 'No config file specified')
152 return
154 if re.search('\.\.', configfile):
155 self.http_error(500, 'Found ".." in config file name')
156 return
157 if not re.search('^[a-zA-Z0-9-_]+.conf$', configfile):
158 self.http_error(500, 'Config file name contains invalid characters')
159 return
161 # Just be sure it exists
162 checks = None
164 # If config file name starts with "_" it's something special
165 if not configfile.startswith('_'):
166 # Try to read config file, execute checks
167 check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
168 if not check_config:
169 self.http_error(500, 'Could not read config file "%s"' % configfile)
170 return
171 checks = conf2dict(check_config, host, service)
173 elif configfile=='_livestatus.conf' and config['livestatus_socket']:
174 # Read mk-livestatus and translate into XML
175 checks = livestatus2dict(config['livestatus_socket'], host, service)
178 # No check results? No (good) answer...
179 if not checks:
180 self.http_error(500, 'No check results')
181 return
183 self.send_response(200)
184 self.send_header('Content-Type', 'text/xml')
185 self.end_headers()
186 self.wfile.write(xml_from_dict(checks))
188 return
192 def main():
193 if options.nossl:
194 config['ssl'] = False
196 if config['ssl'] and not os.path.isfile(config['sslcert']):
197 print 'SSL certificate "%s" not found!' % config['sslcert']
198 sys.exit(127)
200 if not os.path.isdir(config['conf_dir']):
201 print 'Not a config file directory: "%s"' % config['conf_dir']
202 sys.exit(127)
204 if options.daemon:
205 daemonize(pidfile=config['pidfile'])
207 server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
208 try:
209 server.serve_forever()
210 except:
211 server.socket.close()
213 if __name__ == '__main__':
214 main()