/*
 *               Copyright (C) 2005-2008, 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.
 *
 */

/*
 * Need to define this, or else on Cygwin the ticket and tmd
 * structures are laid out differently than on Linux
 */
#define BROADWAY_REV

#include <errno.h>
#include <getopt.h>
#include <inttypes.h>
#include <netinet/in.h>         
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>           
#include <unistd.h>

#include "aes.h"
#include "sha1.h"
#include "image_superblock.h"
#include "types.h"
#include "disk_format.h"
#include "estypes.h"
#include "devel_key.h"
#include "decrypt_common.h"
#include "getRoot.h"
#include "disk_common.h"
#include "tool_common.h"
#include "DF_Structs.h"

enum decryptStatus {DECRYPT_OK, END_OF_FILE, DECRYPT_ERROR};

typedef struct optionVals {
    char *diskFile;
    char *blockFile;
    bool insertBlock;
    bool fixHashes;
    int partitionNum;
    int blockNum;
} optionVals_t;

u8 inBuffer[BYTES_PER_BLOCK];
u8 outBuffer[BYTES_PER_BLOCK];
u8 h3Hashes[H3_SIZE];

static inline u32
blockNumToH2Index(const u32 blockNum)
{
    return ((blockNum >> 3) & 0x7);
}

static inline u8*
blockNumToH3Ptr(const u32 blockNum, const u8* const h3HashArray)
{
    u32    returnVal;

    returnVal = (u32) h3HashArray;
    returnVal += (blockNum >> 6) * SHA1_DIGESTSIZE;
    return ((u8 *) returnVal);
}


void
encryptBlock(u8 *readBuffer, u8 *writeBuffer, u8 *key)
{
    u8 dataIv[AES_IV_LENGTH], hashIv[AES_IV_LENGTH];

    memset(hashIv, 0, AES_IV_LENGTH);
    aes_SwEncryptWrapper((u8 *) key, hashIv, readBuffer,
                         1024 - H2_PAD_LENGTH, writeBuffer);
        
    memcpy(dataIv, writeBuffer + 1024 - 32 - 16, AES_IV_LENGTH);
    aes_SwEncryptWrapper((u8 *) key, dataIv, readBuffer + BYTES_PER_SUBBLOCK,
                         DATA_BYTES_PER_BLOCK, writeBuffer + BYTES_PER_SUBBLOCK);
}

/*
 * Calculate the hashes for a self-consistent disk block
 * NOTE: It only calculates and fills in hashes for the block. It
 * does not initialize other hashes which should be stored in the block
 */
void
hashBlock(u8 *readBuffer, u32 physBlockNum)
{
    u8 *dataPtr, *hashValuePtr;

    dataPtr = readBuffer + BYTES_PER_SUBBLOCK;
    hashValuePtr = readBuffer;

    for (int i = 0; i < DATA_SUBBLOCKS_PER_BLOCK; i++) {
        computeHash(dataPtr, BYTES_PER_SUBBLOCK,
                    hashValuePtr);
        dataPtr += BYTES_PER_SUBBLOCK;
        hashValuePtr += SHA1_DIGESTSIZE;
    }

    hashValuePtr = readBuffer + H1_HASH_OFFSET + ((physBlockNum % 8) * SHA1_DIGESTSIZE);
    computeHash(readBuffer, H0_HASH_LENGTH, hashValuePtr);

    hashValuePtr = readBuffer + H2_HASH_OFFSET
                   + (blockNumToH2Index(physBlockNum) * SHA1_DIGESTSIZE);
    computeHash(readBuffer + H1_HASH_OFFSET, H1_HASH_LENGTH,
                hashValuePtr);
}

int
verifyBlock(u8 *readBuffer, u32 physBlockNum, u8 *h3Hashes)
{
    u8 *dataPtr, *hashValuePtr;

    dataPtr = readBuffer + BYTES_PER_SUBBLOCK;
    hashValuePtr = readBuffer;

    /* Verify the data against the H0 Hashes */
    for (int i = 0; i < DATA_SUBBLOCKS_PER_BLOCK; i++) {
        if (verifyHashArray(dataPtr, BYTES_PER_SUBBLOCK,
                            hashValuePtr) == false) {
            fprintf (stderr, "Physical block %u subblock %d failed to verify against H0 Hash\n",
                     physBlockNum, i);
            return(DECRYPT_ERROR);
        }
        dataPtr += BYTES_PER_SUBBLOCK;
        hashValuePtr += SHA1_DIGESTSIZE;
    }

    /* Verify the H0 Hashes against the correct H1 */
    hashValuePtr = readBuffer + H1_HASH_OFFSET + ((physBlockNum % 8) * SHA1_DIGESTSIZE);
    if (verifyHashArray(readBuffer, H0_HASH_LENGTH, hashValuePtr) == false) {
        fprintf (stderr,
                 "Physical block %u's H0 hash failed to verify against H1 Hash\n", physBlockNum);
        return(DECRYPT_ERROR);
    } else {
        printf ("H0 Hashes verified\n");
    }

    /* Verify the H1 hashes against the correct H2 */
    hashValuePtr = readBuffer + H2_HASH_OFFSET
                   + (blockNumToH2Index(physBlockNum) * SHA1_DIGESTSIZE);
    if (verifyHashArray(readBuffer + H1_HASH_OFFSET, H1_HASH_LENGTH,
                        hashValuePtr) == false) {
        fprintf (stderr,
                "Physical block %u's H1 hash failed to verify against H2 Hash\n", physBlockNum);
        return(DECRYPT_ERROR);
    } else {
        printf ("H1 Hashes verified\n");
    }

    /* Verify the H2 hashes against the correct H3 */
    if (verifyHashArray(readBuffer + H2_HASH_OFFSET, H2_HASH_LENGTH,
                        blockNumToH3Ptr(physBlockNum, h3Hashes)) == false) {
        fprintf (stderr,
                "Physical block %u's H2 hash failed to verify against H3 Hash\n", physBlockNum);
        return(DECRYPT_ERROR);
    } else {
        printf ("H2 Hashes verified\n");
    }

    return(DECRYPT_OK);

}

