#ident "$Id: rvl_partition.c,v 1.50 2008/06/04 23:58:46 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 generate RVL secure DVD partitions.
 *
 * See the Powerpoint
 * presentation on the Web for details.
 *
 * Format of 32K byte disc block:
 * 620 bytes of of H0 hashes
 * 20 bytes of padding 
 *
 * 160 bytes of H1 hashes
 * 36 bytes of padding
 *
 * 160 bytes of H2 hashes
 * 32 bytes of padding
 * Total: 1024 bytes
 *
 * 31K of data
 */


#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 <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <inttypes.h>
#include <netinet/in.h>         // For htonl()
#include <stdbool.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>

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

#include "aes.h"
#include "sha1.h"
#include "image_superblock.h"
#include "types.h"
#include "disk_format.h"
#include "estypes.h"
#include "md5.h"
#include "partition_common.h"
#include "disk_common.h"
#include "tool_common.h"

/*
 * See Makefile for details on DEVELOPER and PRODUCTION flags
 */

// This should have been declared in stdlib.h
int mkstemp(char *template);
#if defined(DEVELOPER)
#include "devel_key.h"
#elif defined(PRODUCTION)
#else
#error Must define either DEVELOPER or PRODUCTION
#endif

#define AES_KEY_LENGTH          16

bool getCertBlob(const char* const certName, u32 *certBlobSize,
                 void **certBlob);

void printMD5sum(const void* const ptr, const u32 numBytes);

bool generateTmd(const char* const binRoot, const char* const pkiRoot,
                 const optionVals_t* const optionVals,
                 const u64 titleId,
                 char *tmdFileName,
                 char *encryptedContentName, char *h3FileName,
                 char *titleKeyName);

bool generatePartition(const optionVals_t* const optionVals);

bool generateFiles(const optionVals_t* optionVals,
                   const char* const binRoot, const char* const pkiRoot,
                   char *encryptedContentName,
                   char *h3HashName, char *tmdName, char* ticketName);

bool getFiles(const char* const dirName,
              char *encryptedContentName, char *h3HashName,
              char *tmdName, char *ticketName);

bool generateContentIdAndIndex(const char* const inputTmdName,
                               ESContentId *contentId, u16 *contentIndex);

static bool readTmdContentIds(const char* const inputTmdName,
                              ESContentId **contentIds,
                              u16 *numContentIds);

bool handleInputTmd(const optionVals_t* optionVals,
                    const char* const binRoot,
                    const char* const inputTmd,
                    char **inputTmdCommandLine,
                    char ***conMetaDataFileNames,
                    int  *numConMetaDataFileNames);

#ifdef DEVELOPER
static char *createDevelTitleKeyFile(const char* const pkiRoot,
                                     const u8* const encryptKey,
                                     const u64 titleId);
#endif

char            *ProgName;

#ifdef DO_DUMP
void dumpBytes (const u8* const ptr, const int length);
#endif

#define PROGRAM_VERSION         "0.74.1"
#if !defined(IRD)
bool            Verbose = false;
#endif
/* ------------------------------------------------------------------------ */

#if !defined(IRD)
void
usage()
{
    fprintf (stderr, "Usage: %s [options] partition_data\n", ProgName);
    fprintf (stderr, "    or %s -c directory\n", ProgName);
    fprintf (stderr,
        " -c  --combine <dir>   - combines file in directory <dir> into\n"
        "                         a partition\n"
        " -g, --group <group Id>- specify group Id [default: 0x0002]\n"
        " -h, --help            - print usage message\n"
        " -k, --keep            - keep intermediate files (for debugging)\n"
        " -I, --titleVersion <version>   - specify title version [default: 0]\n"
        " -i, --ios <ios version>   - specify IOS version\n"
        "                             [default is IOS version 4]\n"
        " -n  --nand            - Produce NAND-enabled partition\n"
        " -o, --out <file>      - output image name [default: output.image]\n"
        " -q, --version         - print version information and stop\n"
        " -s  --stop <dir>      - stop after generating tmd and ticket files\n"
        "                         and leave files in dirctory <dir>\n"
        " -T, --tmd <tmd file>  - TMD containing CMD's for NAND titles\n"
        " -t, --titleId <id>    - title id         [default: 0xdead]\n"
        " -v, --verbose         - print out messages as image is created\n"
        " -x, --certs <file>    - use certificates from <file> instead\n"
        "                         of from $ROOT or $RVL_ROOT\n"
#if defined(ENABLE_DATA_ACCESS_TITLE)
        " -d, --dataTitle       - title contains data only\n"
        " -a, --accessTitleId   - accessTitleId in eTicket\n"
        " -A, --accessTitleMask - accessTitleMask in eTicket\n"
#endif
#if defined(PRODUCTION)
        " -L, --code  <l1,l2,..>- ticket limit codes(s)\n"
        "                         codes: 1->duration, 4->num launches\n"
        " -l, --limit <l1,l2,..>- ticket limit value(s)\n"
        " -R, --acr             - allow partition to have ACR access\n"
        " -V, --dvd             - allow partition to have DVD access\n"
#endif
        );
     fprintf (stderr, "\nCreates a game partition for encrypted disks.\n");
     fprintf (stderr,
             "The name of the resulting file is then specified in a\n");
     fprintf (stderr, "special .dlf file.\n");
}
#endif  // ! defined(IRD)
/* ------------------------------------------------------------------------ */

