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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>

#include "es_int.h"
#include "aes.h"
#include "esl.h"
#include "es_utils.h"

/*
 * return the TMD size in bytes given the number of contents in the title 
 *
 */
int
ES_GetTmdSize(u16 numContents) 
{
    return (sizeof(IOSCSigRsa2048)+sizeof(ESTitleMetaHeader)+
           numContents*sizeof(ESContentMeta));
}

int
ES_EncryptContentReset(ESAesShaHandle* handle, u16 cidx, const u8* titleKey)
{
    if (handle == NULL || titleKey == NULL)
        return ES_ERR_ENCRYPTION_FAILED;
    
    memset(handle, 0, sizeof(ESAesShaHandle));
    u16 idx = htons(cidx);
    memcpy(handle->iv, (u8*)(&idx), sizeof(u16));
    SHA1Reset(&handle->sha);
    handle->titleKey = titleKey;
    handle->inbufSize = 0;
    return ES_ERR_OK;
}


int
ES_EncryptContentUpdate(ESAesShaHandle* handle, const u8* inbuf, u32 inSize, u8* outbuf, u32 outSize)
{
    int inOfst = 0;
    int outOfst = 0;
    const int opSize = sizeof(handle->inbuf);
    
    if (outSize < opSize || outSize < inSize)
        return ES_ERR_ENCRYPTION_FAILED;

    // handle remaining bytes from last call
    if (handle->inbufSize > 0) {
        u32 avail = opSize - handle->inbufSize;
        if (avail > inSize) {
            memcpy(handle->inbuf + handle->inbufSize, inbuf, inSize);
            handle->inbufSize += inSize;
            return 0;
        } else {
            memcpy(handle->inbuf + handle->inbufSize, inbuf, avail);
            inOfst = avail;
            SHA1Input(&(handle->sha), handle->inbuf, opSize);
            if (aes_SwEncrypt((u8*) handle->titleKey, handle->iv,
                handle->inbuf, opSize, outbuf) < 0)
                return ES_ERR_ENCRYPTION_FAILED;
            handle->inbufSize = 0;
            outOfst = opSize;
            memcpy(handle->iv, outbuf + (outOfst - sizeof(IOSCAesIv)),
                   sizeof(IOSCAesIv));
        }
    }

    // encrypt the main part of the input data
    if (inSize - inOfst >= opSize) {
        int size = ((inSize - inOfst) / opSize) * opSize;
        SHA1Input(&(handle->sha), inbuf + inOfst, size);
        if (aes_SwEncrypt((u8*) handle->titleKey, handle->iv,
            (u8*)inbuf + inOfst, size, outbuf + outOfst) < 0)
            return ES_ERR_ENCRYPTION_FAILED;
        inOfst += size;
        outOfst += size;
        memcpy(handle->iv,
               outbuf + (outOfst - sizeof(IOSCAesIv)),
               sizeof(IOSCAesIv));
    }

    // remaining unaligned bytes
    if ((handle->inbufSize = inSize - inOfst) > 0) {
        memcpy(handle->inbuf, inbuf + inOfst, handle->inbufSize);
    }

    return outOfst;
}


int
ES_EncryptContentFinal(ESAesShaHandle* handle, u8* outbuf, u32 outSize, u8* hash)
{
    const int opSize = sizeof(handle->inbuf);
    int result = 0;
    
    if (outSize < opSize)
        return ES_ERR_ENCRYPTION_FAILED;

    if (handle->inbufSize > 0) {
        SHA1Input(&(handle->sha), handle->inbuf, handle->inbufSize);
        if (handle->inbufSize < opSize) {
            memset(handle->inbuf + handle->inbufSize, 0,
                   opSize - handle->inbufSize);
        }
        if (aes_SwEncrypt((u8*) handle->titleKey, handle->iv, handle->inbuf,
                          opSize, outbuf) < 0)
            return ES_ERR_ENCRYPTION_FAILED;
        result = opSize;
    }

    SHA1Result(&(handle->sha), hash);
    return result;
}


/* 
 * AES encrypt content file and compute hash 
 *
 * Input: 
 * contentFile - name of the raw content file
 * cid         - content ID for the content
 * titleKey    - 128 bit AES encryption key
 *
 * Output: 
 * hash        - 160bit SHA1 hash of the content (caller allocates)
 * the encrypted content file is written to <cid>.app, the content 
 * file is padded to multiple of 16 bytes
 *
 */
