// ---------------------------------------------------------------------------
// - TlsDhe.cpp                                                              -
// - afnix:tls service - tls dhe parameters class implementation             -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - This program  is  distributed in  the hope  that it will be useful, but -
// - without  any  warranty;  without  even   the   implied    warranty   of -
// - merchantability or fitness for a particular purpose.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2023 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Pkdhe.hpp"
#include "Vector.hpp"
#include "TlsDhe.hpp"
#include "Integer.hpp"
#include "Evaluable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "transient.tcc"

namespace afnix {
    
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create an empty dhe parameters 

  TlsDhe::TlsDhe (void) {
    p_dhek = nullptr;
    reset ();
  }

  // create a dhe parameters by path

  TlsDhe::TlsDhe (const String& path) {
    p_dhek = nullptr;
    setdhep (path);
  }

  // create a dhe parameters by handshake block

  TlsDhe::TlsDhe (TlsHblock* hblk) {
    p_dhek = nullptr;
    decode (hblk);
  }

  // destroy this dhe parameters

  TlsDhe::~TlsDhe (void) {
    Object::dref (p_dhek);
  }
  
  // return the class name
  
  String TlsDhe::repr (void) const {
    return "TlsDhe";
  }

  // reset this class

  void TlsDhe::reset (void) {
    wrlock ();
    try {
      d_dhep.clear ();
      Object::dref (p_dhek); p_dhek = nullptr;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the dhe parameters info as a plist

  Plist TlsDhe::getinfo (void) const {
    rdlock ();
    try {
      // create a result plist
      Plist plst;
      plst.add ("TLS-HSK-DHEP", "TLS SERVER DHE PARAMETERS", d_dhep);
      // here it is
      unlock ();
      return plst;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // set the dhe parameters path

  void TlsDhe::setdhep (const String& path) {
    wrlock ();
    try {
      reset ();
      Object::iref (p_dhek = Pkdhe(path).getkey ());
      if ((p_dhek == nullptr) || (p_dhek->renew () == false)) {
	throw Exception ("tls-error", "cannot set or renew dhe key");
      }
      d_dhep = path;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the dhe private key
  
  Key* TlsDhe::getprvk (void) const {
    rdlock ();
    try {
      Key* result = p_dhek;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the dhe public key
  
  Key* TlsDhe::getpubk (void) const {
    rdlock ();
    try {
      Key* result =
	(p_dhek == nullptr) ? nullptr : new Key (p_dhek->topublic());
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // decode the hblock into a dhe parameters

  void TlsDhe::decode (TlsHblock* hblk) {
    wrlock ();
    try {
      // reset eveything
      reset ();
      if (hblk == nullptr) {
        unlock ();
        return;
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // map a dhe parameters to a chunk block

  TlsChunk TlsDhe::tochunk (void) const {
    rdlock ();
    try {
      // create a public key
      t_transient<Key> pubk = getpubk ();
      if (pubk.valid () == false) {
	throw Exception ("tls-error", "cannot get dhe public key");
      }
      // collect the dhe parameters
      Relatif p = pubk->getrkey (Key::KDHE_PPRM);
      Relatif g = pubk->getrkey (Key::KDHE_GGEN);
      Relatif y = pubk->getrkey (Key::KDHE_PKEY);
      // create the result chunk
      TlsChunk result;
      // add the dhe parameters
      result.add (p);
      result.add (g);
      result.add (y);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // compute the common key exchange

  Relatif TlsDhe::tokxch (const Relatif& ykey) const {
    rdlock ();
    try {
      if (p_dhek == nullptr) {
	throw Exception ("tls-error", "cannot get common key exchange");
      }
      // collect prime and secret key
      Relatif glop = p_dhek->getrkey (Key::KDHE_PPRM);
      Relatif skey = p_dhek->getrkey (Key::KDHE_SKEY);
      // compute key exchange
      Relatif result =  Relatif::mme (ykey, skey, glop);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 2;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_GETPUBK = zone.intern ("get-public-key");
  static const long QUARK_GETPRVK = zone.intern ("get-private-key");

  // create a new object in a generic way

  Object* TlsDhe::mknew (Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) return new TlsDhe;
    // check for 1 argument
    if (argc == 1) {
      String path = argv->getstring (0);
      return new TlsDhe (path);
    }
    // too many arguments
    throw Exception ("argument-error", 
                     "too many argument with tls dhe parameters");
  }

  // return true if the given quark is defined

  bool TlsDhe::isquark (const long quark, const bool hflg) const {
    rdlock ();
    try {
      if (zone.exists (quark) == true) {
	unlock ();
	return true;
      }
      bool result = hflg ? TlsInfos::isquark (quark, hflg) : false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // apply this object with a set of arguments and a quark

  Object* TlsDhe::apply (Evaluable* zobj, Nameset* nset, const long quark,
			 Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_GETPUBK) return getpubk ();
      if (quark == QUARK_GETPRVK) {
	rdlock ();
	try {
	  Object* result = getprvk ();
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }
    // call the tls infos method
    return TlsInfos::apply (zobj, nset, quark, argv);
  }
}