int
main(int argc, char *argv[])
{
    optionVals_t optionVals;

    ProgName = argv[0];

    processOptions(argc, argv, &optionVals);

    if (optionVals.versionOnly) {
        printf ("%s version %s %s\n", ProgName, PROGRAM_VERSION, __DATE__);
        exit(0);
    }
#if !defined(IRD)
    if (Verbose) {
        printf ("%s version %s %s\n", ProgName, PROGRAM_VERSION, __DATE__);
    }
#endif

    if (generatePartition(&optionVals) == false) {
        fprintf (stderr, "%s: Generation of partition failed.\n",
                          ProgName);
        if (fileExists(optionVals.outputName)) {
            if (unlink(optionVals.outputName) != 0) {
                char    buffer[256];
                sprintf(buffer, "%s: Can't unlink file %s",
                        ProgName, optionVals.outputName);
                perror(buffer);
            }
        }
        fprintf (stderr, "%s: Exiting with error\n", ProgName);
        exit(1);
    }
    exit(0);
}

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

/*
 * Generate a TMD by using the standalone tmd program.
 * If DEVELOPER is defined, use a predefined titleKey so that
 * the resulting encrypted partition can be decrypted using
 * a command line tool.
 * RETURNS:
 *          true if there were no problems
 *          false otherwise
 */
bool
generateTmd(const char* const binRoot, const char* const pkiRoot,
            const optionVals_t* const optionVals, const u64 titleId,
            char *tmdName, char *encryptedContentName,
            char* h3HashName, char* titleKeyName)
{
    char        commandBuf[COMMAND_BUF_LEN];
    int         status;
    ESContentId contentId  = 0;
    u16         contentIndex = 0;
    u32         contentType = ES_CONTENT_TYPE_NG_EXE | ES_CONTENT_TYPE_DISC;
    bool        returnVal   = true;
    char        *inputTmdCommandLine = NULL;
    char        **cmdFileNames = NULL;
    int         numCmdFileNames = 0;
    /* See Makefile for what preprocessor defines are used together */
#if defined(DEVELOPER)
    char        *encryptTitleKeyFile = NULL;
#endif
#if defined(PRODUCTION) || defined(JOHN_CHO_HACK)
    char        tmpBuf[COMMAND_BUF_LEN];
#endif


    char        rmFileName[FILE_NAME_MAX];
    char        rmOption[COMMAND_BUF_LEN];

    /*
     * Create a resource manager access control hash file to be
     * included in the reserved section of the tmd, if necessary.
     */
    if (optionVals->rmAccess) {
        int         tempFileDes;
        strncpy(rmFileName, "rmAccess.XXXXXX", sizeof(rmFileName));

        if ((tempFileDes = mkstemp(rmFileName)) == -1) {
            perror("generateTmd:mkstemp");
            return(false);
        }
        if (close(tempFileDes) == -1) {
            perror("generateTmd:close");
            return(false);
        }
        
        sprintf(commandBuf, "%sconfigHash.py -c %s -o %s",
                binRoot, optionVals->rmAccess, rmFileName);
        status = system(commandBuf);

        if (status == -1) {
            fprintf (stderr, "%s: fork failed for command '%s'\n",
                     ProgName, commandBuf);
            return(false);
        }
        if (WEXITSTATUS(status) != 0) {
            fprintf (stderr, "%s: tmd create command '%s' failed.\n",
                     ProgName, commandBuf);
            return(false);
        }
        sprintf(rmOption, "-B %s", rmFileName);
    } else {
        rmOption[0] = 0;
    }

    if (generateContentIdAndIndex(optionVals->inputTmd, &contentId,
                                  &contentIndex) == false) {
        returnVal = false;
        goto end;
    }

    if (optionVals->inputTmd != NULL) {
        if (handleInputTmd(optionVals, binRoot, optionVals->inputTmd,
                           &inputTmdCommandLine, &cmdFileNames,
                           &numCmdFileNames) == false) {
            returnVal = false;
            goto end;
        }
    }

#if defined(ENABLE_DATA_ACCESS_TITLE)
    sprintf (commandBuf, "%s%s -O"
                          " -c 0x%x"
                          " -i %u"
                          " -t 0x%x"
                          " -T 0x%llx" 
                          " %s "
                          " -b %d ",
                          binRoot, TMD_BINARY,
                          contentId,
                          contentIndex,
                          contentType,
                          titleId,
                          rmOption, 
                          optionVals->bootIndex);
#else
    sprintf (commandBuf, "%s%s -O"
                          " -c 0x%x"
                          " -i %u"
                          " -t 0x%x"
                          " -T 0x%llx" 
                          " %s ",
                          binRoot, TMD_BINARY,
                          contentId,
                          contentIndex,
                          contentType,
                          titleId,
                          rmOption);
#endif
    strcat (commandBuf, " -d ");                // disk encryption
    strcat (commandBuf, " -n ");               // content name
    strcat (commandBuf, optionVals->contentOrPrefixName);    // input content
    if (inputTmdCommandLine != NULL) {
        strcat(commandBuf, inputTmdCommandLine);
    }
    if (optionVals->titleVersion != NULL) {
        strcat (commandBuf, " -m ");
        strcat (commandBuf, optionVals->titleVersion);
    }
    if (optionVals->IOSversion != NULL) {
        strcat (commandBuf, " -o ");
        strcat (commandBuf, optionVals->IOSversion);
    }
    if (optionVals->groupId != NULL) {
        strcat (commandBuf, " -g ");
        strcat (commandBuf, optionVals->groupId);
    }

    /*
     * The following are hardcoded into the developer TMD executable:
     * -P d     - developer PKI
     * -C ES_TITLE_NG_TITLE
     * -r 0x0   - No access rights
     */
#if defined(PRODUCTION) || defined (JOHN_CHO_HACK)
    sprintf (tmpBuf, " -C 0x%x", ES_TITLE_TYPE_NG_TITLE);
    strcat  (commandBuf, tmpBuf);
#endif

#if defined(PRODUCTION)
    strcat (commandBuf, " -P p");               // production PKI

    sprintf (tmpBuf, " -r 0x%llx", optionVals->accessBits);
    strcat  (commandBuf, tmpBuf);

#elif defined(DEVELOPER)
    encryptTitleKeyFile = createDevelTitleKeyFile(pkiRoot, develKey, titleId);
    if (encryptTitleKeyFile == NULL) {
        returnVal = false;
        goto end;
    }
    strcat (commandBuf, " -K ");
    strcat (commandBuf, encryptTitleKeyFile);
#if defined (JOHN_CHO_HACK)
    strcat (commandBuf, " -P d ");
#endif // JOHN_CHO_HACK
#endif // DEVELOPER

    if (optionVals->keepFiles) {
        strcat (commandBuf, " > tmd.out 2>&1 ");
    }
    else {
        strcat (commandBuf, " > /dev/null 2>&1 ");
    }

#if !defined(IRD)
    if (Verbose) {
        printf ("TMD command is: %s\n", commandBuf);
    }
#endif
    status = system(commandBuf);
    if (status == -1) {
        fprintf (stderr, "%s: fork failed for command '%s'\n",
                 ProgName, commandBuf);
        returnVal = false;
        goto end;
    }
    if (WEXITSTATUS(status) != 0) {
        fprintf (stderr, "%s: tmd create command '%s' failed.\n",
                 ProgName, commandBuf);
        returnVal = false;
        goto end;
    }

    sprintf(tmdName, "%" PRIx64 ".tmd", titleId);
    if (! fileExists(tmdName)) {
        fprintf (stderr, "%s: expected 'tmd' to create file %s\n",
                 ProgName, tmdName);
        returnVal = false;
        goto end;
    }

    sprintf(encryptedContentName, "%08x.app", contentId);
    if (! fileExists(encryptedContentName)) {
        fprintf (stderr, "%s: expected 'tmd' to create file %s\n",
                 ProgName, encryptedContentName);
        returnVal = false;
        goto end;
    }

    sprintf(titleKeyName, "%" PRIx64 ".titleKey", titleId);
    if (! fileExists(titleKeyName)) {
        fprintf (stderr, "%s: expected 'tmd' to create file %s\n",
                 ProgName, titleKeyName);
        returnVal = false;
        goto end;
    }

    sprintf(h3HashName, "%08x.hash", contentId);
    if (! fileExists(h3HashName)) {
        fprintf (stderr, "%s: expected 'tmd' to create file %s\n",
                 ProgName, h3HashName);
        returnVal = false;
        goto end;
    }

end:
#ifdef DEVELOPER
    /*
    printf ("Encrypted file is: %s\n", encryptTitleKeyFile);
    */
    if (encryptTitleKeyFile != NULL && optionVals->keepFiles == false) {
        unlink(encryptTitleKeyFile);
    }
#endif
    if (optionVals->rmAccess && unlink(rmFileName) != 0) {
        perror("unlink");
    }
    return(returnVal);
} // generateTmd