int
ES_EncryptContent(const char* contentFile, ESContentId cid, u16 cidx, const u8* titleKey, u8* hash)
{
    ESAesShaHandle handle;
    int rv = ES_ERR_OK;
    FILE *fptr1, *fptr2;
    u8 dataIn[ES_BLOCK_SIZE];
    u8 dataOut[ES_BLOCK_SIZE];
    int bytesRead = 0;
    int bytesEncrypted = 0;
    char name[16];

    if ((rv = ES_EncryptContentReset(&handle, cidx, titleKey)) != ES_ERR_OK)
        return rv;

    if ((fptr1 = fopen(contentFile, "rb"))==NULL) {
        rv = ES_ERR_FILE_OPEN_FAILED;
        goto out;
    }
    sprintf(name, "%08x.%s", cid, ES_APP_FILE_SUFFIX);
    fptr2 = fopen(name, "wb");
    while (!feof(fptr1)) {
        bytesRead = fread(dataIn, sizeof(u8), ES_BLOCK_SIZE, fptr1);
        bytesEncrypted = ES_EncryptContentUpdate(&handle, dataIn, bytesRead,
                         dataOut, sizeof(dataOut));

        if (bytesEncrypted < 0) {
            rv = bytesEncrypted;
            goto out1;
        } else if (bytesEncrypted > 0)
            fwrite(dataOut, sizeof(u8), bytesEncrypted, fptr2);
    }

    bytesEncrypted = ES_EncryptContentFinal(&handle, dataOut,
                     sizeof(dataOut), hash);
    
    if (bytesEncrypted < 0) {
        rv = bytesEncrypted;
        goto out1;
    } else if (bytesEncrypted > 0)
        fwrite(dataOut, sizeof(u8), bytesEncrypted, fptr2);

out1:
    fclose(fptr1);
    fclose(fptr2);

out:
    return rv;
}

/*
 * Generate unsigned TMD for a given title. 
 *
 * Input: 
 * tmdView          - ESTmdView for the list of content IDs & attributes
 *                    (note: size is actual size of the raw content) 
 * caCrlVersion     - CA CRL version
 * signerCrlVersion - server (XS, CP, MS) CRL version
 * sysVersion       - system software version
 * rights           - the title's rights to the device
 * reserved         - Nintendo custom data
 * bootIndex        - content index for boot content
 * hash             - array of 160bit SHA1 hash for the contents
 * signerCertName   - conetent publishing server's cert name
 * signerCertIssuerName       
 *                  - content publishing server cert issuer's name
 *
 * Output:
 * tmd              - unsigned TMD data structure (caller allocates)
 *
 */
int
ES_GenerateUnsignedTmd(const ESTmdView* tmdView, ESVersion caCrlVersion, ESVersion signerCrlVersion, ESSysVersion sysVersion, u32 rights, u16 bootIndex, const u8* hashes, const char* signerCertName, const char* signerCertIssuerName, void* tmd)
{
    int rv = ES_ERR_OK;
    ESTitleMeta* ptr = (ESTitleMeta*)tmd;
    int i, size;

    size = ES_GetTmdSize(tmdView->head.numContents);
    memset(ptr, 0, size);

    /* fill TMD header */
    ptr->head.version = ES_TMD_VERSION; 
    ptr->head.sysVersion = htonll(sysVersion); 
    ptr->head.caCrlVersion = caCrlVersion; 
    ptr->head.signerCrlVersion = signerCrlVersion; 

    ptr->head.type = htonl(tmdView->head.type);
    ptr->head.groupId = htons(tmdView->head.groupId);
    ptr->head.titleId = htonll(tmdView->head.titleId);
    memcpy(ptr->head.reserved, tmdView->head.reserved, sizeof(ESTmdReserved));
    ptr->head.accessRights = htonl(rights);
    ptr->head.titleVersion = htons(tmdView->head.titleVersion); 
    ptr->head.numContents = htons(tmdView->head.numContents);
    ptr->head.bootIndex = htons(bootIndex);

    /* fill CMDs and encrypt content */
    for (i=0; i<tmdView->head.numContents; i++) {
        (ptr->contents[i]).cid = htonl((tmdView->contents[i]).cid);
        (ptr->contents[i]).index = htons((tmdView->contents[i]).index);
        (ptr->contents[i]).type = htons((tmdView->contents[i]).type);
        (ptr->contents[i]).size = htonll((tmdView->contents[i]).size);
        memcpy((ptr->contents[i]).hash, 
               hashes+i*sizeof(IOSCSha1Hash), sizeof(IOSCSha1Hash));
    }

    /* fill sig struct, leave signature blank */
    ptr->sig.sigType = htonl(IOSC_SIG_RSA2048);
    sprintf(ptr->sig.issuer, "%s-%s", signerCertIssuerName, signerCertName); 

    return rv;
}

