//
// File: codec.cpp
// Codec registering and initialisation
// Created: 17/07/2001
// Last Modified: 17/07/2001
//

//
// Modifications History
//
//$ LB (06/06/2002) : changed codec functions format (cbPkgCodec, McodeRegister, McodeCall)
//

#include <stdlib.h>
#include <string.h>

#include "codec.h"
extern "C" {
//#ifdef SERVER
# include "bignum.h"
# include "mmemory.h"
//#endif
}



#define MAXPKGCODEC 16

//$ LB (06/06/2002) : changed codec functions format
int (*cbPkgCodec[MAXPKGCODEC])(char *buf, int sizeBuf, int sizeData, int *sizeNeeded, int (*identify)(char *src, char *dst));
int nbcodec=0;


/* initialise la liste des codecs de packages */
int McodecInit()
{
	nbcodec=0;
	return 0;
}

//$ LB (06/06/2002) : changed codec functions format
/* enregistre un codec de packages */
int McodecRegister(int (*fun)(char *buf, int sizeBuf, int sizeData, int *sizeNeeded, int (*identify)(char *src, char *dst)))
{
//#ifdef SERVER
	if (nbcodec>=MAXPKGCODEC) return -1;
	cbPkgCodec[nbcodec++]=fun;
//#endif
	return 0;
}


//#ifdef SERVER
/* fonction appelable par le codec pour s'assurer qu'il est bien appelé par une machine Scol */
int Midentify(char *src,char *dst)
{
	short source[SIZEV];
	short k_priv[SIZEV];
	short k_pub[SIZEV];
	short res[SIZEV];

	MMechostr(1,"Midentify : %s\n",src);
	CRfromAsc(src,source);
	CRfromAsc("4b543f0609b564510c9d8e2c8719ab",k_priv);
	CRfromAsc("70fe5e890e90168ef356b2787d0f19",k_pub);

	CRexpn(source,k_priv,k_pub,res);

	CRtoAsc(dst,res);

	MMechostr(1,"Midentify ->%s\n",dst);
	return 0;
}



//$ LB (06/06/2002) : changed codec functions format
int McodecCall(char **buf,int *size)
{
	int i,k, sizeNeeded;
	char *newbuf;
	for(i=0;i<nbcodec;i++)
	{
		/* appelle le codec externe,
		celui-ci retourne
			.0 s'il n'a pas touché au buffer (les autres codecs seront alors appelés,
			.1 s'il l'a décodé : le buffer contient alors le source en clair, suivi de \0
			.-1 si la taille allouée n'est pas suffisante
		*/



		k=(*(cbPkgCodec[i]))(*buf, (*size), (*size), &sizeNeeded, Midentify);


		//$ LB (06/06/2002) : codec answered that the buffer is not big enough...
		if (k == -1)
		{
			// alloc new buffer
			newbuf = (char*) malloc (sizeNeeded + 1);
			// copy the contents
			memcpy (newbuf, (*buf), (*size));
			if (*buf) free (*buf);
			(*buf) = newbuf;
			(*buf)[sizeNeeded] = '\0';

			// and re-call the codec
			k=(*(cbPkgCodec[i]))(*buf, sizeNeeded, (*size), &sizeNeeded, Midentify);

			// update the size
			(*size) = sizeNeeded;
		}


		if (k) return k;
	}
	return 0;
}
//#endif