
/*
  cc -g -c isofs_wrap.c
*/

/*
  libisofs related functions of libisoburn.

  Copyright 2007 Vreixo Formoso Lopes <metalpain2002@yahoo.es>
*/

#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include <libburn/libburn.h>
#include <libisofs/libisofs.h>
#include "isoburn.h"
#include "libisoburn.h"

#define BP(a,b) [(b) - (a) + 1]

struct ecma119_pri_vol_desc
{
	uint8_t vol_desc_type		BP(1, 1);
	uint8_t std_identifier		BP(2, 6);
	uint8_t vol_desc_version	BP(7, 7);
	uint8_t unused1			BP(8, 8);
	uint8_t system_id		BP(9, 40);
	uint8_t volume_id		BP(41, 72);
	uint8_t unused2			BP(73, 80);
	uint8_t vol_space_size		BP(81, 88);
	uint8_t unused3			BP(89, 120);
	uint8_t vol_set_size		BP(121, 124);
	uint8_t vol_seq_number		BP(125, 128);
	uint8_t block_size		BP(129, 132);
	uint8_t path_table_size		BP(133, 140);
	uint8_t l_path_table_pos	BP(141, 144);
	uint8_t opt_l_path_table_pos	BP(145, 148);
	uint8_t m_path_table_pos	BP(149, 152);
	uint8_t opt_m_path_table_pos	BP(153, 156);
	uint8_t root_dir_record		BP(157, 190);
	uint8_t	vol_set_id		BP(191, 318);
	uint8_t publisher_id		BP(319, 446);
	uint8_t data_prep_id		BP(447, 574);
	uint8_t application_id		BP(575, 702);
	uint8_t copyright_file_id	BP(703, 739);
	uint8_t abstract_file_id	BP(740, 776);
	uint8_t bibliographic_file_id	BP(777, 813);
	uint8_t vol_creation_time	BP(814, 830);
	uint8_t vol_modification_time	BP(831, 847);
	uint8_t vol_expiration_time	BP(848, 864);
	uint8_t vol_effective_time	BP(865, 881);
	uint8_t file_structure_version	BP(882, 882);
	uint8_t reserved1		BP(883, 883);
	uint8_t app_use			BP(884, 1395);
	uint8_t reserved2		BP(1396, 2048);
};

static
uint32_t iso_read_lsb(const uint8_t *buf, int bytes)
{
	int i;
	uint32_t ret = 0;

	for (i=0; i<bytes; i++) {
		ret += ((uint32_t) buf[i]) << (i*8);
	}
	return ret;
}

/* API function. See libisoburn.h
*/
int isoburn_read_volset(struct burn_drive *d,
                        struct isoburn_read_opts *read_opts, 
                        struct iso_volset **volset)
{
 int ret;
 struct ecma119_read_opts ropts;
 enum burn_disc_status status;
 struct isoburn *o;

 if(d==NULL || read_opts==NULL || volset==NULL) {

   /* >>> program error */;

   return(-1);
 }

 ret = isoburn_find_emulator(&o, d, 0);
 if (ret < 0)
   return 0;

 if (!o) {
   return -1;
 }

 status = isoburn_disc_get_status(d);
 if (status == BURN_DISC_BLANK) {
   struct iso_volume *volume;
   struct iso_tree_node_dir *root;
   
   /*
    * Blank disc, we create a new volset without files.
    */
   
   root = iso_tree_new_root();
   if (!root)
     return -1;
   
   volume = iso_volume_new_with_root("NEW DISC", "", "LIBISOBURN", root);
   if (!volume)
     return -1;
   
   *volset = iso_volset_new(volume, "NEW VOLSET");
   if (!*volset)
     return -1;

   o->target_volset = *volset;
   iso_volset_ref(o->target_volset); /* protects object from premature free */
   return 1;
 }
 
 if (status != BURN_DISC_APPENDABLE && status != BURN_DISC_FULL) {
   /* incorrect disc status */
   return -4;	
 }
 
 ret = isoburn_disc_get_msc1(d, (int*) &ropts.block);
 if (ret < 0)
   return -2;
	
 ropts.norock = read_opts->norock;
 ropts.nojoliet = read_opts->nojoliet;
 ropts.preferjoliet = read_opts->preferjoliet;
 ropts.mode = read_opts->mode;
 ropts.uid = read_opts->uid;
 ropts.gid = read_opts->gid;

 assert(o->src);
 *volset = iso_volset_read(o->src, &ropts);

 if (!(*volset))
   return -3;

