#ident "$Id: image_superblock.c,v 1.9 2006/08/26 02:02:46 craig Exp $"
/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/*
 * This code takes input data and hashes and encrypts it (in that order).
 */

#ifdef __CYGWIN__
#undef __STRICT_ANSI__
#else
#define fseeko(file, where, whence)     fseeko64(file, where, whence)
#define ftello(file)                    ftello64(file)
#endif

#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <strings.h>

#include "aes.h"
#include "types.h"
#include "estypes.h"
#include "es_int.h"
#include "sha1.h"
#include "image_superblock.h"

/* ----------------------------------------------------------------------- */
int
EncryptDiskContent(const char* contentFile, ESContentId cid,
                   const uint8_t* titleKey, uint8_t* const h4Hash)
{
    uint8_t     h3Buf[BLOCKS_FOR_H3 * DVD_BLOCK_SIZE], *h3Ptr;
    char        fileName[64];
    FILE        *inFile, *dataOutFile, *hashOutFile;
    size_t      numHashBytes, numWritten;
    SHA1Context context;

    if ((inFile = fopen(contentFile, "rb"))==NULL) {
        return(ES_ERR_FILE_OPEN_FAILED);
    }
    snprintf(fileName, sizeof(fileName), "%08x.%s", cid, ES_APP_FILE_SUFFIX);
    if ( (dataOutFile = fopen(fileName, "wb")) == NULL) {
        fclose(inFile);
        return(ES_ERR_FILE_OPEN_FAILED);
    }
    /* Make sure that any unused bytes in the H3 hash area are 0 */
    memset(h3Buf, 0, sizeof(h3Buf));

    h3Ptr = h3Buf;

    while (computeSuperBlock(inFile, dataOutFile, h3Ptr,
                             titleKey, true, true) == true) {
        h3Ptr += SHA1_DIGESTSIZE;
    }
    fclose(inFile);
    fclose(dataOutFile);

    snprintf(fileName, sizeof(fileName), "%08x.hash", cid);
    if ((hashOutFile = fopen(contentFile, "wb"))==NULL) {
        return(ES_ERR_FILE_OPEN_FAILED);
    }
    numHashBytes = h3Ptr - h3Buf;
    numWritten = fwrite(h3Buf, numHashBytes, 1, hashOutFile);
    fclose(hashOutFile);
    if (numWritten != numHashBytes) {
        return(ES_ERR_FILE_WRITE_FAILED);
    }

    /*
     * H4 is generated from entire H3 array, because driver won't
     * know how much of the H3 is filled with generated data
     */
    SHA1Reset(&context);
    SHA1Input(&context, h3Buf, BLOCKS_FOR_H3 * DVD_BLOCK_SIZE);
    SHA1Result(&context, h4Hash);
    return(ES_ERR_OK);
}
/* ----------------------------------------------------------------------- */

/*
 * Generate a super block to the output file.  A super block consists of
 * all the DVD blocks which share the same H2 hashes which are present
 * in the hash subblock.  Also, one superblock generates one H3 hash.
 * The size of the superblock is:
 * 31 H0 hashes per datablock -> hashed to 1 H1 hash
 * therefore 1 H1 hash per data block.
 * 8 H1 hashes per H2 hash -> 8 data blocks per H2 hash
 * 8 H2 hashes are in each hash subblock -> 64 data blocks
 * Each data block has 31 subblocks of size 1024 bytes.
 * -> 64 * 31 * 1024 data bytes per superblock
 *
 * Data is hashed, then it is encrypted
 * (unless the flags indicate not to).
 * 
 * The H3 hash for this superblock is written using the h3Ptr.
 * 
 *
 * RETURNS: true if more data is present in the input file,
 *          false otherwise.
 */

