#ident "$Id: dump_partition.c,v 1.6 2007/05/01 18:38:59 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.
 *
 */


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

/*
 * BROADWAY_REV is needed so that the E-ticket structures have the
 * same layout on Cygwin and Linux
 */
#define BROADWAY_REV

#include <ctype.h>
#include <getopt.h>
#include <inttypes.h>
#include <netinet/in.h>         // For htonl()
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.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 "md5.h"

#define AES_KEY_LENGTH          16



#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"help",            0, 0, 'h'},     /* Print usage */
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {0, 0, 0, 0}
};
#endif

static char* options = "ho:v";

void printMD5sum(const void* const ptr, const uint32_t numBytes);
void dumpPartition(const char* inputFileName, const off_t partitionOffset);

char            *ProgName;

static bool     Verbose = false;
/* ------------------------------------------------------------------------ */

void
usage()
{
    fprintf (stderr, "Usage: %s [options] partition\n", ProgName);
    fprintf(stderr,
        " -h, --help            - print usage message\n"
        " -v, --verbose         - print out messages as image is created\n");
}
/* ------------------------------------------------------------------------ */

/*
 * Process the program arguments.
 * OUTPUT:
 *              Sets the titleKey
 */

static void
processOptions(int argc, char* argv[], char **contentName, off_t *seekValue)
               
{
    while (1) {
#if defined(__CYGWIN__)
        int ch = getopt(argc, argv, options);
#else
        int ch = getopt_long_only(argc, argv, options, longOptions, 0);
#endif

        if (ch == -1)
            break;

        switch (ch) {

        case 'h':
            usage();
            exit(0);
            break;

        case 'v':
            Verbose = true;
            break;

        default:
            usage();
            exit(1);
        }
    }
    if (optind >= argc) {
        fprintf (stderr, "%s: Need content name\n", argv[0]);
        usage();
        exit(1);
    }
    *contentName = argv[optind];
}
/* ------------------------------------------------------------------------ */

int
main(int argc, char *argv[])
{
    char        *inputFileName;
    off_t       offsetToPartition;

    ProgName = argv[0];

    processOptions(argc, argv, &inputFileName, &offsetToPartition);

    dumpPartition(inputFileName, offsetToPartition);
    exit(0);
}

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

/*
 * Note: if there is an error, the file isn't closed before returning
 */
void
dumpPartition(const char* inputFileName, const off_t seekValue)
{
    partition_t          partition;
    FILE                *inFile;
    uint8_t             *tmdBytes = NULL;
    off_t               partitionStart;

    if ( (inFile = fopen(inputFileName, "rb")) == NULL) {
        printf ("Can't open file %s\n", inputFileName);
        return;
    }

    partitionStart = ftello(inFile);

    if (fread(&partition, sizeof(partition_t), 1, inFile) != 1) {
        printf ("Can't read partition structure\n");
        return;
    }
    printf ("Ticket MD5 sum: ");
    printMD5sum(&(partition.ticket), sizeof(ESTicket));
    printf ("\n");
    printf ("TMD Size: %d; TMD offset (word): %u\n",
             (unsigned int) ntohl(partition.tmdSize),
             (unsigned int) ntohl(partition.tmdOffset));

    tmdBytes = malloc(ntohl(partition.tmdSize));
    if (tmdBytes == NULL) {
        printf ("Malloc of Tmd bytes failed\n");
        goto end;
    }
    if (fseeko(inFile, partitionStart + (ntohl(partition.tmdOffset) << 2),
               SEEK_SET) == 1) {
        perror("fseeko");
        goto end;
    }
    if (fread(tmdBytes, ntohl(partition.tmdSize), 1, inFile) != 1) {
        printf ("Can't read partition structure\n");
        goto end;
    }
    printf ("TMD MD5 sum: ");
    printMD5sum(tmdBytes, ntohl(partition.tmdSize));
    printf ("\n");

    printf ("Encrypted area start (byte offset): 0x%x\n",
             (unsigned int) ntohl(partition.encryptedAreaOffset) << 2);

end:
    fclose(inFile);
    if (tmdBytes != NULL) {
        free(tmdBytes);
    }
} // dumpPartition

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

void
printMD5sum(const void* const ptr, const uint32_t numBytes)
{
    md5_state_t state;
    md5_byte_t digest[16];

    md5_init(&state);
    md5_append(&state, ptr, numBytes);
    md5_finish(&state, digest);

    for (int idx = 0; idx < 16; idx++) {
        printf("%02x", digest[idx]);
    }
}