int
decryptBlock(u8 *readBuffer, u8 *writeBuffer, const u8* const decryptKey)
{
    u8 dataIv[AES_IV_LENGTH], hashIv[AES_IV_LENGTH];

    memset(hashIv, 0, AES_IV_LENGTH);
    memcpy(dataIv, readBuffer + 1024 - 32 - 16, AES_IV_LENGTH);

    aes_SwDecryptWrapper((u8 *) decryptKey, hashIv, readBuffer,
                         1024 - H2_PAD_LENGTH, writeBuffer);
    aes_SwDecryptWrapper((u8 *) decryptKey, dataIv,
                         readBuffer + BYTES_PER_SUBBLOCK,
                         DATA_BYTES_PER_BLOCK, writeBuffer + BYTES_PER_SUBBLOCK);

    return(DECRYPT_OK);
}

void
usage(char *ProgName)
{
    fprintf (stderr, "Usage: %s [options] diskFile blockFile\n", ProgName);
    fprintf (stderr,
             " -p, - partition number\n"
             " -b, - block offset\n"
             " -i, - insert the block into image. If not set, then program dumps the block into the file\n"
             " -f  - fix (recalculate) the hashes from the input block. If not set, then block is inserted as is\n");
    fprintf (stderr, "\nDumps a disk block after decryption, or inserts a disk block.\n");
}

static char     *options = "b:p:if";

static void
processOptions(int argc, char* argv[], optionVals_t *optionVals)
{

    optionVals->diskFile  = NULL;
    optionVals->blockFile = NULL;
    optionVals->fixHashes = false;
    optionVals->insertBlock = false;
    optionVals->partitionNum = 0;
    optionVals->blockNum = 0;

    while (1) {
        int ch = getopt(argc, argv, options);
        if (ch == -1)
            break;

        switch (ch) {
        case 'p':
            optionVals->partitionNum = atoi(optarg);
            break;
        case 'f':
            optionVals->fixHashes = true;
            break;
        case 'i':
            optionVals->insertBlock = true;
            break;
        case 'b':
            optionVals->blockNum = atoi(optarg);
            break;
        default:
            usage(argv[0]);
            exit(1);
        }
    }
    if (argc - optind < 1) {
        fprintf (stderr, "%s: Need input and output file names\n", argv[0]);
        usage(argv[0]);
        exit(1);
    }
    optionVals->diskFile = argv[optind];
    optionVals->blockFile = argv[optind+1];

} 

char *ProgName;
int Verbose = 1;