bool
computeSuperBlock(FILE *inFile, FILE *outFile, uint8_t* h3Ptr,
                  const uint8_t* const titleKey, const bool encrypt,
                  const bool hash)
{
    SHA1Context context;
    uint8_t     readBuf[DVD_DATA_BYTES_PER_SUPERBLOCK];
    size_t      numRead;
    bool        notEof = true;   
    uint8_t     h0Digests[H0_PER_SUPERBLOCK * SHA1_DIGESTSIZE];
    uint8_t     h1Digests[H1_PER_H2 * H2_PER_SUPERBLOCK * SHA1_DIGESTSIZE];
    uint8_t     h2Digest[H2_PER_SUPERBLOCK * SHA1_DIGESTSIZE];
    uint8_t     *readPtr, *h0Ptr, *h1Ptr, *h2Ptr;
    off_t       outStartPos, blockStartPos;
    uint8_t     hashSubBlock[SUBBLOCK_SIZE], *hashSubBlockPtr;
    uint8_t     encryptedSubBlock[SUBBLOCK_SIZE];
    uint8_t     encryptedDataBlock[31 * SUBBLOCK_SIZE];
    uint8_t     dataIv[16], hashIv[16];
    int         blocksToWrite;


    numRead = fread(readBuf, 1, DVD_DATA_BYTES_PER_SUPERBLOCK, inFile);
    /* printf ("Num read: %d\n", numRead); */
    if (numRead != DVD_DATA_BYTES_PER_SUPERBLOCK) {
        if (numRead == 0 && feof(inFile)) {
            return(false);
        } else if (numRead == 0 && ferror(inFile)) {
            printf ("Error when reading input file - exiting\n");
            exit(1);
        }
        else {
            /* 
             * The file size is not an exact multiple of the number
             * of data bytes per superblock.  Zero out the bytes
             * that would have been read had the file size been
             * an exact multiple
             */
            memset(readBuf + numRead, 0,
                   DVD_DATA_BYTES_PER_SUPERBLOCK - numRead);
        }
    }

    notEof = (feof(inFile) == 0) ? true : false;

    h0Ptr = h0Digests;
    readPtr = readBuf;


    if (hash) {
        /* Generate all the H0 digests needed for H1 and H2 */
        for (int subblock = 0; subblock < H0_PER_SUPERBLOCK; subblock++) {
            SHA1Reset(&context);
            SHA1Input(&context, readPtr, SUBBLOCK_SIZE);
            SHA1Result(&context, h0Ptr);
            readPtr += SUBBLOCK_SIZE;
            h0Ptr   += SHA1_DIGESTSIZE;
        }
    }
    else {
        memset(h0Digests, 0, SHA1_DIGESTSIZE * H0_PER_SUPERBLOCK);
    }


    if (hash) {
        /* Generate the H1 digests */
        h0Ptr = h0Digests;
        h1Ptr = h1Digests;
        for (int h1_count = 0; h1_count < H1_PER_SUPERBLOCK; h1_count++) {
            SHA1Reset(&context);
            SHA1Input(&context, h0Ptr, H0_PER_H1 * SHA1_DIGESTSIZE);
            SHA1Result(&context, h1Ptr);
            h0Ptr += H0_PER_H1 * SHA1_DIGESTSIZE;
            h1Ptr += SHA1_DIGESTSIZE;
        }
    }
    else {
        memset(h1Digests, 0, SHA1_DIGESTSIZE * H1_PER_SUPERBLOCK);
    }

    if (hash) {
        /* Generate the H2 digest */
        h1Ptr = h1Digests;
        h2Ptr = h2Digest;
        for (int i = 0; i < H2_PER_SUPERBLOCK; i++) {
            SHA1Reset(&context);
            SHA1Input(&context, h1Ptr, H1_PER_H2 * SHA1_DIGESTSIZE);
            SHA1Result(&context, h2Ptr);
            h1Ptr += H1_PER_H2 * SHA1_DIGESTSIZE;
            h2Ptr += SHA1_DIGESTSIZE;
        }
    }
    else {
        memset(h2Digest, 0, SHA1_DIGESTSIZE * H2_PER_SUPERBLOCK);
    }

    if (hash) {
        /* Generate the H3 digest */
        SHA1Reset(&context);
        SHA1Input(&context, h2Digest, H2_PER_SUPERBLOCK * SHA1_DIGESTSIZE);
        SHA1Result(&context, h3Ptr);
    }
    else {
        memset(h3Ptr, 0, SHA1_DIGESTSIZE);
    }


    /* Write the H0, H1, and H2 digests, along with the data */
    h0Ptr = h0Digests;
    h1Ptr = h1Digests;
    readPtr = readBuf;
    outStartPos = ftello(outFile);

    blocksToWrite = numRead / DVD_DATA_BYTES_PER_SUPERBLOCK;
    if (blocksToWrite * DVD_DATA_BYTES_PER_SUPERBLOCK != numRead) {
        blocksToWrite++;
    }
    assert(blocksToWrite > 0 && blocksToWrite <= 64);

    for (int block = 0; block < blocksToWrite; block++) {
        size_t  numWritten;

        blockStartPos = ftello(outFile);

        hashSubBlockPtr = hashSubBlock;

        /* Copy H0's plus pad into the hash subblock */
        memcpy(hashSubBlockPtr, h0Ptr, SHA1_DIGESTSIZE * H0_PER_H1);
        h0Ptr += SHA1_DIGESTSIZE * H0_PER_H1;
        hashSubBlockPtr += SHA1_DIGESTSIZE * H0_PER_H1;

        memset(hashSubBlockPtr, 0, H0_PAD_BYTES);
        hashSubBlockPtr += H0_PAD_BYTES;

        /* Copy H1's plus pad into hash subblock */
        memcpy(hashSubBlockPtr, h1Ptr, SHA1_DIGESTSIZE * H1_PER_H2);
        hashSubBlockPtr += SHA1_DIGESTSIZE * H1_PER_H2;

        if ((block + 1) % H1_PER_H2 == 0) {
            h1Ptr += SHA1_DIGESTSIZE * H1_PER_H2;
        }

        memset(hashSubBlockPtr, 0, H1_PAD_BYTES);
        hashSubBlockPtr += H1_PAD_BYTES;

        /* Copy H2 plus pad into hash block */
        memcpy(hashSubBlockPtr, h2Digest, SHA1_DIGESTSIZE * H2_PER_SUPERBLOCK);
        hashSubBlockPtr += SHA1_DIGESTSIZE * H2_PER_SUPERBLOCK;

        memset(hashSubBlockPtr, 0, H2_PAD_BYTES);
        hashSubBlockPtr += H2_PAD_BYTES;

        if (encrypt) {
            /* Encrypt the hashes */
            /* The hashIv is always 0 */
            memset(hashIv, 0, 16);
            aes_SwEncryptWrapper((uint8_t *) titleKey, hashIv,
                                  hashSubBlock, SUBBLOCK_SIZE,
                                  encryptedSubBlock);
        }
        else {
            memcpy(encryptedSubBlock, hashSubBlock, SUBBLOCK_SIZE);
        }

        if (encrypt) {
            /* Encrypt the data
             * The IV is the last 20 encrypted data bytes (not the pad)
             * from the hash subblock 
             */
            memcpy(dataIv, encryptedSubBlock + DVD_DATA_IV_OFFSET, 16);
            /*
            printf ("(%d) dataIv: 0x%x 0x%x 0x%x 0x%x\n",
             timesCalled,
             * (uint32_t *) dataIv,
             * (uint32_t *) (dataIv + 4),
             * (uint32_t *) (dataIv + 8),
             * (uint32_t *) (dataIv + 12));
             */

            aes_SwEncryptWrapper((uint8_t *) titleKey, dataIv,
                                 readPtr, 31 * SUBBLOCK_SIZE,
                                 encryptedDataBlock);
        }
        else {
            memcpy(encryptedDataBlock, readPtr, 31 * SUBBLOCK_SIZE);
        }
        readPtr += DVD_DATA_BYTES_PER_BLOCK;

        /* Write hash subblock to file */
        numWritten = fwrite(encryptedSubBlock, 1, SUBBLOCK_SIZE, outFile);
        if (numWritten != SUBBLOCK_SIZE) {
            fprintf (stderr, "Error: write failed (%d out of %d written) - exit\n",
                     numWritten, SUBBLOCK_SIZE);
            exit(1);
        }

        /* Write data subblocks to file */
        numWritten = fwrite(encryptedDataBlock, 1, SUBBLOCK_SIZE * 31, outFile);
        if (numWritten != SUBBLOCK_SIZE * 31) {
            fprintf (stderr, "Error: write failed (%d out of %d written) - exit\n",
                     numWritten, SUBBLOCK_SIZE * 31);
            exit(1);
        }
        // This assert fails on files > 2Gbytes in size, because
        // ftello is broken for such files..
        // assert(ftello(outFile) - blockStartPos == DVD_BLOCK_SIZE);
    }
    
    return(notEof);
}
