Code

Changed license to GPL-2+ (from GPL-2only).
[nagixsc.git] / nagixsc_conf2http.py
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; either version 2 of the License, or (at your
10 # option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with this program; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
21 import ConfigParser
22 import base64
23 import optparse
24 import os
25 import re
26 import subprocess
27 import sys
29 try:
30         from hashlib import md5
31 except ImportError:
32         from md5 import md5
34 ##############################################################################
36 from nagixsc import *
38 ##############################################################################
40 parser = optparse.OptionParser()
42 parser.add_option('-c', '', dest='cfgfile', help='Config file')
43 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', help='Daemonize, go to background')
44 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
46 parser.set_defaults(cfgfile='conf2http.cfg')
48 (options, args) = parser.parse_args()
50 cfgread = ConfigParser.SafeConfigParser()
51 cfgread.optionxform = str # We need case-sensitive options
52 cfg_list = cfgread.read(options.cfgfile)
54 if cfg_list == []:
55         print 'Config file "%s" could not be read!' % options.cfgfile
56         sys.exit(1)
58 config = {
59                         'ip': '0.0.0.0',
60                         'port': '15666',
61                         'ssl': False,
62                         'sslcert': None,
63                         'conf_dir': '',
64                         'pidfile': '/var/run/nagixsc_conf2http.pid',
65                         'livestatus_socket' : None,
66                 }
68 if 'ip' in cfgread.options('server'):
69         config['ip'] = cfgread.get('server', 'ip')
71 if 'port' in cfgread.options('server'):
72         config['port'] = cfgread.get('server', 'port')
73 try:
74         config['port'] = int(config['port'])
75 except ValueError:
76         print 'Port "%s" not an integer!' % config['port']
77         sys.exit(127)
79 if 'ssl' in cfgread.options('server'):
80         try:
81                 config['ssl'] = cfgread.getboolean('server', 'ssl')
82         except ValueError:
83                 print 'Value for "ssl" ("%s") not boolean!' % config['ssl']
84                 sys.exit(127)
86 if config['ssl']:
87         if 'sslcert' in cfgread.options('server'):
88                 config['sslcert'] = cfgread.get('server', 'sslcert')
89         else:
90                 print 'SSL but no certificate file specified!'
91                 sys.exit(127)
93 try:
94         config['conf_dir'] = cfgread.get('server', 'conf_dir')
95 except ConfigParser.NoOptionError:
96         print 'No "conf_dir" specified!'
97         sys.exit(127)
99 if 'pidfile' in cfgread.options('server'):
100         config['pidfile'] = cfgread.get('server', 'pidfile')
102 if 'livestatus_socket' in cfgread.options('server'):
103         config['livestatus_socket'] = prepare_socket(cfgread.get('server', 'livestatus_socket'))
106 users = {}
107 for u in cfgread.options('users'):
108         users[u] = cfgread.get('users', u)
110 ##############################################################################
112 class Conf2HTTPHandler(MyHTTPRequestHandler):
114         def http_error(self, code, output):
115                 self.send_response(code)
116                 self.send_header('Content-Type', 'text/plain')
117                 self.end_headers()
118                 self.wfile.write(output)
119                 return
122         def do_GET(self):
123                 path = self.path.split('/')
125                 # Check Basic Auth
126                 try:
127                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
128                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
129                                 raise Exception
130                 except:
131                         self.send_response(401)
132                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
133                         self.send_header('Content-Type', 'text/plain')
134                         self.end_headers()
135                         self.wfile.write('Sorry! No action without login!')
136                         return
139                 if len(path) >= 4:
140                         service = path[3]
141                 else:
142                         service = None
144                 if len(path) >= 3:
145                         host = path[2]
146                 else:
147                         host = None
149                 if len(path) >= 2:
150                         configfile = path[1] + '.conf'
151                 else:
152                         self.http_error(500, 'No config file specified')
153                         return
155                 if re.search('\.\.', configfile):
156                         self.http_error(500, 'Found ".." in config file name')
157                         return
158                 if not re.search('^[a-zA-Z0-9-_]+.conf$', configfile):
159                         self.http_error(500, 'Config file name contains invalid characters')
160                         return
162                 # Just be sure it exists
163                 checks = None
165                 # If config file name starts with "_" it's something special
166                 if not configfile.startswith('_'):
167                         # Try to read config file, execute checks
168                         check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
169                         if not check_config:
170                                 self.http_error(500, 'Could not read config file "%s"' % configfile)
171                                 return
172                         checks = conf2dict(check_config, host, service)
174                 elif configfile=='_livestatus.conf' and config['livestatus_socket']:
175                         # Read mk-livestatus and translate into XML
176                         checks = livestatus2dict(config['livestatus_socket'], host, service)
179                 # No check results? No (good) answer...
180                 if not checks:
181                         self.http_error(500, 'No check results')
182                         return
184                 self.send_response(200)
185                 self.send_header('Content-Type', 'text/xml')
186                 self.end_headers()
187                 self.wfile.write(xml_from_dict(checks))
189                 return
193 def main():
194         if options.nossl:
195                 config['ssl'] = False
197         if config['ssl'] and not os.path.isfile(config['sslcert']):
198                 print 'SSL certificate "%s" not found!' % config['sslcert']
199                 sys.exit(127)
201         if not os.path.isdir(config['conf_dir']):
202                 print 'Not a config file directory: "%s"' % config['conf_dir']
203                 sys.exit(127)
205         if options.daemon:
206                 daemonize(pidfile=config['pidfile'])
208         server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
209         try:
210                 server.serve_forever()
211         except:
212                 server.socket.close()
214 if __name__ == '__main__':
215         main()