 o->target_volset = *volset;
 iso_volset_ref(o->target_volset); /* protects object from premature free */

 read_opts->hasRR = ropts.hasRR;
 read_opts->hasJoliet = ropts.hasJoliet;
 return 1;
}


/* API function. See libisoburn.h
*/
int isoburn_activate_session(struct burn_drive *drive)
{
 int ret;
 struct isoburn *o;

 ret = isoburn_find_emulator(&o, drive, 0);
 if (ret < 0)
   return -1;

 if (o->emulation_mode != 1)
   return 1; /* don't need to activate session */
 
 if (o->fabricated_disc_status != BURN_DISC_APPENDABLE)
   return 1;
 
 ret = burn_random_access_write(drive, 0, (char*)o->target_iso_head, 
                                64*2048, 1);

 return ret;
}


/** Create a new data source suitable for reading from the given drive.
    @param o A freshly created isoburn object, without any data_source
             (src field == NULL), but with the drive field set.
    @return <=0 error , 1 = success
*/
int isoburn_create_data_source(struct isoburn *o)
{

 /* create and initialize the data source */
 o->src = isoburn_data_source_new(o->drive);
 return (o->src ? 1 : -1);
}


/** Dispose the data source created by isoburn_create_data_source().
    @return <=0 error , 1 = success
*/
int isoburn_free_data_source(struct isoburn *o)
{
 if (o->src)
   data_source_free(o->src);
 return 1;
}


/** Initialize the emulation of multi-session on random access media.
    The need for emulation is confirmed already.
    @param o A freshly created isoburn object. isoburn_create_data_source() was
             already called, nevertheless.
    @return <=0 error , 1 = success
*/
int isoburn_start_emulation(struct isoburn *o, int flag)
{
 int ret, i;
 off_t data_count;
 struct burn_drive *drive;
 struct ecma119_pri_vol_desc *pvm;
 
 assert(o);

 drive= o->drive;

 /* we can assume 0 as start block for image */
 /* TODO what about ms? where we validate valid iso image in ms disc? */
 ret = burn_read_data(drive, (off_t) 0, (char*)o->target_iso_head, 
                      sizeof(o->target_iso_head), &data_count, 1);

 /* an error means an empty disc */
 if (ret <= 0) {
   o->fabricated_disc_status= BURN_DISC_BLANK;
   return 1;
 }

 /* check first 64K. If 0's, the disc is treated as a blank disc, and thus
    overwritten without extra check. */
 i = sizeof(o->target_iso_head);
 while (i && !o->target_iso_head[i-1]) 
   --i;

 if (!i) {
   o->fabricated_disc_status= BURN_DISC_BLANK;
   return 1;
 }

 pvm = (struct ecma119_pri_vol_desc *)(o->target_iso_head + 16 * 2048);

 if (!strncmp((char*)pvm->std_identifier, "CD001", 5)) {
   off_t size;

   /* sanity check */
   if (pvm->vol_desc_type[0] != 1 || pvm->vol_desc_version[0] != 1 
       || pvm->file_structure_version[0] != 1 ) {
     /* TODO for now I treat this as a full disc */
     o->fabricated_disc_status= BURN_DISC_FULL;
     return 1;
   }

   /* ok, PVM found, set size */
   size = (off_t) iso_read_lsb(pvm->vol_space_size, 4);
   size *= (off_t) 2048; /* block size in bytes */
   isoburn_set_start_byte(o, size, 0);
   o->fabricated_disc_status= BURN_DISC_APPENDABLE;
 } else if (!strncmp((char*)pvm->std_identifier, "CDXX1", 5)) {

   /* empty image */
   isoburn_set_start_byte(o, (off_t) 0, 0);
   o->fabricated_disc_status= BURN_DISC_BLANK;
 } else {
   /* treat any disc in an unknown format as full */
   o->fabricated_disc_status= BURN_DISC_FULL;
 }
 return 1;
}


/** Alters and writes the first 64 kB of a "media" to invalidate
    an ISO image. (It shall stay restorable by skilled humans, though).
    The result shall especially keep libisoburn from accepting the media
    image as ISO filesystem.
    @param o A fully activated isoburn object. isoburn_start_emulation()
             was already called.
    @return <=0 error , 1 = success
*/
int isoburn_invalidate_iso(struct isoburn *o, int flag)
{
 /* 
  * replace CD001 with CDXX1 in PVM.
  * I think this is enought for invalidating an iso image
  */
 strncpy((char*)o->target_iso_head + 16 * 2048 + 1, "CDXX1", 5);
 return isoburn_activate_session(o->drive);
}