int
main(int argc, char *argv[])
{
    optionVals_t optionVals;
    FILE *diskFile = NULL, *blockFile = NULL;
    DF_GameTOC          gameToc;
    DF_PartitionInfo    *partitionInfoArray = NULL;
    u32                 numPartitions, partitionInfoRawOffset;
    off_t               partitionInfoOffset;
    int partitionType;
    off_t partitionAddr;
    int i;
    partition_t partition;
    off_t partitionDataStart;
    u32 lengthToDataArea;

    ProgName = argv[0];
    processOptions(argc, argv, &optionVals);

    if ((diskFile = fopen(optionVals.diskFile, "rb+")) == NULL) {
        fprintf (stderr, "%s: Can't open file %s for reading - exit\n",
                 ProgName, optionVals.diskFile);
        exit(1);
    }

    /*
     * Read TOC
     */
    fseek(diskFile, GLOBAL_TOC_OFFSET + RVM_HEADER_LENGTH, SEEK_SET);
    if (fread(&gameToc, sizeof(DF_GameTOC), 1, diskFile) != 1) {
        fprintf(stderr, "%s: Can't read game TOC from file\n", ProgName);
        goto end;
    }

    numPartitions = ntohl(gameToc.numGamePartitions);
    partitionInfoRawOffset = UNDO_DISK_ADDR(gameToc.partitionInfos);
    partitionInfoOffset = partitionInfoRawOffset + RVM_HEADER_LENGTH;
    printf ("Number of partitions: %u\n", numPartitions);

    partitionInfoArray = (DF_PartitionInfo *) malloc(sizeof(DF_PartitionInfo) * numPartitions);
    if (partitionInfoArray == NULL) {
        fprintf(stderr, "%s: Can't allocate space for partition infos\n",
                ProgName);
        goto end;
    }
    if (fseek(diskFile, partitionInfoOffset, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition info offset failed\n",
                 ProgName);
        goto end;
    }
    if (fread(partitionInfoArray, sizeof(DF_PartitionInfo),
              numPartitions, diskFile) != numPartitions) {
        fprintf(stderr, "%s: Can't read partition infos from file\n", ProgName);
        goto end;
    }

    if (optionVals.partitionNum < numPartitions) {
        i = optionVals.partitionNum;
        partitionType = ntohl(partitionInfoArray[i].type);
        partitionAddr = (off_t) (partitionInfoArray[i].gamePartition);
        partitionAddr = UNDO_DISK_ADDR(partitionAddr);
        printf("Partition %d type %d offset 0x%llx\n", i, partitionType, partitionAddr);
    } else {
        fprintf(stderr, "Partition out of range, max is %d\n", numPartitions-1);
        goto end;
    }

    /*
     * Read partition header
     */
    if (fseek(diskFile, partitionAddr + RVM_HEADER_LENGTH, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition offset failed\n", ProgName);
        goto end;
    }
    if (fread(&partition, sizeof(partition_t), 1, diskFile) != 1) {
        fprintf(stderr, "%s: Can't read partition structure %d from file\n", ProgName, i);
        goto end;
    }

    /*
     * Read H3
     */
    off_t h3HashOffset = UNDO_DISK_ADDR(partition.h3HashesOffset);
    if (fseek(diskFile, partitionAddr + h3HashOffset + RVM_HEADER_LENGTH, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition offset failed\n", ProgName);
        goto end;
    }
    if (fread(h3Hashes, H3_SIZE, 1, diskFile) != 1) {
        fprintf(stderr, "%s: Can't read Hashes from file\n", ProgName);
        goto end;
    }
    
    /*
     * Find block
     */
    lengthToDataArea = UNDO_DISK_ADDR((off_t)partition.encryptedAreaOffset);
    partitionDataStart = partitionAddr + lengthToDataArea + RVM_HEADER_LENGTH;
    off_t offset = (long long) partitionDataStart + (long long) (optionVals.blockNum) * 32LL * 1024LL;
    if (fseeko(diskFile, offset, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to block start failed\n",
                 ProgName);
        goto end;
    }

    if (optionVals.insertBlock == false) {
        /*
         * Case for dumping the block out, unencrypted
         */
        if ((blockFile = fopen(optionVals.blockFile, "wb")) == NULL) {
            fprintf (stderr, "%s: Can't open file %s for writing - exit\n",
                     ProgName, optionVals.blockFile);
            exit(1);
        }

        if (fread(inBuffer, BYTES_PER_BLOCK, 1, diskFile) == 1) {
            memcpy(outBuffer, inBuffer, BYTES_PER_BLOCK);
            decryptBlock(inBuffer, outBuffer, develKey);
            verifyBlock(outBuffer, optionVals.blockNum, h3Hashes);
        } else {
            fprintf(stderr, "%s: Can't read block %d from disk file\n", ProgName, optionVals.blockNum);
            exit(1);
        }
        fwrite(outBuffer, BYTES_PER_BLOCK, 1, blockFile);
    } else {
        if ((blockFile = fopen(optionVals.blockFile, "rb")) == NULL) {
            fprintf (stderr, "%s: Can't open file %s for reading\n", ProgName, optionVals.blockFile);
            exit(1);
        }
        if (fread(inBuffer, BYTES_PER_BLOCK, 1, blockFile) != 1) {
            fprintf(stderr, "%s: Can't read block from file %s\n", ProgName, optionVals.blockFile);
            exit(1);
        }
        if (optionVals.fixHashes) {
            /*
             * Lets try to redo hashes
             */
            hashBlock(inBuffer, optionVals.blockNum);
        }
        encryptBlock(inBuffer, outBuffer, develKey);

        if (fseeko(diskFile, offset, SEEK_SET) == -1) {
            fprintf (stderr, "%s: Seeking to block start failed\n", ProgName);
            goto end;
        }
        if (fwrite(outBuffer, BYTES_PER_BLOCK, 1, diskFile) != 1) {
            fprintf(stderr, "%s: Can't insert block %d into file %s\n", ProgName, optionVals.blockNum, optionVals.diskFile);
            exit(1);
        }
    }

 end:
    if (blockFile != NULL) {
        fclose(blockFile);
    }
    if (diskFile != NULL) {
        fclose(diskFile);
    }
    exit(0);
}