/* ------------------------------------------------------------------------ */
/*
 * Given an input tmd, extract all of the content meta datas it contains.
 * Generate the argument list to hand to tmd to input the extracted
 * content meta datas, and return an array of the extracted content
 * meta data file names so they can be cleaned up.
 */
bool
handleInputTmd(const optionVals_t* optionVals,
               const char* const binRoot,
               const char* const inputTmdName,
               char **inputTmdCommandLine,
               char ***conMetaDataFileNames,
               int  *numConMetaDataFileNames)
{
    bool                returnVal = false;
    char                *tmdOutFileName;
    ESContentId         *existingIds = NULL;
    u16                 numContents;
    char                commandBuf[COMMAND_BUF_LEN];
    int                 status;


    if (inputTmdName == NULL) {
        *inputTmdCommandLine = NULL;
        *conMetaDataFileNames = NULL;
        *numConMetaDataFileNames = 0;
        return(true);
    }
    /*
     * Don't use mkstemp because it doesn't say whether it opens a file
     * in text or binary mode
     */

    tmdOutFileName = ".tmdOut";

    // FIXME - This always uses tmd - what should be done in
    //         the tmdIrd case?
    sprintf (commandBuf, "%s%s -I %s -a -P d > %s 2>&1",
             binRoot, "tmd", inputTmdName, tmdOutFileName);

#if !defined(IRD)
    if (Verbose) {
        printf ("Tmd CMD extraction command is: %s\n", commandBuf);
    }
#endif
    status = system(commandBuf);
    if (status == -1) {
        fprintf (stderr, "%s: fork failed for command '%s'\n",
                 ProgName, commandBuf);
        returnVal = false;
        goto end;
    }
    if (WEXITSTATUS(status) != 0) {
        fprintf (stderr,
                 "%s: tmd content meta data extraction command '%s' failed.\n",
                 ProgName, commandBuf);
        returnVal = false;
        if (rename(tmdOutFileName, "tmd.cmdExtract.errLog") != 0) {
            fprintf(stderr, "%s: Rename of tmd error output file failed (%s)\n",
                   ProgName, strerror(errno));
        }
        goto end;
    }

    if (optionVals->keepFiles) {
        if (rename(tmdOutFileName, "tmd.cmdExtract.log") != 0) {
            fprintf(stderr, "%s: Rename of tmd error output file failed (%s)\n",
                   ProgName, strerror(errno));
        }
    }
    else {
        unlink(tmdOutFileName);
    }
    if (readTmdContentIds(inputTmdName, &existingIds, &numContents) == false) {
        goto end;
    }

    *conMetaDataFileNames = (char **) malloc(numContents * sizeof (char *));
    if (*conMetaDataFileNames == NULL) {
        fprintf(stderr, "%s: Allocating %hu char pointers failed\n",
                ProgName, numContents);
        goto end;
    }
    for (u16 i = 0; i < numContents; i++) {
        char tmpFileName[FILE_NAME_MAX];

        snprintf(tmpFileName, sizeof(tmpFileName), "%hu.cmd", existingIds[i]);
        if (i == 0) {
            strcpy(commandBuf, " -A ");
        }
        else {
            strcat(commandBuf, ",");
        }
        strcat(commandBuf, tmpFileName);
        (*conMetaDataFileNames)[i] = strdup(tmpFileName);
        if ((*conMetaDataFileNames)[i] == NULL) {
            fprintf(stderr, "%s: conMetaDataFileNames allocation failed\n",
                    ProgName);
            goto end;
        }
    }
    *numConMetaDataFileNames = numContents;

    *inputTmdCommandLine = strdup(commandBuf);
    if (*inputTmdCommandLine == NULL) {
        fprintf(stderr, "%s: Duplicating CMD command line failed\n", ProgName);
        goto end;
    }

    returnVal = true;

end:
    if (existingIds != NULL) {
        free(existingIds);
    }
    return(returnVal);
}
/* ------------------------------------------------------------------------ */