/* 
 * Generate content publisher common key encrypted title key, to be stored 
 * in eTicket.
 *
 * Input
 * commonKey - 128bit AES encryption key from content publishing server
 * titleId   - title ID for the title
 * titleKey  - 128bit AES encryption key used for encrypting the title
 *
 * Output
 * outKey    - 128bit encrypted title key (caller allocates)
 *
 */
int 
ES_CpEncryptTitleKey(const u8* commonKey, ESTitleId titleId, const u8* titleKey, u8* outKey)
{
    int rv = ES_ERR_OK;
    IOSCAesIv iv;

    ESTitleId tid = htonll(titleId);
    memset(iv, 0, sizeof(IOSCAesIv));
    memcpy(iv, (u8*)(&tid), sizeof(ESTitleId));
    if ( (aes_SwEncrypt((u8*)commonKey, iv, (u8*)titleKey, sizeof(IOSCAesKey), outKey)) < 0) 
        return ES_ERR_ENCRYPTION_FAILED;

    return rv;
}

/* ------------------------------------------------------------------------- */
/*                       Disk encryption functions                           */
/* ------------------------------------------------------------------------- */
static int
aes_SwEncryptWrapper(u8 *key, u8 *initVector, u8 *dataIn,
                     u32 bytes, u8 *dataOut);

static void
generateSuperBlock(u8* const inBuf, const u32 inBufSize,
                  u8* const h3Ptr, const u8* const titleKey,
                  u8*       outBuf, int *numOutBytes);

/*
 * Initialize an ESDiskAesShaHandle object for encryption.
 * Returns either ES_ERR_ENCRYPTION_FAILED or ES_ERR_OK
 */

int
ES_DiskEncryptContentReset(ESDiskAesShaHandle* handle, u16 inputContentIndex,
                           const u8* titleKey)
{
    u16 contentIndex;

    if (handle == NULL || titleKey == NULL) {
        return ES_ERR_ENCRYPTION_FAILED;
    }
    
    memset(handle, 0, sizeof(ESAesShaHandle));
    contentIndex = htons(inputContentIndex);
    memcpy(handle->iv, (u8*)(&contentIndex), sizeof(u16));
    SHA1Reset(&handle->sha);
    handle->titleKey = titleKey;
    handle->inbufSize = 0;
    memset(handle->h3Buf, 0, H3_SIZE);
    handle->h3Index = 0;
    return ES_ERR_OK;
}

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

/*
 * Encrypt the inbuf and write the output to outbuf.
 * inbuf:  pointer to the clear text buffer.
 * inSize:  # of bytes of clear text data in inbuf.
 *         Must be <= ES_AES_DISK_BUF_SIZE
 * outbuf: point to the cipher text buffer for output.
 * outSize: # of bytes availabe in output.
 *          Must be >= ES_AES_DISK_OUTPUT_BUF_SIZE
 * Returns the number of bytes written to outbuf, or a negative error code.
 */

int
ES_DiskEncryptContentUpdate(ESDiskAesShaHandle* handle, const u8* inbuf,
                            u32 inSize, u8* outbuf, u32 outSize)
{
    int         bytesEncrypted = 0;
    int         returnVal;


    if (   inSize > ES_AES_DISK_BUF_SIZE
        || outSize < ES_AES_DISK_OUTPUT_BUF_SIZE) {
        returnVal = ES_ERR_ENCRYPTION_FAILED;
        goto end;
    }

    if (handle->inbufSize + inSize >= ES_AES_DISK_BUF_SIZE) {
        u32     bytesToCopy;

        if (handle->h3Index >= H3_SIZE) {
            returnVal = ES_ERR_ENCRYPTION_FAILED;
            goto end;
        }
        bytesToCopy = ES_AES_DISK_BUF_SIZE - handle->inbufSize;
        memcpy(handle->inbuf + handle->inbufSize, inbuf, bytesToCopy);
        generateSuperBlock(handle->inbuf, ES_AES_DISK_BUF_SIZE,
                          handle->h3Buf + handle->h3Index, handle->titleKey,
                          outbuf, &bytesEncrypted);
        handle->h3Index += ES_HASH_SIZE;
        /*
         * Copy any remaining bytes back to the beginning of
         * the handle
         */
        handle->inbufSize = inSize - bytesToCopy;
        memcpy(handle->inbuf, inbuf + bytesToCopy, handle->inbufSize);
    }
    else {
        memcpy(handle->inbuf + handle->inbufSize, inbuf, inSize);
        handle->inbufSize += inSize;
    }
    returnVal = bytesEncrypted;

end:
    return(returnVal);

}

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

/*
 * Finalize the encryption.  Any remaininginput will be 
 * encrypted into outbuf.  The H4 hash is also written to "hash".
 * Outbuf must be at least ES_AES_DISK_OUTPUT_BUF_SIZE bytes in size.
 * Returns the number of bytes written to outbuf, or a negative error code.
 */

