#ident "$Id: decomp_disk.c,v 1.24.32.1 2009/03/24 23:03:37 cnguyen 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.
 *
 */

/*
 * Program to decompose disk images and rvl.bin files.
 *
 * This code is partially derived from Nintendo's makeRVTR program.
 *
 */


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

/*
 * 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 <netinet/in.h>         // For ntohl()
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>            // For rindex()
#include <sys/types.h>          // For off_t and stat
#include <sys/stat.h>           // For stat()
#include <unistd.h>

// Declare strdup rathern than define __USE_SVID or __USE_BSD on
// Linux FC 3 systems.
extern char *strdup(const char *s);

#include "types.h"
#include "disk_format.h"
#include "estypes.h"
#include "disk_common.h"
#include "decomp_common.h"
#include "masterimage.h"        /* From Nintendo */
#include "master_common.h"      /* From Nintendo */
#include "DF_structs.h"

#define FILE_NAME_MAX    256
#define PATH_LEN        1024
#define COMMAND_LEN     2048
#define IO_BUF_LENGTH  (64 * 1024)
#define PROGRAM_VERSION "0.10"

#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"disk",            0, 0, 'd'},     /* Input is disk image */
    {"force",           0, 0, 'f'},     /* Force extraction */
    {"help",            0, 0, 'h'},     /* Print usage */
    {"print",           0, 0, 'p'},     /* print file meta data */
    {"rvl",             0, 0, 'r'},     /* Input is rvl.bin */
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {"extract",         0, 0, 'x'},     /* Extract partitions */
    {0, 0, 0, 0}
};
#endif

static char* options = "dfhprvx";
char            *ProgName;
bool            Verbose = false;

typedef struct optionVals {
    char        *inputName;
    bool        diskImageIsInput;
    bool        rvlBinIsInput;
    bool        extract;
    bool        forceExtraction;
    bool        print;
} optionVals_t;

const char* partitionTypeToExt[] = {"game", "up", "game"};

void usage();
bool decomposeSecurityRegion(const optionVals_t* const optionVals,
                             FILE  *inFile,
                             const s64 securityOffset,
                             const char* const baseName);
bool printPartition(FILE *inFile, const off_t partitionAddr,
                    const s64 diskOffsetToFile, const char* const lineStart);
void printEticket(const ESTicket* const ticket, const char* const lineStart);
void printTmd(const ESTitleMeta* tmd, const char* const lineStart);
bool printCerts(const void* certList,
                const u32 certListSize, const char* const lineStart);
void determineBaseName(const char* const inputName, char *baseName);
bool extractPartitions(const optionVals_t* const optionVals,
                       FILE *inFile, const u32 numPartitions,
                       const DF_PartitionInfo* const PartitionInfoArray,
                       const s64 diskOffsetToFile, const char* const baseName);
bool fileSize(const char* const fileName, off_t *fileSize);
bool sliceFile(const char* outputName, FILE *inFile, const off_t sliceStart,
               const off_t sliceLength);
char *accessRightsToStr(const u32 accessRights);
char *contentTypeToStr(const u16 contentType);
char *titleTypeToStr(const ESTitleType titleType);
bool dumpDiskBeginning(const optionVals_t* const optionVals,
                       FILE *inFile, const s64 diskOffsetToFile);
char *limitTypeToStr(const u32 limitType);

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

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

void
processOptions(int argc, char* argv[], optionVals_t* const optionVals)
{
    ProgName = argv[0];

    // Default values
    optionVals->inputName               = NULL;
    optionVals->diskImageIsInput        = false;
    optionVals->rvlBinIsInput           = false;
    optionVals->extract                 = false;
    optionVals->forceExtraction         = false;
    optionVals->print                   = false;


    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 'd':
            optionVals->diskImageIsInput = true;
            break;

        case 'f':
            optionVals->forceExtraction = true;
            break;

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

        case 'p':
            optionVals->print = true;
            break;

        case 'r':
            optionVals->rvlBinIsInput = true;
            break;

        case 'v':
            Verbose = true;
            break;

        case 'x':
            optionVals->extract = true;
            break;

        default:
            fprintf (stderr, "Unknown option '%c' - exit\n", ch);
            usage();
            exit(1);
        }
    }
    if (optind >= argc) {
        fprintf (stderr, "%s: Need input file name\n", ProgName);
        usage();
        exit(1);
    }
    else {
        optionVals->inputName = argv[optind];
    }
    if (   optionVals->rvlBinIsInput == false 
        && optionVals->diskImageIsInput == false) {
        fprintf(stderr, "%s: Must specify type of input\n", ProgName);
        usage();
        exit(1);
    }
    if (   optionVals->print   == false
        && optionVals->extract == false) {
        fprintf(stderr, "%s: Must specify either -p or -x\n", ProgName);
        usage();
        exit(1);
    }
} // processOptions
/* ------------------------------------------------------------------------ */