/*
 * Generate a unique (for this title) content id for the input content.
 * Return it in the pointer 'contentId'.
 * If there is no input tmd, use a content id of 0.
 *
 * RETURNS: 
 *          true:        if a unique content id could be generated
 *          false:       if there was a problem
 */

bool
generateContentIdAndIndex(const char* const inputTmdName,
                          ESContentId *contentId, u16 *contentIndex)
{
    bool                returnVal = false;
    ESContentId         *existingIds = NULL;
    u16                 numContents;
    int                 ESContentIdCompare(const void* ptr1, const void* ptr2);

    if (inputTmdName == NULL) {
        *contentId = 0;
        *contentIndex = 0;
        return(true);
    }
    if (readTmdContentIds(inputTmdName, &existingIds, &numContents) == false) {
        *contentId = 7700;      /* Value should not be used */
        goto end;
    }
    *contentIndex = numContents;

    qsort(existingIds, numContents, sizeof(ESContentId), ESContentIdCompare);
    if (numContents == 1) {
        if (existingIds[0] == 0) {
            *contentId = 1;
        }
        else {
            *contentId = 0;
        }
        returnVal = true;
    }
    else {
        /*
         * Scan existing content ids.  If there is an empty slot in
         * the existing sequence, use it.  Otherwise, use one greater
         * than the highest content id
         */
        for (u16 i = 1; i < numContents; i++) {
            if (existingIds[i] != existingIds[i-1] + 1) {
                *contentId = existingIds[i-1] + 1;
                returnVal = true;
                break;
            }
        }
        *contentId = existingIds[numContents - 1] + 1;
        returnVal = true;
    }

end:
    if (existingIds != NULL) {
        free(existingIds);
    }
    return(returnVal);
} // generateContentId
/* ------------------------------------------------------------------------ */

/*
 * This function is used as the compare routine handed to qsort.
 *
 * RETURNS: 0, if ptr1 and ptr2 point to equal ESContentId's
 *          1, if ptr1 points to an ESContentId GREATER than ptr2
 *         -1, of ptr1 points to an ESContentID LESS than ptr
 */
int
ESContentIdCompare(const void* ptr1, const void* ptr2)
{
    if (* (ESContentId *) ptr1 == * (ESContentId *) ptr2) {
        return(0);
    }
    else if (* (ESContentId *) ptr1 < * (ESContentId *) ptr2) {
        return(-1);
    }
    else {
        return(1);
    }
} // ESContentIdCompare
/* ------------------------------------------------------------------------ */
/*
 * Read the content id's contained in the tmd contained in the
 * file named 'inputTmdName'.
 *
 * Return the contentIds in 'contentIds', and the number of content
 * id's in numContentIds.  
 *
 * NOTE: the caller should free *contentIds.
 */