int ES_DiskEncryptContentFinal(ESDiskAesShaHandle* handle,
                               u8* outbuf, u32 outSize, u8* hash)
{
    int         bytesEncrypted = 0;
    SHA1Context context;
    int         returnVal;


    if (handle->inbufSize > 0) {
        if (handle->h3Index >= H3_SIZE) {
            returnVal = ES_ERR_ENCRYPTION_FAILED;
            goto end;
        }
        generateSuperBlock(handle->inbuf, handle->inbufSize,
                          handle->h3Buf + handle->h3Index, handle->titleKey,
                          outbuf, &bytesEncrypted);
        handle->h3Index += ES_HASH_SIZE;
    }
    returnVal = bytesEncrypted;
    /*
     * 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, handle->h3Buf, H3_SIZE);
    SHA1Result(&context, hash);
end:
    return(returnVal);
}


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

/*
 * Generate a encrypted super block.  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
 *
 * The H3 hash for this superblock is written using the h3Ptr.
 * 
 *
 * RETURNS: 
 *          
 */

static void
generateSuperBlock(u8* const inBuf, const u32 inBufSize,
                  u8* const h3Ptr, const u8* const titleKey,
                  u8*       outBuf, int *numOutBytes)
{
    SHA1Context context;
    u8          h0Digests[H0_PER_SUPERBLOCK * SHA1_DIGESTSIZE];
    u8          h1Digests[H1_PER_H2 * H2_PER_SUPERBLOCK * SHA1_DIGESTSIZE];
    u8          h2Digest[H2_PER_SUPERBLOCK * SHA1_DIGESTSIZE];
    u8          *inPtr, *h0Ptr, *h1Ptr, *h2Ptr;
    u8          hashSubBlock[SUBBLOCK_SIZE], *hashSubBlockPtr;
    u8          encryptedSubBlock[SUBBLOCK_SIZE];
    u8          encryptedDataBlock[DVD_DATA_BYTES_PER_BLOCK];
    u8          dataIv[ES_AES_IV_SIZE], hashIv[ES_AES_IV_SIZE];
    int         blocksToWrite;

    *numOutBytes = 0;

    if (inBufSize != DVD_DATA_BYTES_PER_SUPERBLOCK) {
        /* 
         * 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(inBuf + inBufSize, 0,
               DVD_DATA_BYTES_PER_SUPERBLOCK - inBufSize);
    }

    h0Ptr = h0Digests;
    inPtr = inBuf;


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

    /* 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;
    }

    /* 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;
    }

    /* Generate the H3 digest */
    SHA1Reset(&context);
    SHA1Input(&context, h2Digest, H2_PER_SUPERBLOCK * SHA1_DIGESTSIZE);
    SHA1Result(&context, h3Ptr);

    /* Write the H0, H1, and H2 digests, along with the data */
    h0Ptr = h0Digests;
    h1Ptr = h1Digests;
    inPtr = inBuf;

    blocksToWrite = inBufSize / DVD_DATA_BYTES_PER_BLOCK;
    if (blocksToWrite * DVD_DATA_BYTES_PER_BLOCK != inBufSize) {
        blocksToWrite++;
    }

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

        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;

        /* Encrypt the hashes */
        /* The hashIv is always 0 */
        memset(hashIv, 0, ES_AES_IV_SIZE);
        aes_SwEncryptWrapper((u8 *) titleKey, hashIv, hashSubBlock,
                              SUBBLOCK_SIZE, encryptedSubBlock);

        /* 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, ES_AES_IV_SIZE);
        /*
        printf ("(%d) dataIv: 0x%x 0x%x 0x%x 0x%x\n",
         timesCalled,
         * (u32 *) dataIv,
         * (u32 *) (dataIv + 4),
         * (u32 *) (dataIv + 8),
         * (u32 *) (dataIv + 12));
         */

        aes_SwEncryptWrapper((u8 *) titleKey, dataIv,
                             inPtr, DVD_DATA_BYTES_PER_BLOCK,
                             encryptedDataBlock);

        inPtr += DVD_DATA_BYTES_PER_BLOCK;

        /* Write hash subblock to output buffer */
        memcpy(outBuf + *numOutBytes, encryptedSubBlock, SUBBLOCK_SIZE);
        *numOutBytes += SUBBLOCK_SIZE;

        /* Write data subblocks to file */
        memcpy(outBuf + *numOutBytes, encryptedDataBlock,
               DVD_DATA_BYTES_PER_BLOCK );
        *numOutBytes += DVD_DATA_BYTES_PER_BLOCK;
    }
}

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

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

/* ------------------------------------------------------------------------- */
/*            End of disk encryption functions                               */
/* ------------------------------------------------------------------------- */