void
usage()
{
    fprintf (stderr, "%s version %s %s\n", ProgName,
             PROGRAM_VERSION, __DATE__);
    fprintf (stderr, "Usage: %s [options] input_file_name\n", ProgName);
    fprintf (stderr,
        " Options:\n"
        " -d, --disk            - input is disk image file\n"
        " -h, --help            - print usage message\n"
        " -p, --print           - print file meta data\n"
        " -r, --rvl_bin         - input is an rvl.bin file\n"
        " -v, --verbose         - print out messages\n"
        " -x, --extract         - extract partitions\n"
        "\n");

}
/* ------------------------------------------------------------------------ */

int
main(int argc, char *argv[])
{
    optionVals_t        optionVals;
    FILE                *inputFile = NULL;
    char                baseName[FILE_NAME_MAX];
    int                 exitValue = -1;
    s64                 diskOffsetToFile;

    ProgName = argv[0];

    processOptions(argc, argv, &optionVals);

    if (Verbose) {
        printf ("%s version %s %s\n", ProgName, PROGRAM_VERSION, __DATE__);
    }

    if ((inputFile = fopen(optionVals.inputName, "rb")) == NULL) {
        fprintf (stderr, "%s: Can't open file %s for reading - exit\n",
                 ProgName, optionVals.inputName);
        exit(1);
    }
    if (optionVals.rvlBinIsInput) {
        diskOffsetToFile = GLOBAL_TOC_OFFSET;
    }
    else if (optionVals.diskImageIsInput) {
        diskOffsetToFile = -RVM_HEADER_LENGTH;
    }
    else {
        fprintf(stderr, "%s: Input type isn't defined - exit\n", ProgName);
        usage();
        exit(1);
    }

    if (optionVals.extract) {
        determineBaseName(optionVals.inputName, baseName);
    }

    if (optionVals.diskImageIsInput && optionVals.print) {
        if (dumpDiskBeginning(&optionVals, inputFile,
                              diskOffsetToFile) == false) {
            fprintf(stderr, "Printing disk beginning failed - exit\n");
            goto end;
        }
    }

    if (optionVals.rvlBinIsInput) {
        decomposeSecurityRegion(&optionVals, inputFile,
                                diskOffsetToFile, baseName);
    }
    else if (optionVals.diskImageIsInput) {
        char    outputName[FILE_NAME_MAX];
        FILE    *unencryptFile;

        if (optionVals.print == false) {
            /* Write out the unencrypted/non-security part */
            sprintf(outputName, "%s.unencrypt", baseName);
            if ( (unencryptFile = fopen (outputName, "wb")) == NULL) {
                fprintf(stderr, "%s: Can't open file %s for writing\n",
                        ProgName, outputName);
                goto end;
            }
            if (copyPartialBinFileToOutFile(unencryptFile,
                                            optionVals.inputName,
                                            0,
                                            GLOBAL_TOC_OFFSET + RVM_HEADER_LENGTH) == false) {
                fprintf(stderr, "%s: Extract unencrypted part failed - exit\n",
                        ProgName);
                goto end;
            }
            if (fclose(unencryptFile) != 0) {
                fprintf(stderr, "%s: Can't close file %s\n",
                        ProgName, outputName);
                goto end;
            }
        }
        if (fseeko(inputFile, (off_t) GLOBAL_TOC_OFFSET + RVM_HEADER_LENGTH,
                   SEEK_SET) == -1) {
            fprintf (stderr, "%s: Seeking to partition offset failed\n",
                     ProgName);
            goto end;
        }
        decomposeSecurityRegion(&optionVals, inputFile, diskOffsetToFile,
                                baseName);
    }

    exitValue = 0;
end:
    if (inputFile != NULL) {
        fclose(inputFile);
    }

    exit(exitValue);
}


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