static bool
readTmdContentIds(const char* const inputTmdName, ESContentId **contentIds,
                  u16 *numContentIds)
{
    bool                returnVal = false;
    u8                  *tmpTmdPtr = NULL;
    ESTitleMeta         *inputTmd = NULL;
    u32                 tmdSize;

    /*
     * Pass tmpTmdPtr instead of inputTmd to avoid breaking strict
     * aliasing that happens if &inputTmd is cast to (u8 **)
     */
    if (readBinFileIntoArray(inputTmdName, &tmpTmdPtr, &tmdSize) == false) {
        goto end;
    }
    inputTmd = (ESTitleMeta *) tmpTmdPtr;

    *numContentIds = ntohs(inputTmd->head.numContents);

    /* Read all the existing content ID's */
    *contentIds = (ESContentId *) malloc(*numContentIds * sizeof(ESContentId));
    if (*contentIds == NULL) {
        fprintf(stderr, "%s: Can't allocate space for %hu contentIds\n",
                ProgName, *numContentIds);
        goto end;
    }

    /*
     * Read the content IDs.
     */
    for (u16 i = 0; i < *numContentIds; i++) {
        (*contentIds)[i] = ntohl(inputTmd->contents[i].cid);
    }
    returnVal = true;

end:
    if (tmpTmdPtr != NULL) {
        free(inputTmd);
    }
    return(returnVal);
} /* readTmdContentIds */
/* ------------------------------------------------------------------------ */

bool stopMidway(const char* const dirName,  const char* const contentName,
                const char* const hashName, const char* const tmdName,
                const char* const ticketName);

/*
 *
 * Write out the game meta-data and game data (collectively, the
 * partition) for each update.
 * Each partition consists of, in order:
 * - game structure (includes eTicket, since it is fixed length)
 * - the TMD (variable length)
 * - the variable size certificate blob
 * - the H3 hashes (fixed length)
 * - the "virtual disk image"
 * RETURNS:
 *           an array of pointers to game tables of content
 *
 */

