// ---------------------------------------------------------------------------
// - PublicCipher.cpp                                                        -
// - afnix:sec module - block cipher 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-2008 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Vector.hpp"
#include "Integer.hpp"
#include "QuarkZone.hpp"
#include "PublicCipher.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------
  
  // create a cipher by name and key
  
  PublicCipher::PublicCipher (const String& name, 
			      const Key&    key) : Cipher (name) {
    // reset all block sizes
    d_mbsz = 0;
    d_cbsz = 0;
    // set the key
    setkey (key);
  }

  // return the class name

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

  // set the public cipher key

  void PublicCipher::setkey (const Key& key) {
    wrlock ();
    try {
      // check the key for validity
      if (key.ispk () == false) {
	throw Exception ("key-error", "invalid key for public cipher");
      } 
      // set the key and return
      Cipher::setkey (key);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the message block size

  long PublicCipher::getmbsz (void) const {
    rdlock ();
    long result = d_mbsz;
    unlock ();
    return result;
  }

  // return the crypted block size

  long PublicCipher::getcbsz (void) const {
    rdlock ();
    long result = d_cbsz;
    unlock ();
    return result;
  }

  // process an input buffer into an output buffer

  t_long PublicCipher::stream (Buffer& ob, Buffer& ib) {
    // trvial case first
    if (d_cbsz == 0) return 0;
    // lock and process
    wrlock ();
    // precompute size
    long bisz = d_rflg ? d_cbsz : d_mbsz;
    long bosz = d_rflg ? d_mbsz : d_cbsz;
    // preallocate counter and buffer
    t_long  cc = 0;
    t_byte* bi = new t_byte[bisz];
    t_byte* bo = new t_byte[bosz];
    // loop as long as the buffer is not empty
    try {
      // initialize the data counter and input buffer
      long bcnt = 0;
      for (long i = 0; i < bisz; i++) bi[i] = nilc;
      while (ib.empty () == false) {
	bi[bcnt++] = ib.read ();
	// check if we process the buffer
	if (bcnt == bisz) {
	  long pmsz = process (bo, bi, bcnt);
	  ob.add ((char*) bo, pmsz);
	  cc += bcnt;
	  bcnt = 0;
	  for (long i = 0; i < bisz; i++) bi[i] = nilc;
	}
      }
      if (bcnt != 0) {
	long pmsz = process (bo, bi, bcnt);
	ob.add ((char*) bo, pmsz);
	cc += bcnt;
      }
      // clean and unlock
      delete [] bi;
      delete [] bo;
      unlock ();
    } catch (...) {
      delete [] bi;
      delete [] bo;
      unlock ();
      throw;
    }
    return cc;
  }

  // process an input stream into an output stream

  t_long PublicCipher::stream (Output& os, Input& is) {
    // trvial case first
    if (d_cbsz == 0) return 0;
    // lock and process
    wrlock ();
    // precompute size
    long bisz = d_rflg ? d_cbsz : d_mbsz;
    long bosz = d_rflg ? d_mbsz : d_cbsz;
    // preallocate counter and buffer
    t_long  cc = 0;
    t_byte* bi = new t_byte[bisz];
    t_byte* bo = new t_byte[bosz];
    // loop as long as the buffer is valid
    try {
      // initialize the data counter and input buffer
      long bcnt = 0;
      for (long i = 0; i < bisz; i++) bi[i] = nilc;
      while (is.valid () == true) {
	bi[bcnt++] = is.read ();
	// check if we process the buffer
	if (bcnt == bisz) {
	  long pmsz = process (bo, bi, bcnt);
	  os.write ((char*) bo, pmsz);
	  cc += bcnt;
	  bcnt = 0;
	  for (long i = 0; i < bisz; i++) bi[i] = nilc;
	}
      }
      if (bcnt != 0) {
	long pmsz = process (bo, bi, bcnt);
	os.write ((char*) bo, pmsz);
	cc += bcnt;
      }
      // clean and unlock
      delete [] bi;
      delete [] bo;
      unlock ();
    } catch (...) {
      delete [] bi;
      delete [] bo;
      unlock ();
      throw;
    }
    return cc;
  }

  // -------------------------------------------------------------------------
  // - 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_GETMBSZ = zone.intern ("get-message-size");
  static const long QUARK_GETCBSZ = zone.intern ("get-crypted-size");

  // return true if the given quark is defined

  bool PublicCipher::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Cipher::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }

  // apply this object with a set of arguments and a quark
  
  Object* PublicCipher::apply (Runnable* robj, Nameset* nset, const long quark,
			      Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_GETMBSZ) return new Integer (getmbsz ());
      if (quark == QUARK_GETCBSZ) return new Integer (getcbsz ());
    }
    // call the cipher method
    return Cipher::apply (robj, nset, quark, argv);
  }
}
