// ---------------------------------------------------------------------------
// - Pkakp.cpp                                                                -
// - afnix:tls service - public key cryptographic standard 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-2020 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Xoid.hpp"
#include "Pkakp.hpp"
#include "AsnOid.hpp"
#include "Vector.hpp"
#include "AsnNull.hpp"
#include "AsnBits.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "AsnBuffer.hpp"
#include "AsnOctets.hpp"
#include "AsnInteger.hpp"
#include "AsnSequence.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------

  // get the pkakp relatif number by index
  static Relatif pkakp_torval (const AsnSequence* pseq, const long index) {
    // check for nil
    if (pseq == nullptr) {
      throw Exception ("pkakp-error", "invalid nil pkakp sequence node");
    }
    // get the node by index
    auto inod = dynamic_cast <AsnInteger*> (pseq->getnode (index));
    if (inod == nullptr) {
      throw Exception ("pkakp-error", "cannot map integer node");
    }
    return inod->torelatif ();
  }


  // get a pkakp rsa private key
  static Key* pkakp_torsa (const AsnOctets* octs) {
    // check for a valid sequence
    if (octs == nullptr) return nullptr;
    // create an asn buffer by octet string
    AsnBuffer abuf (octs->tobuffer());
    // map the buffer as a node
    AsnNode* node = abuf.mapnode();
    // check for a sequence
    auto pseq = dynamic_cast <AsnSequence*> (node);
    // check the sequence length
    if (pseq->getnlen () != 9) {
      throw Exception ("pkakp-error", "invalid pkakp rsa sequence length");
    }
    // get the object version
    long vers = pkakp_torval(pseq, 0).tolong ();
    if (vers != 0L) {
      throw Exception ("pkakp-error", "invalid pkakp rsa key version");
    }
    // get the key element
    Relatif pmod = pkakp_torval (pseq, 1);
    Relatif pexp = pkakp_torval (pseq, 2);
    Relatif sexp = pkakp_torval (pseq, 3);
    Relatif spvp = pkakp_torval (pseq, 4);
    Relatif spvq = pkakp_torval (pseq, 5);
    Relatif crtp = pkakp_torval (pseq, 6);
    Relatif crtq = pkakp_torval (pseq, 7);
    Relatif crti = pkakp_torval (pseq, 8);
    // create a key vector argument
    Vector kvec;
    kvec.add (new Relatif (pmod));
    kvec.add (new Relatif (pexp));
    kvec.add (new Relatif (sexp));
    kvec.add (new Relatif (spvp));
    kvec.add (new Relatif (spvq));
    kvec.add (new Relatif (crtp));
    kvec.add (new Relatif (crtq));
    kvec.add (new Relatif (crti));
    // create the key
    return new Key (Key::CKEY_KRSA, kvec);
  }

  // get a pkakp rsa public key
  static Key* pkakp_torsa (const AsnBits* bits) {
    // check for a valid sequence
    if (bits == nullptr) return nullptr;
    // create an asn buffer by bit string
    AsnBuffer abuf (bits->tobuffer());
    // map the buffer as a node
    AsnNode* node = abuf.mapnode();
    // check for a sequence
    auto pseq = dynamic_cast <AsnSequence*> (node);
    // check the sequence length
    if (pseq->getnlen () != 2) {
      throw Exception ("pkakp-error", "invalid pkakp rsa sequence length");
    }
    // get the key element
    Relatif pmod = pkakp_torval (pseq, 0);
    Relatif pexp = pkakp_torval (pseq, 1);
    // create a key vector argument
    Vector kvec;
    kvec.add (new Relatif (pmod));
    kvec.add (new Relatif (pexp));
    // create the key
    return new Key (Key::CKEY_KRSA, kvec);
  }
  
  // get the pkakp key from the asn buffer
  static Key* pkakp_tokey (const AsnBuffer& abuf) {
    // map the buffer to a node
    AsnNode* node = abuf.mapnode ();
    // check for a sequence
    auto pseq = dynamic_cast <AsnSequence*> (node);
    if (pseq == nullptr) {
      delete node;
      throw Exception ("pkakp-error", "cannot map pkakp sequence node");
    }
    // check the sequence length 3 (private) 2 (public)
    if ((pseq->getnlen () != 3) && (pseq->getnlen () != 2)) {
      delete node;
      throw Exception ("pkakp-error", "invalid pkakp sequence length");
    }
    bool pflg = (pseq->getnlen () == 3) ? true : false;
    // get the object version in private mode
    if (pflg == true) {
      long vers = pkakp_torval(pseq, 0).tolong ();
      if (vers != 0L) {
	throw Exception ("pkakp-error", "invalid pkakp key version");
      }
    }
    long sidx = pflg ? 1L : 0L;
    // get the asn sequence
    auto aseq = dynamic_cast <AsnSequence*> (pseq->getnode(sidx));
    if (aseq == nullptr) {
      delete node;
      throw Exception ("pkakp-error", "cannot map pkakp sequence node");
    }
    if (aseq->getnlen () != 2) {
      delete node;
      throw Exception ("pkakp-error", "invalid pkakp sequence length");
    }
    // get the object oid
    auto soid = dynamic_cast <AsnOid*> (aseq->getnode (0));
    if (soid == nullptr) {
      delete node;
      throw Exception ("pkakp-error", "invalid pkakp object as oid");
    }
    Xoid::t_toid toid = Xoid::totoid (soid->getoid());
    // map the result key
    Key* result = nullptr;
    if (toid == Xoid::TLS_ALGO_RSAE) {
      // check for null node
      auto anil = dynamic_cast<AsnNull*>(aseq->getnode(1));
      if (anil == nullptr) {
	delete node;
	throw Exception ("pkakp-error", "missing null node in pkakp sequence");
      }
      // get the octets string
      result = pflg
	? pkakp_torsa (dynamic_cast<AsnOctets*>(pseq->getnode(2)))
	: pkakp_torsa (dynamic_cast<AsnBits*>  (pseq->getnode(1)));
    }
    delete node;
    return result;
  }

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default pkakp key
  
  Pkakp::Pkakp (void) {
    p_pkey = nullptr;
    reset ();
  }

  // create a pkakp key by key

  Pkakp::Pkakp (Key* pkey) {
    if (pkey != nullptr) {
      d_pemc = pkey->ispublic () ? Pem::PEMC_KEYK : Pem::PEMC_KEYP;
    }
    Object::iref (p_pkey = pkey);
  }

  // create a pkakp key by path

  Pkakp::Pkakp (const String& path) {
    // preset objects
    p_pkey = nullptr;
    // read by path
    Pki::read (path);
    // adjust key type
    if (p_pkey != nullptr) {
      d_pemc = p_pkey->ispublic () ? Pem::PEMC_KEYK : Pem::PEMC_KEYP;
    }
  }
  
  // copy construct this pkakp key

  Pkakp::Pkakp (const Pkakp& that) {
    that.rdlock ();
    try {
      // assign base object
      Pki::operator = (that);
      // copy locally
      p_pkey = (that.p_pkey == nullptr) ? nullptr : new Key (*that.p_pkey);
      Object::iref (p_pkey);
      // here it is
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }
      
  // destroy this pkakp key

  Pkakp::~Pkakp (void) {
    Object::dref (p_pkey);
  }

  // assign a pkakp key to this one

  Pkakp& Pkakp::operator = (const Pkakp& that) {
    // check for self-assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.rdlock ();
    try {
      // assign base object
      Pki::operator = (that);
      // copy locally
      Object::dref (p_pkey);
      p_pkey = (that.p_pkey == nullptr) ? nullptr : new Key (*that.p_pkey);
      Object::iref (p_pkey);
      // here it is
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }
  
  // return the object class name

  String Pkakp::repr (void) const {
    return "Pkakp";
  }

  // return a clone of this object

  Object* Pkakp::clone (void) const {
    return new Pkakp (*this);
  }
  
  // reset the pkakp key

  void Pkakp::reset (void) {
    wrlock ();
    try {
      // reset base object
      Pki::reset ();
      // reset locally
      Object::dref (p_pkey); p_pkey = nullptr;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the pkakp key

  Key* Pkakp::getkey (void) const {
    rdlock ();
    try {
      Key* result = p_pkey;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - protected section                                                     -
  // -------------------------------------------------------------------------

  // encode the pkakp buffer

  bool Pkakp::encode (void) {
    wrlock ();
    try {
      bool result = false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // decode the pkakp buffer
  
  bool Pkakp::decode (void) {
    wrlock ();
    try {
      // create an asn buffer
      AsnBuffer abuf (d_xbuf);
      // map the buffer to a key
      Object::iref (p_pkey = pkakp_tokey (abuf));
      unlock ();
      return true;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

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

  // the object supported quarks
  static const long QUARK_GETKEY = zone.intern ("get-key");

  // create a new object in a generic way
 
  Object* Pkakp::mknew (Vector* argv) {
    long argc = (argv == nullptr) ? 0 : argv->length ();

    // create a default object
    if (argc == 0) return new Pkakp;
    // check for 1 argument
    if (argc == 1) {
      Object* obj = argv->get (0);
      // check for a string
      String* path = dynamic_cast <String*> (obj);
      if (path != nullptr) return new Pkakp (*path);
      // check for a key
      Key* key = dynamic_cast <Key*> (obj);
      if (key != nullptr) return new Pkakp (key);
      // invalid object
      throw Exception ("type-error", "invalif object with pkakp",
		       Object::repr (obj));
    }
    // too many arguments
    throw Exception ("argument-error",
                     "too many argument with pkakp constructor");
  }

  // return true if the given quark is defined

  bool Pkakp::isquark (const long quark, const bool hflg) const {
    rdlock ();
    try {
      if (zone.exists (quark) == true) {
	unlock ();
	return true;
      }
      bool result = hflg ? Pki::isquark (quark, hflg) : false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // apply this object with a set of arguments and a quark

  Object* Pkakp::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_GETKEY) {
	rdlock ();
	try {
	  Object* result = getkey ();
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }
    // call the pkakp method
    return Pki::apply (zobj, nset, quark, argv);
  }
}