#define PATH_LEN        1024
bool
generatePartition(const optionVals_t* optionVals)
{
    FILE                *outFile;
    partition_t         partition, partitionOnDisk;
    off_t               fileOffset, partitionStart, tmdStart, partLength;
    off_t               certBlobStart, h3HashStart, cryptAreaStart;
    off_t               currentPos;
    char                tmdName[PATH_LEN], encryptedContentName[PATH_LEN];
    char                h3HashName[PATH_LEN];
    char                ticketName[PATH_LEN], titleKeyName[PATH_LEN];
    u32                 ticketSize;
    u8                  *ticket, *tmd, *certBlob;
    char                *binRoot, *pkiRoot;

#if !defined(IRD)
    if (Verbose) {
        printf ("Partition size is: %u\n", sizeof(partition_t));
    }
#endif
    
    if ((outFile = fopen(optionVals->outputName, "wb")) == NULL) {
        fprintf(stderr, "%s: Can't open output file '%s' for writing\n",
                ProgName, optionVals->outputName);
        return(false);
    }

    /*
     * If we are combining files, and the certificate file is specified,
     * then we don't need binRoot or pkiRoot.
     * This is the case on the CLS machine, where no ROOT of any kind
     * is defined.
     * Just in case, set them to NULL so that any use will get flagged
     */
    if (optionVals->combineDirectory == NULL || optionVals->certFile == NULL) {
        if (getRoot(&binRoot, &pkiRoot) == false) {
            return(false);
        }
    }
    else {
        binRoot = NULL;
        pkiRoot = NULL;
    }

    /*
     * Either generate the component files if the combine
     * directory isn't specified, or get the names of the
     * components that were already generated
     */
    if (optionVals->combineDirectory == NULL) {
        if (generateFiles(optionVals, binRoot, pkiRoot,
                          encryptedContentName, h3HashName,
                          tmdName, ticketName) == false) {
            return(false);
        }
    }
    else {
         getFiles(optionVals->combineDirectory, encryptedContentName,
                  h3HashName, tmdName, ticketName);
    }


    if (optionVals->stopDirectory != NULL) {
        if (fclose(outFile) == -1) {
            fprintf(stderr, "%s: Warning - can't close empty"
                             " output file '%s' (%s)\n",
            ProgName, optionVals->outputName, strerror(errno));
        }
        if (unlink(optionVals->outputName) == -1) {
            fprintf(stderr, "%s: Warning - can't remove empty"
                             " output file '%s' (%s)\n",
            ProgName, optionVals->outputName, strerror(errno));
        }
        stopMidway(optionVals->stopDirectory, encryptedContentName, h3HashName, tmdName, ticketName);
        printf ("%s: Stopping after generating intermediate files\n", ProgName);
        exit(0);
    }
    
    if (optionVals->isNand == false) {
        /* Read E-ticket into game partition */
        if (readBinFileIntoArray(ticketName, &ticket, &ticketSize) == false) {
            fprintf(stderr, "(%s) Error: can't read e-ticket from file '%s'\n",
            ProgName, ticketName);
            return(false);
        }
        if (ticketSize != sizeof(ESTicket)) {
            fprintf(stderr, "(%s) Error: sizeof of ticket file (%u) does not match the sizeof an ESTicket (%u)\n",
            ProgName, ticketSize, sizeof(ESTicket));
        }
        memcpy(&(partition.ticket), ticket, sizeof(ESTicket));
        free(ticket);
    }
    else {
        /* No e-ticket - zero out the bytes in the partition header */
        memset(&(partition.ticket), 0, sizeof(ESTicket));
    }

    /* Read TMD */
    if (readBinFileIntoArray(tmdName, &tmd, &(partition.tmdSize)) == false) {
        return(false);
    }

    /* Read certificates */
    if (optionVals->certFile == NULL) {
#ifdef DEVELOPER
        if (readCertBlob(pkiRoot, &certBlob,
                         &(partition.certBlobSize), false) == false) {
            return(false);
        }
#else
        if (readCertBlob(pkiRoot, &certBlob,
                         &(partition.certBlobSize), true) == false) {
            return(false);
        }
#endif
    }
    else {
        if (readBinFileIntoArray(optionVals->certFile, &certBlob,
                                 &(partition.certBlobSize)) == false) {
            return(false);
        }
    }

    fileOffset = ftell(outFile);

    partitionStart = alignAddress(fileOffset, PARTITION_ALIGN);

    tmdStart = partitionStart + sizeof(partition_t);
    tmdStart = alignAddress(tmdStart, ITEM_ALIGN);
    certBlobStart = alignAddress(tmdStart + partition.tmdSize, ITEM_ALIGN);
    h3HashStart = certBlobStart + partition.certBlobSize;
    h3HashStart = alignAddress(h3HashStart, H3_ALIGN);
    cryptAreaStart = alignAddress(h3HashStart + H3_SIZE, ENCRYPT_ALIGN);

    partition.tmdOffset           = DISK_ADDR(tmdStart - partitionStart);
    partition.certBlobOffset      = DISK_ADDR(certBlobStart - partitionStart);
    partition.h3HashesOffset      = DISK_ADDR(h3HashStart - partitionStart);
    partition.encryptedAreaOffset = DISK_ADDR(cryptAreaStart - partitionStart);
    if (fileSize(encryptedContentName, &partLength) == false) {
#if !defined(IRD)
        fprintf(stderr,
                "%s: Can't get size of encrypted content - continuing\n",
                ProgName);
#endif
        partLength = 0;
    }
    else {
        partition.partDataLengthWords = htonl((u32) (partLength >> 2));
    }
    
    partitionOnDisk = partition;
    partitionOnDisk.tmdSize      = htonl(partition.tmdSize);
    partitionOnDisk.certBlobSize = htonl(partition.certBlobSize);
#if !defined(IRD)
    if (Verbose) {
        printf ("tmdOffset: 0x%" PRIx32 "\n", ntohl(partitionOnDisk.tmdOffset) << 2);
        printf ("CertBlobSize: 0x%" PRIx32 "\n", ntohl(partitionOnDisk.certBlobSize) << 2);
        printf ("CertBlobOffset: 0x%" PRIx32 "\n", ntohl(partitionOnDisk.certBlobOffset) << 2);
        printf ("H3 hash offset: 0x%" PRIx32 "\n", ntohl(partitionOnDisk.h3HashesOffset) << 2);
        printf ("Encrypted area offset: 0x%" PRIx32 "\n", ntohl(partitionOnDisk.encryptedAreaOffset) << 2);
    }
#endif
    /*
     * Write out the game partition structure, which includes
     * the eTicket
     */
    if (fseeko(outFile, partitionStart, SEEK_SET) == -1) {
        perror("fseeko");
        return(false);
    }
    if (fwrite(&partitionOnDisk, sizeof(partition_t), 1, outFile) != 1) {
        fprintf(stderr, "Partition struct write failed\n");
        return(false);
    }

    /* Write out TMD structure */
    if (fseeko(outFile, tmdStart, SEEK_SET) == -1) {
        perror("fseeko");
        return(false);
    }
    if (fwrite(tmd, 1, partition.tmdSize, outFile) != partition.tmdSize) {
        fprintf(stderr, "Partition TMD write failed\n");
        return(false);
    }

    /* Write out certificates */
    if (fseeko(outFile, certBlobStart, SEEK_SET) == -1) {
        perror("fseeko");
        return(false);
    }
    if (fwrite(certBlob, partition.certBlobSize, 1, outFile) != 1) {
        fprintf(stderr, "Partition certificates write failed\n");
        return(false);
    }

    /* Write out H3 Hashes */
    if (fseeko(outFile, h3HashStart, SEEK_SET) == -1) {
        perror("fseeko");
        return(false);
    }
    if (copyBinFileToOutFile(outFile, h3HashName) == false) {
        return(false);
    }

    /*
     * The hash file that was just copied is not padded out to H3_SIZE.
     * Write padding bytes out between the end of the real H3 bytes
     * and the crypt area start.  This is necessary because if the content is
     * empty, the partition written won't include H3_SIZE bytes for the
     * H3 partition.
     */
    currentPos = ftello(outFile);
    for (int i = 0; i < cryptAreaStart - currentPos; i++) {
        putc(0, outFile);
    }

    /* Write out content */
    if (fseeko(outFile, cryptAreaStart, SEEK_SET) == -1) {
        perror("fseeko");
        return(false);
    }
    if (copyBinFileToOutFile(outFile, encryptedContentName) == false) {
        return(false);
    }
    free(tmd);
    free(certBlob);
    if (fclose(outFile) != 0) {
        fprintf(stderr, "%s: Closing output file failed (%s)\n",
                ProgName, strerror(errno));
        return(false);
    }
    if (optionVals->isNand == true) {
        char    outName[PATH_LEN];

        sprintf(outName, "%s.tmd", optionVals->outputName);
        if (rename(tmdName, outName) != 0) {
            fprintf(stderr, "%s: Renaming TMD file from %s to %s failed (%s)\n",
                    ProgName, tmdName, outName, strerror(errno));
            return(false);
        }
    }
    else if (optionVals->keepFiles == false) {
        unlink(tmdName);
    }
    if (optionVals->keepFiles == false) {
        unlink(encryptedContentName);
        unlink(h3HashName);
        unlink(ticketName);
        unlink(titleKeyName);
    }

    return(true);
} // generatePartition

