#ident "$Id: disk_encrypt.c,v 1.10 2006/08/22 19:44:19 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 <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>


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

static bool computeSuperBlock(FILE *inFile, FILE *outFile, uint8_t* h3Ptr,
                              const uint8_t* const titleKey, const bool encrypt,
                              const bool hash);

static int aes_SwEncryptWrapper(uint8_t *key, uint8_t *initVector,
                                uint8_t *dataIn, uint32_t bytes,
                                uint8_t *dataOut);

/* Define DUMP_KEY to write the decryption key to file decrypt_key.h */
// #define DUMP_KEY

/* PRINT_H4_HASH is used to test the streaming library */
// #define PRINT_H4_HASH
#ifdef PRINT_H4_HASH
void dumpBytes (const u8* const ptr, const int length);
#endif

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

    /*
    struct rlimit       resourceLimit;
    if (getrlimit(RLIMIT_STACK, &resourceLimit) == -1) {
        printf ("Can't get stack limit\n");
    }
    else {
        printf ("Stack limit is: %u(soft); %u (hard)\n", resourceLimit.rlim_cur, resourceLimit.rlim_max);
    }
    */
#ifdef DUMP_KEY
    FILE        *keyFile;

    if ((keyFile = fopen("decrypt_key.h", "w")) == NULL) {
        perror("Open of key file failed:");
    }
    else {
        int i;
        fprintf(keyFile, "uint8_t decryptKey[] = {");
        fprintf(keyFile, "0x%02x", titleKey[0]);
        for (i = 1; i < 16; i++) {
            fprintf(keyFile, ", 0x%02x", titleKey[i]);
        }
        fprintf(keyFile, "};\n");
        fclose(keyFile);
    }
#endif


    if ((inFile = fopen(contentFile, "rb")) == NULL) {
        perror("Open of content file failed:");
        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;
    }
    h3Ptr += SHA1_DIGESTSIZE;

    /*
     * Don't signal error on input file close problems, because such
     * errors are in effect harmless
     */
    fclose(inFile);

    if (fclose(dataOutFile) != 0) {
        /*
         * There is no error code for file close failed, so
         * use FILE_WRITE_FAILED as the next best thing
         */
        return(ES_ERR_FILE_WRITE_FAILED);
    }

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

    if (fclose(hashOutFile) != 0) {
        /*
         * There is no error code for file close failed, so
         * use FILE_WRITE_FAILED as the next best thing
         */
        return(ES_ERR_FILE_WRITE_FAILED);
    }
    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, H3_SIZE);
    SHA1Result(&context, h4Hash);

#ifdef PRINT_H4_HASH
    printf ("H4 Hash: ");
    dumpBytes(h4Hash, ES_HASH_SIZE);
#endif

    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.
 */

static 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;
    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;

    /*
     * Malloc'ed because Cygwin default maximum stack size
     * default is ~2M.
     */
    readBuf = (uint8_t *) malloc(DVD_DATA_BYTES_PER_SUPERBLOCK);
    if (readBuf == NULL) {
        printf ("Cannot malloc %u bytes - exit\n",
                 DVD_DATA_BYTES_PER_SUPERBLOCK);
        exit(1);
    }



    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 */
        int subblock; 
        for (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;
        int h1_count;
        for (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;
        int i;
        for (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_BLOCK;
    if (blocksToWrite * DVD_DATA_BYTES_PER_BLOCK != numRead) {
        blocksToWrite++;
    }

    assert(   numRead != DVD_DATA_BYTES_PER_SUPERBLOCK
           || blocksToWrite == BLOCKS_PER_SUPERBLOCK);

    int block;
    for (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);
    }
    
    free(readBuf);
    return(notEof);
}

/* ----------------------------------------------------------------------- */

/*************************************
 * Wrapper to return the new IV needed for chained encryptions
 *************************************
 */
static int
aes_SwEncryptWrapper(uint8_t *key, uint8_t *initVector, uint8_t *dataIn,
                     uint32_t bytes,uint8_t *dataOut)
{
    int         numOldIvBytes;
    int         returnVal;

    returnVal = aes_SwEncrypt(key, initVector, dataIn, bytes, dataOut);
    if (bytes < 16) {
        numOldIvBytes = 16 - bytes;
        memmove(initVector, initVector + bytes, numOldIvBytes);
        memcpy(initVector + numOldIvBytes, dataOut, bytes);
    }
    else {
        memcpy(initVector, dataOut + (bytes - 16), 16);
    }
    return(returnVal);
}

/* ----------------------------------------------------------------------- */

#ifdef PRINT_H4_HASH
void
dumpBytes (const u8* const ptr, const int length)
{
    int i;

    for (i = 0; i < length; i++) {
        if (i % 16 == 0)
            printf ("\n0x%03x: ", i);
        printf ("%02x ", ptr[i]);
    }
    printf ("\n");
}
#endif
/* ----------------------------------------------------------------------- */
