"""
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)

$Id: conninfo.py,v 1.29 2002/01/27 01:32:56 michael Exp $
"""

import time,ldap,w2lapp.cnf,pyweblib.sslenv,w2lapp.core,w2lapp.gui,msgzip

##############################################################################
# Connection info
##############################################################################

def w2l_ConnInfo(sid,outf,command,form,ls,dn,env):

  ldap_managedsait = form.getInputValue('ldap_managedsait',[None])[0]
  if ldap_managedsait!=None:
    ls.manageDsaIt(int(ldap_managedsait))
  
  context_menu_list = []

  currently_bound = hasattr(ls,'who')

  if currently_bound:

    if ls.__dict__.get('hasRootDSE',0):
      context_menu_list.append(
        w2lapp.gui.W2L_Anchor(form,'read','Root DSE',sid,[('dn','')])
      )
    try:
      subschemaSubentryDN = ls.getSubschemaEntryDN(dn)
    except ldap.LDAPError:
      pass
    else:
      if subschemaSubentryDN:
        context_menu_list.append(
          w2lapp.gui.W2L_Anchor(
            form,'read','Subschema',sid,[('dn',subschemaSubentryDN)]
          )
        )
    config_dn_list = [
      ('CN=MONITOR','Monitor'),
      ('CN=CONFIG','Config'),
      ('cn=ldbm','Database'),
    ]
    for config_dn,txt in config_dn_list:
      try:
        if ls.existingEntry(config_dn,suppress_referrals=1):
          context_menu_list.append(
            w2lapp.gui.W2L_Anchor(form,'read',txt,sid,[('dn',config_dn)])
          )
      except ldap.LDAPError:
        pass

  w2lapp.gui.TopSection(
    sid,outf,form,ls,dn,
    'Connection Info',
    w2lapp.gui.MainMenu(sid,form,ls,dn),
    context_menu_list=context_menu_list
  )

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

  outf.write("""
    <div id=MessageDiv>
    <h1>Connection Info</h1>
    <h2>Gateway statistics</h2>
    <table summary="Gateway statistics">
    <tr>
      <td>Uptime:</td>
      <td>%s</td>
    </tr>
    <tr>
      <td>LDAP connections:</td>
      <td>%d</td>
    </tr>
    </table>
    """ % (
      '%02d:%02d' % (uptime/60,uptime%60),
      len(w2lapp.core.session.sessiondict)/2,
    )
  )
  # Extract vendor information (see RFC 3045)
  vendorInfo = u'; Version: '.join(
    filter(
      None,
      [
        ls.__dict__.get('vendorName','unknown'),
        ls.__dict__.get('vendorVersion',None),
      ]
    )
  ).encode(form.accept_charset)
  if not currently_bound:
    outf.write('<h2>LDAP</h2><p>Currently not properly bound.</p>')
  else:
    outf.write("""
      <h2>LDAP connection</h2>
      <table summary="LDAP connection">
      <tr>
        <td>LDAPv%d connection to:</td>
        <td>%s</td>
      </tr>
      <tr>
        <td>Manage DSA IT:</td>
        <td>%s | %s</td>
      </tr>
      <tr>
        <td>Server vendor info:</td>
        <td>%s</td>
      </tr>
      <tr>
        <td>Character set/encoding:</td>
        <td>%s</td>
      </tr>
      <tr>
        <td>Cached items:</td>
        <td>%d</td>
      </tr>
      <tr>
        <td>Started TLS:</td>
        <td>%s</td>
      </tr>
      <tr>
        <td>Bound as:</td>
        <td>
      """ % (
        ls.currentLDAPVersion,
        ls.host.encode('ascii'),
        {0:'disabled',1:'enabled'}[ls.manageDsaItenabled],
        w2lapp.gui.W2L_Anchor(
          form,'conninfo',
          {1:'Disable',0:'Enable'}[ls.manageDsaItenabled],
          sid,
          [('dn',dn),('ldap_managedsait',str(not ls.manageDsaItenabled))]
        ),
        vendorInfo,
        ls.charset.upper(),
        len(ls.read_cache),
        {0:'no',1:'yes'}[ls.startedTLS>0],
      )
    )
    if ls.who:
      
      outf.write(
        ' | '.join([
          w2lapp.gui.DisplayDN(sid,form,ls,ls.who,commandbutton=0),
          w2lapp.gui.W2L_Anchor(
            form,'read','Read',sid,
            [
              ('dn',ls.who),
            ],
          ),
          w2lapp.gui.W2L_Anchor(
            form,'passwd','Password',sid,
            [
              ('dn',ls.who),
              ('passwd_who',ls.who),
            ],
          )
        ])
      )
    else:
      outf.write('anonymous')
    outf.write('</td>\n</tr>\n</table>\n')

  if isinstance(outf,msgzip.GzipFile):
    compresslevel = outf.__dict__.get('compresslevel',None)
  else:
    compresslevel = None
  outf.write("""
    <h2>HTTP connection</h2>
    <table summary="HTTP connection">
      <tr><td>Your IP address:</td><td>%s</td></tr>
      <tr><td>Server signature:</td><td>%s</td></tr>
      <tr><td>Character set/encoding:</td><td>%s</td></tr>
      <tr><td>GZIP compression level:</td><td>%s</td></tr>
      <tr><td>Cross-check vars in use:</td><td>%s</td></tr>
    </table>
    <h2>SSL</h2>
    """ % (
      form.env.get('REMOTE_ADDR','???'),
      form.env.get('SERVER_SIGNATURE',''),
      form.accept_charset.upper(),
      str(compresslevel),
      ', '.join(w2lapp.core.session.sessiondict['__session_checkvars__'+sid].keys()),
    )
  )
  sec_valid_dn = w2lapp.cnf.GetParam(ls,'sec_valid_dn','')
  sec_valid_idn = w2lapp.cnf.GetParam(ls,'sec_valid_idn','')
  pyweblib.sslenv.PrintSecInfo(env,w2lapp.cnf.misc.sec_sslacceptedciphers,sec_valid_dn,sec_valid_idn,outf)
  outf.write('</div>')
  w2lapp.gui.PrintFooter(outf,form)