/* ------------------------------------------------------------------------ */
bool
generateFiles(const optionVals_t* optionVals,
              const char* const binRoot, const char* const pkiRoot,
              char *encryptedContentName,
              char *h3HashName, char *tmdName, char* ticketName)
{
    char                titleKeyName[FILE_NAME_MAX];

    /* generateTmd also generates the encrypted content file */
    if (generateTmd(binRoot, pkiRoot, optionVals, optionVals->titleId, tmdName,
                    encryptedContentName, h3HashName, titleKeyName) == false) {
        return(false);
    }
#ifdef DEVELOPER
    if (generateEticket(binRoot, titleKeyName, optionVals->titleId,
                        NULL, NULL, 
                        optionVals->accessTitleId, optionVals->accessTitleMask,
                        false, optionVals->keepFiles,
                        ticketName) == false) {
        return(false);
    }
#else
    if (generateEticket(binRoot, titleKeyName, optionVals->titleId,
                        optionVals->limitCodes, optionVals->limitValues,
                        optionVals->accessTitleId, optionVals->accessTitleMask,
                        true, optionVals->keepFiles, ticketName) == false) {
        return(false);
    }
#endif
    if (optionVals->keepFiles == false && fileExists(titleKeyName)) {
        unlink(titleKeyName);
    }
    return(true);
}

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

/*
 * Implement stopping the partition create process midway through.
 * Move the component files 'contentName', 'hashName', etc. to
 * 'dirName'
 * Return false if something goes wrong
 */
bool
stopMidway(const char* const dirName, const char* const contentName,
           const char* const hashName, const char* const tmdName,
           const char* const ticketName)
{
    struct stat statBuf;
    char        newName[PATH_LEN_MAX];

    if (stat(dirName, &statBuf) == -1) {
        if (errno == ENOENT) {
            if (mkdir(dirName, 0777) == -1) {
                fprintf(stderr, "%s: Can't make directory '%s' - exit\n",
                        ProgName, dirName);
                exit(-1);
            }
        }
    }
    else if (! S_ISDIR(statBuf.st_mode)) {
        fprintf (stderr, "%s: '%s' already exists and is not a directory - exit\n",
                 ProgName, dirName);
        exit(-1);
    }

    sprintf(newName, "%s/%s", dirName, contentName);
    if (rename(contentName, newName) == -1) {
        fprintf(stderr, "%s: Can't rename '%s' to '%s' - exit",
                ProgName, contentName, newName);
        exit(1);
    }

    sprintf(newName, "%s/%s", dirName, hashName);
    if (rename(hashName, newName) == -1) {
        fprintf(stderr, "%s: Can't rename '%s' to '%s' - exit",
                ProgName, hashName, newName);
        exit(1);
    }

    sprintf(newName, "%s/%s", dirName, tmdName);
    if (rename(tmdName, newName) == -1) {
        fprintf(stderr, "%s: Can't rename '%s' to '%s' - exit",
                ProgName, tmdName, newName);
        exit(1);
    }
    
    sprintf(newName, "%s/%s", dirName, ticketName);
    if (rename(ticketName, newName) == -1) {
        fprintf(stderr, "%s: Can't rename '%s' to '%s' - exit",
                ProgName, ticketName, newName);
        exit(1);
    }
    return(true);
} // stopMidway

bool getTypedFileName(DIR *dirPtr, const char* const dirName,
                      const char* const nameExtension, char *fileName);

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

/*
 * Get the names of the content, H3 hash, tmd, and ticket files
 * that shoud be in directory 'dirName'.
 * RETURN: true - if all files could be found and there was only one file
 *                of each type in the directory
 *         false - otherwise
 */
bool
getFiles(const char* const dirName,
         char *encryptedContentName, char *h3HashName,
         char *tmdName, char *ticketName)
{
    struct      stat statBuf;
    DIR         *dirPtr;

    if (stat(dirName, &statBuf) == -1) {
        fprintf(stderr, "%s: No such directory '%s'\n", ProgName, dirName);
        return(false);
    }
    if (! S_ISDIR(statBuf.st_mode)) {
        fprintf(stderr, "%s: '%s' is not directory\n", ProgName, dirName);
        return(false);
    }
    if ((dirPtr = opendir(dirName)) == NULL) {
        fprintf(stderr, "%s: Can't open directory %s\n", ProgName, dirName);
        return(false);
    }

    if (getTypedFileName(dirPtr, dirName, ".app",
                         encryptedContentName) == false) {
        return(false);
    }
    rewinddir(dirPtr);

    if (getTypedFileName(dirPtr, dirName, ".hash", h3HashName) == false) {
        return(false);
    }
    rewinddir(dirPtr);

    if (getTypedFileName(dirPtr, dirName, ".tmd", tmdName) == false) {
        return(false);
    }
    rewinddir(dirPtr);

    if (getTypedFileName(dirPtr, dirName, ".tik", ticketName) == false) {
        return(false);
    }
    if (closedir(dirPtr) != 0) {
        printf("%s: Closing directory %s returned an error\n",
                ProgName, dirName);
    }
    return(true);
}
/* ------------------------------------------------------------------------ */

