# -*- coding: utf-8 -*-
"""
w2lapp.secinfo.py: Display (SSL) connection data

web2ldap - a web-based LDAP Client,
see http://www.web2ldap.de for details

(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
"""

import time,threading,utctime,web2ldapcnf.misc,web2ldapcnf.monitor,w2lapp.core,w2lapp.gui

from pyweblib.forms import escapeHTML

from w2lapp.session import session

from ldapsession import LDAPSession

try:
  from netaddr import IPAddress,IPNetwork
except ImportError:
  from ipaddr import IPAddress,IPNetwork

def w2l_Monitor(outf,command,form,env):
  """
  List several general gateway stats
  """

  def check_IPAdress(remote_addr,allowed_networks):
    a = IPAddress(remote_addr)
    for n in map(IPNetwork,allowed_networks):
      if a in n:
        return True
    return False

  if not check_IPAdress(env['REMOTE_ADDR'],web2ldapcnf.monitor.access_allowed):
    raise w2lapp.core.ErrorExit(u'Access denied.')

  uptime = (time.time()-w2lapp.core.startUpTime)/60

  w2lapp.gui.TopSection(None,outf,form,None,None,'Monitor',w2lapp.gui.EntryMainMenu(form),[])

  outf.write("""
    <div id="Message" class="Main">
      <h1>Gateway Monitor</h1>
      <h2>Time information</h2>
      <table summary="Time information">
        <tr><td>Current time:</td><td>%s</td></tr>
        <tr><td>Startup time:</td><td>%s</td></tr>
        <tr><td>Uptime:</td><td>%s</td></tr>
      </table>
      <h2>%d active threads:</h2>
      <ul>
        %s
      </ul>
      <h2>Session counters</h2>
      <table summary="Session counters">
        <tr><td>Web sessions initialized:</td> <td>%d</td></tr>
        <tr><td>Web session limit:</td>        <td>%d</td></tr>
        <tr><td>Session removed time:</td>     <td>%d secs</td></tr>
      </table>
    <h2>Active web sessions</h2>
    """ % (
      utctime.strftimeiso8601(time.gmtime(time.time())),
      utctime.strftimeiso8601(time.gmtime(w2lapp.core.startUpTime)),
      '%02d:%02d' % (int(uptime/60),int(uptime%60)),
      threading.activeCount(),
      '\n'.join(
        [
          '<li>%s</li>' % ''.join(
            [
              repr(t),
              ', alive'*t.isAlive(),
              ', daemon'*t.isDaemon(),
            ]
          )
          for t in threading.enumerate()
        ]
      ),
      session.sessionCounter,
      web2ldapcnf.misc.session_limit,
      session.expireRemove,
    )
  )

  if len(session.sessiondict):

    real_ldap_sessions = []
    fresh_ldap_sessions = []
    for k,i in session.sessiondict.items():
      if not k.startswith('__'):
        if isinstance(i[1],LDAPSession):
          real_ldap_sessions.append((k,i))
        else:
          fresh_ldap_sessions.append((k,i))

    if real_ldap_sessions:
      outf.write("""
            <h3>%d active LDAP connections:</h3>
            <table summary="Active LDAP connections">
              <tr>
                <th>Last access time</th>
                <th>Target URI</th>
                <th>Bound as</th>
                <th>Connected from</th>
              </tr>
              %s
            </table>
        """ % (
          len(real_ldap_sessions),
          '\n'.join([
            '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
              utctime.strftimeiso8601(time.gmtime(i[0])),
              form.utf2display(i[1].uri.decode('ascii') or u'no connection'),
              form.utf2display(i[1].who or u'anonymous'),
              form.utf2display(i[1].onBehalf.decode('ascii') or u'unknown'),
            )
            for k,i in real_ldap_sessions
          ]),
      ))

    if fresh_ldap_sessions:
      outf.write("""
            <h3>%d sessions just created:</h3>
            <table summary="Sessions not fully initialized">
              <tr>
                <th>Creation time</th>
              </tr>
              %s
            </table>
        """ % (
          len(fresh_ldap_sessions),
          '\n'.join([
            '<tr><td>%s</td></tr>' % (utctime.strftimeiso8601(time.gmtime(i[0])))
            for k,i in fresh_ldap_sessions
          ]),
      ))

  else:
    outf.write('No active sessions.\n')

  outf.write('</div>\n')
  w2lapp.gui.PrintFooter(outf,form)
