#!/bin/env python 
#-*- coding: UTF-8 -*-

""" This is a parser for openvpn status files, version 3.

How to use:

- add "status-version 3" to openvpn server configuration. Reload/restart openvpn server.
- locate openvpn status file. Usually it's under /var/run in Unix based systems.
- Run "python openvpn-status-parser.py <filename>" for demo. Sample file with random data
  is included in the repository, try it with "python openvpn-status-parser.py".

MIT License:

Copyright (C) 2012, Olli Jarva <olli.jarva@futurice.com>

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to 
the following conditions:

The above copyright notice and this permission notice shall be included 
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

"""
# enable debugging
import cgitb
cgitb.enable()


import pprint
import csv
import datetime
import time
import logging
import sys
import subprocess
import socket

# enable debugging
import cgitb
cgitb.enable()


class OpenVPNStatusParser:
    def __init__(self, filename):
        self.filename = filename
        self.connected_clients = None
    	self.parse_file()
        self.info_time
    	self.what

    def parse_file(self):
        self.connected_clients = {}
        csvreader = csv.reader(open(self.filename), delimiter='\t')
        for row in csvreader:
            row_title = row[0] 
            if row_title == "TIME":
                try:
                    self.info_time= datetime.datetime.fromtimestamp(int(row[2]))
                except (IndexError, ValueError):
                    logging.error("TIME row is invalid: %s" % row)

            elif row_title == "CLIENT_LIST":
                try:
                    self.connected_clients[row[2]] = { "keyname":row[1],"VirtAddr":row[3],"recd":row[4],"sent":row[5],"startts":row[8] }
                except IndexError:
                    logging.error("CLIENT_LIST row is invalid: %s" % row)

            elif row_title == "ROUTING_TABLE":
                try:
                    self.connected_clients[row[3]].update({ "stopts":row[5]})
                except IndexError:
                    logging.error("ROUTING_TABLE row is invalid: %s" % row)

            elif row_title == "GLOBAL_STATS":
                try:
                    self.what= row[2]
                except IndexError:
                    logging.error("GLOBAL_STATS row is invalid: %s" % row)


def main():
    cur_ts = time.time()
    if len(sys.argv) == 1:
        files = ["/etc/openvpn/status.log"]
    else:
        files = sys.argv[1:]

    print "Content-type: text/html"
    print
    print "<html"
    print "<header>"
    print "</header>"
    print "<body>"
    print "<pre>"
    for file in files:
        parser = OpenVPNStatusParser(file)

    	print "<h1>Connected Schoolservers on the XSCENET</h1>"
        print "="*79
        print "Last updated:         %s"%(parser.info_time)
        today = str(datetime.datetime.today())
    	print "Current machine time: %s"%today[0:20]
        print "-"*79
    	print "   vpn ip          actual ip         connect time         handle"
        print "-"*79

        lookup = {}
        for x in parser.connected_clients:
            lookup[parser.connected_clients[x]["VirtAddr"]] = x
        for y in sorted(lookup):
            x = lookup[y]
            handle = uuid = data = ''
            try:
#                secs = long(parser.connected_clients[x]["stopts"]) - long(parser.connected_clients[x]["startts"])
                 start = long(parser.connected_clients[x]["startts"])
                 secs = long(cur_ts) - long(start)
            except Exception as e:
                print(str(e))
                secs = 0
            m, s = divmod(secs, 60)
            h, m = divmod(m , 60)
            d, h = divmod(h , 24)
            readabletime = "%sd %sh %sm"%(d,h,m)

            # get the handle for this client
            try:
                ip = parser.connected_clients[x]["VirtAddr"]
                HOST = ip    # The remote host
                PORT = 1705              # The same port as used by the server
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(2)
                s.connect((HOST, PORT))
                result = s.recv(1024)
                s.close()
                lines = result.split('|')
                for line in lines:
                    if len(line) > 0:
                        chunks = line.split(' ')
                        if line.find('HANDLE') >-1:
                            handle = chunks[2]
                        elif line.find('UUID')>-1:
                            uuid = chunks[2]
            except:
                s.close()
                data = parser.connected_clients[x]['keyname']
            data = handle
            if data == '' and uuid != '':
                data = uuid[0:6]
            if data == '':
                data = parser.connected_clients[x]['keyname'] + "\'s certificate"

            print(parser.connected_clients[x]["VirtAddr"],x,readabletime,data)
    print "\n"
    print "</pre>"
    print "</body>"
    print "</html>"

if __name__ == '__main__':
    main()
# vim: ts=4 expandtab shiftwidth=4 softtabstop=4