#ifdef DEVELOPER

// __tune_i686__ is set on Cygwin - it doesn't set i386 :(
#if defined(__ARMEL__) || defined(__i386__) || defined(__tune_i686__)
#define htonll(x) ((u64)( ((u64)((htonl((u32)(x)))) << 32) | (htonl((u32)(((u64)(x))>>32))) ))
#elif defined (__ARMEB__)
#define htonll(x) (x)
#else
#error Unknown architecture
#endif

#define FILE_TEMPLATE   ".rvl_partitionXXXXXX"

/*
 * Take the AES key passed as a parameter, and encrypt it
 * so that when it is decrypted by the 'tmd' program it
 * it gets the original key.  Write the encrypted key
 * out to a file, and return the file name.
 * If something goes wrong, return NULL;
 */

static char *
createDevelTitleKeyFile(const char* const pkiRoot, const u8* const key,
                        const u64 titleId)
{
    u8     encryptedKey[AES_KEY_LENGTH];
    u8     initVector[AES_IV_LENGTH];
    char   commonKeyName[FILE_NAME_MAX], *titleKeyName;
    u8     *commonKey;
    u32    commonKeySize;
    int    tempFD;
    u64    titleIdNetwork;
    FILE   *tempFile;


    /* Get the common key used to encrypt the title key */
    sprintf(commonKeyName, "%scommon_dpki.aesKey", pkiRoot);
    if (readBinFileIntoArray(commonKeyName, &commonKey,
                             &commonKeySize) == false) {
#if defined(IRD)
        // Avoid using the word 'key' in IRD messages'
        fprintf(stderr, "%s: Can't read file %s\n", ProgName, commonKeyName);
#else
        fprintf(stderr, "%s: Can't read common key file %s\n",
                ProgName, commonKeyName);
#endif
        return(NULL);
    }
    if (commonKeySize != AES_KEY_LENGTH) {
#if defined(IRD)        // Avoid mentioning "key" in IRD messages
        fprintf(stderr,
                "%s: Length of file %s (%u) incorrect\n",
                ProgName, commonKeyName, commonKeySize);
#else
        fprintf(stderr,
                "%s: Length of file %s (%u) doesn't match AES key length %d\n",
                ProgName, commonKeyName, commonKeySize, AES_KEY_LENGTH);
#endif
        return(NULL);
    }

    titleIdNetwork = htonll(titleId);
    memset(initVector, 0, AES_IV_LENGTH);
    memcpy(initVector, &titleIdNetwork, sizeof(ESTitleId));

    /*
    printf ("Common key: ");
    dumpBytes(commonKey, 16);
    printf ("initVector");
    dumpBytes(initVector, AES_IV_LENGTH);
    printf ("(Developer) key");
    dumpBytes(key, AES_KEY_LENGTH);
    */

    aes_SwEncryptWrapper((u8 *) commonKey, initVector, (u8 *) key,
                         AES_KEY_LENGTH, encryptedKey);

    /*
    printf ("Encrypted key");
    dumpBytes(encryptedKey, AES_KEY_LENGTH);
    */

    titleKeyName = strdup(FILE_TEMPLATE);
    if (titleKeyName == NULL) {
#if defined(IRD) // Avoid using the word "key" in IRD messages.
        fprintf(stderr, "%s: malloc failed\n", ProgName);
#else
        fprintf(stderr, "%s: Duplicating titleKeyName failed\n", ProgName);
#endif
        return(NULL);
    }
    /*
     * Note: the mkstemp man page says nothing about opening the
     *       file in binary mode, so don't use the file descriptor
     *       that is returned!
     */

    if ((tempFD = mkstemp(titleKeyName)) == -1) {
        perror("mkstemp");
        return(NULL);
    }
    if (close(tempFD) != 0) {
        printf ("%s: Closing temporary file failed\n", ProgName);
        return(NULL);
    }
    if ( (tempFile = fopen(titleKeyName, "wb")) == NULL) {
        printf ("%s: Open temporary file %s failed\n", ProgName, titleKeyName);
        return(NULL);
    }

    if (fwrite(encryptedKey, AES_KEY_LENGTH, 1, tempFile) != 1) {
        /*
         * Avoid using the word 'encrypt' in IRD version to foil
         * novice crackers.
         */
#if defined(IRD)
        fprintf (stderr, "%s: Can't write file %s\n", ProgName, titleKeyName);
#else
        fprintf (stderr, "%s: Can't write encrypted key to file %s\n",
                          ProgName, titleKeyName);
#endif
        /* Already in error situation - don't check for errors here */
        fclose(tempFile);
        unlink(titleKeyName);
        return(NULL);
    }
    if (fclose(tempFile) != 0) {
        fprintf (stderr, "%s: Can't close file %s\n", ProgName, titleKeyName);
        return(NULL);
    }
    return(titleKeyName);
} // createDevelTitleKeyFile

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