bool
dumpDiskBeginning(const optionVals_t* const optionVals,
                  FILE *inFile, const s64 diskOffsetToFile)
{
    bool                returnVal = false;
    DVDDiskId           diskId;
    DVDDiskInfo         diskInfo;

    if (fseeko(inFile, - diskOffsetToFile, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition offset failed\n",
                 ProgName);
        goto end;
    }
    if (fread(&diskId, sizeof(diskId), 1, inFile) != 1) {
        fprintf(stderr, "%s: Can't read DVD Disk Id from file\n", ProgName);
        goto end;
    }


    printf ("*** Disk Header ***\n");
    printf ("Game name:       ");
    for (int i = 0; i < 4; i++) {
        putchar(diskId.gameName[i]);
    }
    putchar ('\n');

    printf ("Company:         ");
    for (int i = 0; i < 2; i++) {
        putchar(diskId.company[i]);
    }
    putchar ('\n');
    printf ("Disk type:       ");
    if (ntohl(diskId.rvlMagic) == REVOLUTION_MAGIC) {
        printf ("Revolution\n");
    }
    else if (ntohl(diskId.gcMagic) == GAMECUBE_MAGIC) {
        printf ("GameCube\n");
    }
    else {
        printf ("Unknown\n");
    }

    /* Dump out DiskInfo structure */

    if (fseeko(inFile, DISK_INFO_OFFSET - diskOffsetToFile, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition offset failed\n",
                 ProgName);
        goto end;
    }
    if (fread(&diskInfo, sizeof(DVDDiskInfo), 1, inFile) != 1) {
        fprintf(stderr, "%s: Can't read DVD disk info from file\n", ProgName);
        goto end;
    }
    printf ("Long game name:  %s\n", diskInfo.gameNameLong);
    printf ("Hashing:         ");
    if (diskInfo.noHash == 0) {
        printf ("ON\n");
    }
    else {
        printf ("OFF\n");
    }
    printf ("Encryption:      ");
    if (diskInfo.noEncryption == 0) {
        printf ("ON\n");
    }
    else {
        printf ("OFF\n");
    }
    printf ("************\n");
        
    returnVal = true;

end:
    return (returnVal);
} // dumpDiskBeginning
/* ------------------------------------------------------------------------ */

/*
 * INPUTS:
 *          inFile           - input file.  Current offset points
 *                             to table of contents.
 *          diskOffsetToFile - at what offset in the disk image is
 *                             the input file located.
 */


bool
decomposeSecurityRegion(const optionVals_t* const optionVals,
                        FILE  *inFile,
                        const s64 diskOffsetToFile,
                        const char* const baseName)
{
    bool                returnVal = false;
    DF_GameTOC          gameToc;
    DF_PartitionInfo    *partitionInfoArray = NULL;
    u32                 numPartitions, partitionInfoRawOffset;
    off_t               partitionInfoOffset;


    if (fread(&gameToc, sizeof(DF_GameTOC), 1, inFile) != 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 - diskOffsetToFile;

    if (optionVals->print) {
        printf ("Number of partitions: %u\n", numPartitions);
        printf (" -> partitionInfoRawOfs: 0x%08x partitionInfoOfs:0x%08x\n", 
            partitionInfoRawOffset, (u32)partitionInfoOffset);
    }

    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 (fseeko(inFile, partitionInfoOffset, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition info offset failed\n",
                 ProgName);
        goto end;
    }
    if (fread(partitionInfoArray, sizeof(DF_PartitionInfo),
              numPartitions, inFile) != numPartitions) {
        fprintf(stderr, "%s: Can't read partition infos from file\n", ProgName);
        goto end;
    }
    if (optionVals->print) {
        printf ("Partition info structs:\n");
        for (int i = 0; i < numPartitions; i++) {
            u32               partitionType;
            const char        *partitionTypeString;

            partitionType = ntohl(partitionInfoArray[i].type);
            if (partitionType < NumPartitionTypes) {
                partitionTypeString = partitionTypeToString[partitionType];
            }
            else {
                partitionTypeString = "ERROR: OUT OF RANGE";
            }
            printf ("Partition %d: Type: %u (%s);"
                     " Disk address (byte): 0x%llx\n",
                     i, partitionType, partitionTypeString,
                     UNDO_DISK_ADDR(partitionInfoArray[i].gamePartition));
        }
        for (int i = 0; i < numPartitions; i++) {
            u32         partitionType;
            off_t       gamePartitionAddr;

            partitionType = ntohl(partitionInfoArray[i].type);


            printf ("Partition %d details:\n", i);
            gamePartitionAddr = (off_t) (partitionInfoArray[i].gamePartition);
            gamePartitionAddr = UNDO_DISK_ADDR(gamePartitionAddr);


            if (optionVals->print) {
                printPartition(inFile, gamePartitionAddr,
                               diskOffsetToFile, "\t");
            }
        }
    }
    if (optionVals->extract) {
        FILE    *TocFile;
        char    TocFileName[FILE_NAME_MAX];

        /* Write out the table of contents */
        sprintf(TocFileName, "%s.TOC", baseName);
        if ( (TocFile = fopen (TocFileName, "wb")) == NULL) {
            fprintf(stderr, "%s: Can't open file %s for writing\n",
                    ProgName, TocFileName);
            goto end;
        }
        if (copyPartialBinFileToOutFile(TocFile, optionVals->inputName,
                                        GLOBAL_TOC_OFFSET + RVM_HEADER_LENGTH,
                                        UNDO_DISK_ADDR(partitionInfoArray[0].gamePartition) - GLOBAL_TOC_OFFSET) == false) {

            fprintf(stderr, "%s: Can't extract TOC from file %s - exit\n",
                    ProgName, TocFileName);
            goto end;
        }
        if (fclose(TocFile) != 0) {
            fprintf(stderr, "%s: Can't close file %s\n", ProgName, TocFileName);
            goto end;
        }
        extractPartitions(optionVals, inFile, numPartitions,
                          partitionInfoArray, diskOffsetToFile, baseName);
    }

    returnVal = true;

end:
    if (partitionInfoArray == NULL) {
        free (partitionInfoArray);
    }
    return(returnVal);
}

/* ------------------------------------------------------------------------ */
bool
extractPartitions(const optionVals_t* const optionVals,
                  FILE *inFile,
                  const u32 numPartitions,
                  const DF_PartitionInfo* const partitionInfoArray,
                  const s64 diskOffsetToFile,
                  const char* const baseName)
{
    bool        returnVal = false;
    off_t       fileLength, netFileLength;
    off_t       *partitionLengths;

    if (fileSize(optionVals->inputName, &fileLength) == false) {
        fprintf(stderr, "%s: Can't get length of file %s - exit\n",
                ProgName, optionVals->inputName);
        goto end;
    }
    netFileLength = fileLength + diskOffsetToFile;

    partitionLengths = (off_t *) malloc (sizeof(off_t) * numPartitions);
    if (partitionLengths == NULL) {
        fprintf(stderr, "%s: Allocation of memory for"
                " partition lengths failed\n", ProgName);
        goto end;
    }
    if (readPartitionLengths(inFile, optionVals->inputName, numPartitions,
                             partitionInfoArray, diskOffsetToFile,
                             partitionLengths) == false) {
        goto end;
    }

    for (int i = 0; i < numPartitions; i++) {
        partition_t     partition;
        u32             partitionType;
        off_t           partitionAddr, partitionDataStart;
        off_t           lengthToDataArea;
        u64             partitionDataLength;
        char            outputName[FILE_NAME_MAX];

        partitionType = ntohl(partitionInfoArray[i].type);

        partitionAddr = (off_t) (partitionInfoArray[i].gamePartition);
        partitionAddr = UNDO_DISK_ADDR(partitionAddr);


        if (fseeko(inFile, partitionAddr - diskOffsetToFile, SEEK_SET) == -1) {
            fprintf (stderr, "%s: Seeking to partition offset failed\n",
                     ProgName);
            goto end;
        }
        if (fread(&partition, sizeof(partition_t), 1, inFile) != 1) {
            fprintf(stderr, "%s: Can't read partition structure %d from file\n",
                    ProgName, i);
            goto end;
        }
        lengthToDataArea = UNDO_DISK_ADDR((off_t)partition.encryptedAreaOffset);
        partitionDataStart = partitionAddr + lengthToDataArea;
                            
        partitionDataLength = ((u64) ntohl(partition.partDataLengthWords)) << 2;
        /*
         * Partition length of 0 means partition was generated before
         * field was defined.
         * Partitions are also always a multiple of 32K, so check for
         * that as well.
         * If partition length isn't usable, use the start of the
         * next partition as the end of the current partition,
         * or the remaining length of the file.
         */
        if (partitionDataLength == 0 || partitionDataLength & 0x7fff) {
            if (i < numPartitions - 1) {
                off_t nextPartitionStart;

                nextPartitionStart = UNDO_DISK_ADDR(partitionInfoArray[i + 1].gamePartition);
                partitionDataLength = nextPartitionStart -  partitionDataStart;
            }
            else {
                if (netFileLength <= partitionDataStart) {
                    printf("%s: File %s does not contain the data"
                            " for partition %d.\n",
                            ProgName, optionVals->inputName, i);
                    printf("%s: Extraction of partition %d and"
                           " beyond not done.\n", ProgName, i);
                    break;
                }
                partitionDataLength = netFileLength - partitionDataStart;
            }
        }
        if (Verbose) {
            printf ("Partition #%d length: %llu (0x%llx) bytes\n",
                     i, partitionDataLength, partitionDataLength);
        }
        if (partitionDataStart + partitionDataLength > netFileLength) {
            s64         overage;

            overage = partitionDataStart + partitionDataLength - netFileLength;
            printf("%s: File %s does not contain enough data for partition %d.\n",
                    ProgName, optionVals->inputName, i);
            printf("%s: File needs 0x%llx (%lld) more bytes.\n",
                    ProgName, overage, overage);
            printf ("%s: Data start: 0x%llx; Length: 0x%llx;"
                    " netFileLength: 0x%llx\n", ProgName,
                    partitionDataStart, partitionDataLength, netFileLength);
            if (optionVals->forceExtraction == false) {
                printf("%s: Extraction of partition %d and beyond not done.\n",
                        ProgName, i);
                break;
            }
            else {
                partitionDataLength = netFileLength - partitionDataStart;
            }
        }
        snprintf (outputName, sizeof(outputName),
                  "%s.%s.%d", baseName, partitionTypeToExt[partitionType], i);
        if (Verbose) {
            printf ("Extracting partition #%d to %s...\n", i, outputName);
        }
        if (sliceFile(outputName, inFile,
                      partitionAddr - diskOffsetToFile,
                      lengthToDataArea + partitionDataLength) == false) {
            printf("%s: Extraction of partition %d failed\n", ProgName, i);
            goto end;
        }
        if (i < numPartitions - 1) {
            off_t       nextPartitionAddr, endPartitionAddr;

            nextPartitionAddr = (off_t) UNDO_DISK_ADDR(partitionInfoArray[i + 1].gamePartition);
            endPartitionAddr =  partitionAddr + lengthToDataArea
                                + partitionDataLength;
            if (nextPartitionAddr > endPartitionAddr) {
                snprintf (outputName, sizeof(outputName),
                          "%s.pad.%d", baseName, i);
                if (sliceFile(outputName, inFile,
                          endPartitionAddr - diskOffsetToFile,
                          nextPartitionAddr - endPartitionAddr) == false) {
                    printf("%s: Extraction of partition %d-%d pad failed\n",
                            ProgName, i, i+1);
                    goto end;;
                }
            }
        }       // if (i < numPartitions)
    }           // for
    returnVal = true;

end:
    return(returnVal);
} // extractPartitions

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

/*
 * INPUT:
 *         inFile - 
 */
bool 
printPartition(FILE *inFile, const off_t partitionAddr,
               const s64 diskOffsetToFile, const char* const lineStart)
{
    partition_t         partition;
    bool                returnVal = false;
    ESTitleMeta         *tmd = NULL;
    void                *certBlob = NULL;
    u64                 partDataLengthBytes;
    u32                 h3StartAddr;

    if (fseeko(inFile, partitionAddr - diskOffsetToFile, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition offset failed\n",
                 ProgName);
        goto end;
    }
    if (fread(&partition, sizeof(partition_t), 1, inFile) != 1) {
        fprintf(stderr, "%s: Can't read partition from input file\n", ProgName);
        goto end;
    }
    if (partition.h3HashesOffset == 0) {
        printf ("%sUnencrypted partition\n", lineStart);
    }
    else {
        h3StartAddr = (partitionAddr-diskOffsetToFile) +
                      (ntohl(partition.h3HashesOffset) << 2);
        printf ("%sEncrypted partition\n", lineStart);
        printf ("%sH3 ofs: 0x%08x, H3 start addr: 0x%08x, end addr: 0x%08x\n",
            lineStart, ntohl(partition.h3HashesOffset),
            h3StartAddr, h3StartAddr + H3_SIZE - 1);
    }

    partDataLengthBytes =  ((u64) (ntohl(partition.partDataLengthWords))) << 2;
    printf ("%sPartition data area length: %llu (0x%llx) bytes\n",
             lineStart, partDataLengthBytes, partDataLengthBytes);

    printEticket(&(partition.ticket), lineStart);

    /* Read and print out TMD */
    tmd = readTmdFromPartition(inFile, &partition,
                               partitionAddr, diskOffsetToFile);
    if (tmd == NULL) {
        goto end;
    }
    printf ("%sTMD size: %u; offset from partition start: 0x%llx\n",
             lineStart, (unsigned int) ntohl(partition.tmdSize),
             UNDO_DISK_ADDR(partition.tmdOffset));
    printTmd(tmd, lineStart);

    /* Read and print out certificates */
    certBlob = readCertBlobFromPartition(inFile, &partition,
                                         partitionAddr, diskOffsetToFile);
    if (certBlob == NULL) {
        goto end;
    }
    printCerts(certBlob, ntohl(partition.certBlobSize), lineStart);

    returnVal = true;
end:
    if (tmd != NULL) {
        free(tmd);
    }
    if (certBlob != NULL) {
        free(certBlob);
    }
    return(returnVal);
} // printPartition

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

void
printEticket(const ESTicket* ticket, const char* const lineStart)
{
    bool        hasLimit = false;

    printf ("%sTicket size: %u\n", lineStart, sizeof(ESTicket));
    printf ("%sTicket issuer: %s\n", lineStart, ticket->sig.issuer);
    printf ("%sTicket title id: 0x%llx\n", lineStart, ntohll(ticket->titleId));

    for (int i = 0; i < ES_MAX_LIMIT_TYPE; i++) {
        if (ticket->limits[i].code != 0) {
            if (hasLimit == false) {
                hasLimit = true;
                printf ("%sTicket limits:\n", lineStart);
            }
            printf ("%s\t%s: %u\n", lineStart,
                    limitTypeToStr(ntohl(ticket->limits[i].code)),
                    (u32) ntohl(ticket->limits[i].limit));
        }
    }
    if (hasLimit == false) {
        printf ("%sTicket limits: NONE\n", lineStart);
    }
}

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


void
printTmd(const ESTitleMeta* tmd, const char* const lineStart)
{
    u32         accessRights;
    char        *accessRightsStr;
    u16         numContents;

    printf ("%sTMD:\n", lineStart);
    printf ("%s\tTitle Id : 0x%llx; Group ID: 0x%x\n", lineStart,
             ntohll(tmd->head.titleId), ntohs(tmd->head.groupId));
    printf ("%s\tTitle Type : 0x%x (%s)\n", lineStart,
             (unsigned int) ntohl(tmd->head.type),
             titleTypeToStr(ntohl(tmd->head.type)));
    printf ("%s\tRequired system software version: 0x%llx (%llu)\n", lineStart,
             ntohll(tmd->head.sysVersion), (ntohll(tmd->head.sysVersion)) & 0xFFFFFFFF);
    printf ("%s\tTitle version: 0x%hx\n", lineStart,
             ntohs(tmd->head.titleVersion));
    accessRights    = ntohl(tmd->head.accessRights);
    accessRightsStr = accessRightsToStr(accessRights);
    if (accessRightsStr != NULL) {
        printf ("%s\tAccess rights: 0x%x (%s)\n", lineStart,
                 accessRights, accessRightsStr);
        free(accessRightsStr);
    }
    else {
        printf ("%s\tAccess rights: 0x%x (Rights to string failed)\n",
                 lineStart, accessRights);
    }
    numContents = ntohs(tmd->head.numContents);
    printf ("%s\tNumber of contents: %u\n", lineStart, numContents);
    for (int i = 0; i < numContents; i++) {
        printf ("%s\tContent #%i:\n", lineStart, i);
        printf ("%s\t\tId: 0x%x; Index: 0x%x; Type: 0x%hx (%s)\n", lineStart,
                (unsigned int) ntohl(tmd->contents[i].cid),
                (unsigned int) ntohl(tmd->contents[i].index),
                ntohs(tmd->contents[i].type),
                contentTypeToStr(ntohs(tmd->contents[i].type)));
        printf ("%s\t\tSize: 0x%llx (%llu)\n", lineStart,
                ntohll(tmd->contents[i].size), ntohll(tmd->contents[i].size));
    }
} // printTmd

/* ------------------------------------------------------------------------ */
char *
contentTypeToStr(const u16 contentType)
{
    char        tmpBuf[512];
    bool        useStrcat = false;

    if (contentType & ES_CONTENT_TYPE_NG_EXE) {
        strcpy(tmpBuf, "NG_EXE ");
        useStrcat = true;
    }
    if (contentType & ES_CONTENT_TYPE_SHARED) {
        if (useStrcat) {
            strcat(tmpBuf, "SHARED ");
        }
        else {
            strcpy(tmpBuf, "SHARED ");
            useStrcat = true;
        }
    }
    if (contentType & ES_CONTENT_TYPE_DISC) {
        if (useStrcat) {
            strcat(tmpBuf, "DISC ");
        }
        else {
            strcpy(tmpBuf, "DISC ");
            useStrcat = true;
        }
    }
    if (useStrcat == false) {
        strcpy(tmpBuf, "NONE");
    }
    return(strdup(tmpBuf));
} // contentTypeToStr
/* ------------------------------------------------------------------------ */
char *
titleTypeToStr(const ESTitleType titleType)
{
    char        tmpBuf[512];
    bool        useStrcat = false;

    if (titleType & ES_TITLE_TYPE_NC_TITLE) {
        strcpy(tmpBuf, "NC_TITLE ");
        useStrcat = true;
    }
    if (titleType & ES_TITLE_TYPE_NG_TITLE) {
        if (useStrcat) {
            strcat(tmpBuf, "NG_TITLE ");
        }
        else {
            strcpy(tmpBuf, "NG_TITLE ");
            useStrcat = true;
        }
    }
    if (titleType & ES_TITLE_TYPE_DS_TITLE) {
        if (useStrcat) {
            strcat(tmpBuf, "DS_TITLE ");
        }
        else {
            strcpy(tmpBuf, "DS_TITLE ");
            useStrcat = true;
        }
    }
    if (useStrcat == false) {
        strcpy(tmpBuf, "NONE");
    }
    return(strdup(tmpBuf));
} // titleType

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

/*
 * Return a string representation of the tmd access bits.
 * The string is dynamically allocated.
 * Retruns NULL if something went wrong
 */

char *
accessRightsToStr(const u32 accessRights)
{

    char        tempBuf[512];
    bool        useStrcat = false;

    if (accessRights == 0x0) {
        strcpy(tempBuf, "No access rights");
    }
    else {
        if (accessRights & TMD_ACR_ACCESS_BIT) {
            strcpy(tempBuf, "ACR ");
            useStrcat = true;
        }
        if (accessRights & TMD_DVD_ACCESS_BIT) {
            if (useStrcat) {
                strcat(tempBuf, "DVD ");
            }
            else {
                strcpy(tempBuf, "DVD ");
            }
            useStrcat = true;
        }
    }
    return(strdup(tempBuf));
}

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

char *
limitTypeToStr(const u32 limitType)
{

    switch (limitType) {

    case 0:
        return("None");
        break;

    case 1:
        return("Time duration");
        break;

    case 2:
        return("Absolute time");
        break;

    case 3:
        return("Number of titles");
        break;

    case 4:
        return("Number of launches");
        break;

    default:
        return("Unknown limit");
    }
} // limitTypeToStr
/* ------------------------------------------------------------------------ */

bool
printCerts(const void* certList, const u32 certListSize, const char* lineStart)
{
    bool                        returnVal = false;
    u8*                         ptr = (u8*)certList;
    IOSCCertSigType             sigType;
    IOSCCertPubKeyType          keyType;
    char*                       pIssuer;
    char*                       pCert;
    u32                         certSize;

    printf ("%sCertificates:\n", lineStart);
    printf ("%s\tBlob (List) size: %u\n", lineStart, certListSize);

    while (ptr < ((u8*) certList + certListSize)) {

        sigType = ntohl(((IOSCSigRsa4096*)ptr)->sigType);
        switch (sigType) {

        case IOSC_SIG_RSA4096:
            pIssuer = ((IOSCSigRsa4096*)ptr)->issuer;
            pCert = ((IOSCRsa4096RsaCert*)ptr)->head.name.serverId;
            certSize = sizeof(IOSCRsa4096RsaCert);
            break;

        case IOSC_SIG_RSA2048:
            pIssuer = ((IOSCSigRsa2048*)ptr)->issuer;
            keyType = ntohl(((IOSCRsa2048RsaCert*)ptr)->head.pubKeyType);
            switch (keyType) {
                case IOSC_PUBKEY_RSA2048:
                    pCert =  ((IOSCRsa2048RsaCert*)ptr)->head.name.serverId;
                    certSize = sizeof(IOSCRsa2048RsaCert);
                    break;
                case IOSC_PUBKEY_ECC:
                    pCert =  ((IOSCRsa2048EccCert*)ptr)->head.name.serverId;
                    certSize = sizeof(IOSCRsa2048EccCert);
                    break;
                default:
                    returnVal = false;
                    goto out;
            }
            break;
        case IOSC_SIG_ECC:
            pIssuer = ((IOSCSigEcc*)ptr)->issuer;
            pCert = ((IOSCEccEccCert*)ptr)->head.name.deviceId;
            certSize = sizeof(IOSCEccEccCert);
            break;

        default:
            returnVal = false;
            goto out;
        }
        printf ("%s\tIssuer: %s; Certificate: %s\n", lineStart, pIssuer, pCert);
        ptr += (certSize);
    }

    returnVal = true;
out:
    return (returnVal);
} // printCerts
/* ------------------------------------------------------------------------ */

/*
 * Return the 'base' part of a file name.
 * The base is the part before the final '.' if the file ends
 * in a well known extension.
 * Otherwise, just return the input file name.
 */
void
determineBaseName(const char* const inputName, char *baseName)
{
    char        tmpName[FILE_NAME_MAX], *extPtr;

    strncpy(tmpName, inputName, sizeof(tmpName));
    extPtr = rindex(tmpName, (int) '.');

    if (extPtr == NULL) {
        strcpy(baseName, inputName);
    }
    else if (   (strcmp(extPtr, ".bin") == 0)
             || (strcmp(extPtr, ".gcm") == 0)
             || (strcmp(extPtr, ".rvm") == 0)
            ) {
        *extPtr = '\0';
        strcpy(baseName, tmpName);
    }
    else {
        strcpy(baseName, inputName);
    }
}
/* ------------------------------------------------------------------------ */

/*
 * Write a slice of the file pointed to by inFile to the file
 * named outputName.
 * The slice starts at sliceStart and is of length sliceLength
 */
#define SLICE_BUF_SIZE          (8 * 1024 * 1024)
bool
sliceFile(const char* outputName, FILE *inFile, const off_t sliceStart,
          const off_t sliceLength)
{
    FILE        *outFile;
    u8          *dataBuf = NULL;
    bool        returnVal = false;
    off_t       remainingBytes;
    size_t      bytesRead, bytesWritten, bytesToRead;

    if ( (outFile = fopen (outputName, "wb")) == NULL) {
        fprintf(stderr, "%s: Can't open file %s for writing\n",
                ProgName, outputName);
            return(false);
    }

    if ((dataBuf = (u8 *) malloc(SLICE_BUF_SIZE)) == NULL) {
        fprintf(stderr, "%s: Can't allocate %u bytes\n",
                ProgName, SLICE_BUF_SIZE);
        goto end;
    }
    if (fseeko(inFile, sliceStart, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition data start failed\n",
                 ProgName);
        goto end;
    }
    remainingBytes = sliceLength;

    do {
        bytesToRead = MIN(remainingBytes, SLICE_BUF_SIZE);
        bytesRead = fread(dataBuf, 1, bytesToRead, inFile);
        if (bytesRead != bytesToRead) {
            if (ferror(inFile)) {
                fprintf(stderr, "%s: Read error on input file\n", ProgName);
                goto end;
            }
            else {
                fprintf(stderr, "%s: EOF reached on input file"
                        " before end of partiton", ProgName);
                goto end;
            }
        }
        bytesWritten = fwrite(dataBuf, 1, bytesRead, outFile);
        if (bytesWritten != bytesRead) {
            fprintf(stderr, "Write error when writing file %s\n",
                    outputName);
            goto end;
        }
        remainingBytes -= bytesRead;
    } while (remainingBytes != 0);
    returnVal = true;

end:
    if (outFile != NULL) {
        if (fclose(outFile) != 0) {
            fprintf(stderr, "%s: Closing output file %s failed (%s)\n",
                    ProgName, outputName, strerror(errno));
            returnVal = false;
        }
    }
    if (dataBuf != NULL) {
        free(dataBuf);
    }
    return(returnVal);
} // sliceFile
/* ------------------------------------------------------------------------ */
