#ident "$Id: clsCompose.c,v 1.8 2007/02/02 23:23:29 craig Exp $"
/*
 *               Copyright (C) 2006, 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 a production disk image from an encrypted partition
 *
 * This code is 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 <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 "types.h"
#include "disk_format.h"
#include "estypes.h"
#include "tool_common.h"
#include "disk_common.h"
#include "masterimage.h"        /* From Nintendo */
#include "master_common.h"      /* From Nintendo */

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

#define PATH_LEN        1024
#define COMMAND_LEN     2048
#define DIR_EXTENSION   ".files"

#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"rcf",             1, 0, 'c'},     /* Rcf file name */
    {"help",            0, 0, 'h'},     /* Print usage */
    {"keep",            0, 0, 'k'},     /* keep intermediate files */
    {"part",            1, 0, 'p'},     /* partition name */
    {"rvl",             1, 0, 'r'},     /* rvl.bin name */
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {0, 0, 0, 0}
};
#endif

static char* options = "c:hkp:r:v";
char            *ProgName;
bool            Verbose = false;

typedef struct optionVals {
    char *outputName;
    char *rcfName;
    char *rvlName;
    char *partName;
    bool keepFiles;
} optionVals_t;

// The DF_ structures are copied from makeRVTR.c
typedef struct {
    u32 numGamePartitions;
    u32 partitionInfos;   // Address of an array of partition infos
    u8  padding[24];
} DF_GameTOC;

typedef struct {
    u32 gamePartition;
    u32 type;
} DF_PartitionInfo;

typedef struct {
    u32 sysVersionHigh;
    u32 sysVersionLow;
    u32 titleIdHigh;
    u32 titleIdLow;
}   DF_ESTicket;


// This should have been declared in stdlib.h, but isn't
int mkstemp(char *template);

char *genNewRcfFile(const optionVals_t* const optionVals);
void usage();
bool getSysVersion(const u32 numGamePartitions, FILE *rcfFile,
                   u32 *sysVersionLow, u32 *sysVersionHigh);

bool produceImage(const optionVals_t* const optionVals,
                  const char* const newRcfFile);
/* ------------------------------------------------------------------------ */

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

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

    // Default values
    optionVals->outputName              = NULL;
    optionVals->rcfName                 = NULL;
    optionVals->rvlName                 = NULL;
    optionVals->partName                = NULL;
    optionVals->keepFiles               = 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 'c':
            optionVals->rcfName = optarg;
            break;

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

        case 'k':
            optionVals->keepFiles = true;
            break;

        case 'o':
            optionVals->outputName = optarg;
            break;

        case 'p':
            optionVals->partName = optarg;
            break;

        case 'r':
            optionVals->rvlName = optarg;
            break;

        case 'v':
            Verbose = true;
            break;

        default:
            fprintf (stderr, "Unknown option '%c' - exit\n", ch);
            usage();
            exit(1);
        }
    }
    if (optionVals->partName == NULL) {
        fprintf(stderr, "%s: Must use the -p flag to set partition name\n",
                ProgName);
        usage();
        exit(1);
    }
    if (optionVals->rcfName == NULL) {
        fprintf(stderr, "%s: Must use the -c flag to set .rcf name\n",
                ProgName);
        usage();
        exit(1);
    }
    if (optionVals->rvlName == NULL) {
        fprintf(stderr, "%s: Must use the -r flag to set the rvl.bin name\n",
                ProgName);
        usage();
        exit(1);
    }
    if (optionVals->outputName == NULL) {
        char    *suffixPtr, tempName[PATH_LEN];

        suffixPtr = rindex(optionVals->partName, (int) '.');
        if (suffixPtr == NULL) {
            sprintf(tempName, "%s.rvm", optionVals->partName);
        }
        else {
            strcpy(tempName, optionVals->partName);
            suffixPtr = rindex(tempName, (int) '.');
            if (suffixPtr == NULL) {
                fprintf(stderr, "(%s) Can't find '.' in copy of partition name\n",
                ProgName);
                exit(1);
            }
            *suffixPtr = '\0';
            strcat(tempName, ".rvm");
        }
        optionVals->outputName = strdup(tempName);
        if (optionVals->outputName == NULL) {
            fprintf(stderr, "%s: Duplicating output name failed - exit\n",
                    ProgName);
            exit(1);
        }
    }
} // processOptions
/* ------------------------------------------------------------------------ */

void
usage()
{
    fprintf (stderr, "Usage: %s [options] -p partition -c file.rcf -r rvl.bin\n",
                     ProgName);
    fprintf (stderr, 
        " Options:\n"
        " -h, --help            - print usage message\n"
        " -k, --keep            - keep intermediate files (for debugging)\n"
        " -v, --verbose         - print out messages as image is created\n"
        "\n");

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

int
main(int argc, char *argv[])
{
    optionVals_t        optionVals;
    char                *newRcfName;
    int                 exitVal = 1;

    ProgName = argv[0];

    if (Verbose) {
        printf ("%s version 0.02 %s\n", ProgName, __DATE__);
    }
    processOptions(argc, argv, &optionVals);

    if ((newRcfName = genNewRcfFile(&optionVals)) == NULL) {
        fprintf(stderr, "%s: Generating the new .rcf file failed - exiting\n",
                ProgName);
        goto end;
    }
    if (produceImage(&optionVals, newRcfName) == false) {
        goto end;
    }
    exitVal = 0;

end:
    exit(exitVal);
}

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


/*
 * Generate a new .rcf file.  The new rcf file has encryption
 * and hashing turned on, and incorporates the rvl.bin file
 * specified on the command line.
 *
 * Returns the name of the new Rcf file, or NULL if something
 * went wrong.  The name is dynamically allocated.
 */


char *
genNewRcfFile(const optionVals_t* const optionVals)
{
    char                tempName[PATH_LEN];
    FILE                *newRcf = NULL;
    char                *returnVal = NULL;
    DF_DataHeader       diskHeader;
    DF_GameTOC          gameToc;
    off_t               partitionOffset;
    u32                 numGamePartitions;
    u32                 sysVersionHigh, sysVersionLow;
    int                 fileDes;

    strcpy(tempName, ".new_rcf_XXXXXX");

    /*
     * 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 ((fileDes = mkstemp(tempName)) == -1) {
        printf ("%s: Making temporary file failed\n", ProgName);
        goto end;
    }

    if (close(fileDes) != 0) {
        printf ("%s: Closing temporary file failed\n", ProgName);
        goto end;
    }

    if ((newRcf = fopen(tempName, "wb+")) == NULL) {
        fprintf(stderr, "%s: Can't open temporary rcf file '%s'\n",
                ProgName, tempName);
        goto end;
    }
    if (copyBinFileToOutFile(newRcf, optionVals->rcfName) == false) {
        goto end;
    }

    /*
     * Read the information at the beginning of the disk from the
     * new rcf file, which at this point is just a copy of the old
     * file
     */

    if (fseeko(newRcf, (off_t) 0, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Rewinding new rcf file failed\n", ProgName);
        goto end;
    }

    /*
     * Change the no hash and no encrypt bits in the header to 0.
     */
    if (fread(&diskHeader, sizeof(DF_DataHeader), 1, newRcf) != 1) {
        fprintf(stderr, "%s: Can't read header from rcf file\n", ProgName);
        goto end;
    }

    if (   diskHeader.disk_info.t.no_hash != 1
        || diskHeader.disk_info.t.no_encryption != 1) {
        fprintf(stderr, "%s: Error - the rcf file comes from an encrypted disk\n",
        ProgName);
        goto end;
    }

    diskHeader.disk_info.t.no_hash       = 0;
    diskHeader.disk_info.t.no_encryption = 0;

    if (fseeko(newRcf, (off_t) 0, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Rewinding new rcf file failed\n", ProgName);
        goto end;
    }

    if (fwrite(&diskHeader, sizeof(DF_DataHeader), 1, newRcf) != 1) {
        fprintf(stderr, "%s: Can't write header back to rcf file\n", ProgName);
        goto end;
    }

    if (fseeko(newRcf, (off_t) GLOBAL_TOC_OFFSET, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to global TOC offset failed\n",
                 ProgName);
        goto end;
    }
    if (fread(&gameToc, sizeof(DF_GameTOC), 1, newRcf) != 1) {
        fprintf(stderr, "%s: Can't read game TOC from rcf file\n", ProgName);
        goto end;
    }
    partitionOffset = (off_t) (htonl(gameToc.partitionInfos) << 2);
    if (fseeko(newRcf, partitionOffset, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to partition array offset failed\n",
                 ProgName);
        goto end;
    }

    numGamePartitions =  ntohl(gameToc.numGamePartitions);
    if (getSysVersion(numGamePartitions, newRcf,
                      &sysVersionLow, &sysVersionHigh) == false) {
        goto end;
    }

    /*
     * Write the rvl.bin file specified on the command line into the
     * new rcf
     */
    if (fseeko(newRcf, (off_t) GLOBAL_TOC_OFFSET, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to global TOC offset failed\n",
                 ProgName);
        goto end;
    }
    if (copyBinFileToOutFile(newRcf, optionVals->rvlName) == false) {
        goto end;
    }

    /*
     * We don't need to check the return value of strdup, because
     * on an error it returns NULL, which is what this function
     * returns on an error anyway.
     */
    returnVal = strdup(tempName);

end:
    if (newRcf != NULL) {
        if (fclose(newRcf) != 0) {
            fprintf(stderr, "%s: Closing new rcf file failed\n", ProgName);
            returnVal = false;
        }
    }
    /*
     * If something went wrong, get rid of the new rcf file.
     * Don't check the unlink return value - we are already in an
     * error situation.
     */
    if (returnVal == NULL) {
        unlink(tempName);
    }
    return(returnVal);
} // genNewRcfFile

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

/*
 * This code comes from makeRVTR.c.  It gets the system version by
 * reading a field in the e-ticket from partition headers.
 */

bool
getSysVersion(const u32 numGamePartitions, FILE *rcfFile,
              u32 *sysVersionLow, u32 *sysVersionHigh)
{

    // 16 is used because that is what makeRVTR.c does.
    DF_PartitionInfo    partitionInfo[16];
    DF_ESTicket         esTicket;
    off_t               eTicketOffset = 0;
    bool                ticketOffsetSet = false;

    if (fread(partitionInfo,
              sizeof(DF_PartitionInfo) * numGamePartitions,
              1, rcfFile) != 1) {
        fprintf(stderr, "%s: Can't read partition info from rcf file\n",
                ProgName);
        return(false);
    }

    for (int i = 0; i < numGamePartitions; i++) {
        /*
         * Note: not certain this comment is correct.
         * Type 0 == BOOTGAME
         * Type 1 == UPDATE
         * Type 2 == GAME
         * Values from RVL_SDK/securebuild/tools/maketoc/disk_format.h
         */
        if (ntohl(partitionInfo[i].type) == 0x0) {
            eTicketOffset = (ntohl(partitionInfo[i].gamePartition) << 2)
                            + 0x444;
            ticketOffsetSet = true;
        }
    }
    if (ticketOffsetSet == false) {
        fprintf (stderr, "%s: Can't find e-ticket offset\n", ProgName);
        return(false);
    }

    if (fseeko(rcfFile, (off_t) eTicketOffset, SEEK_SET) == -1) {
        fprintf (stderr, "%s: Seeking to e-ticket failed\n", ProgName);
        return(false);
    }

    if (fread(&esTicket, sizeof(DF_ESTicket), 1, rcfFile) != 1) {
        fprintf(stderr, "%s: Can't read header from rcf file\n", ProgName);
        return(false);
    }
    *sysVersionLow  = ntohl(esTicket.sysVersionLow);
    *sysVersionHigh = ntohl(esTicket.sysVersionHigh);

    if (Verbose) {
        printf ("%s: Found system version - high: 0x%x; low: 0x%x\n",
                ProgName, *sysVersionHigh, *sysVersionLow);
    }
    return(true);

} // getSysVersion

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

bool
produceImage(const optionVals_t* const optionVals,
             const char* const newRcfFile)
{
    FILE        *newDlfFile = NULL;
    char        commandBuf[COMMAND_LEN];
    char        dlfName[PATH_LEN];
    int         status;
    bool        returnVal = false;

    /*
     * Create the .dlf file which will be used by the makervm command
     * to create the image
     */
    sprintf(dlfName, "%s.dlf", optionVals->outputName);

    /* This is a regular text file - so don't specify the 'b' flag */
    if ((newDlfFile = fopen(dlfName, "w")) == NULL) {
        fprintf(stderr, "%s: Can't open file %s for writing\n",
                ProgName, dlfName);
        goto end;
    }

    fprintf(newDlfFile, "v2.00\n");
    fprintf(newDlfFile, "RVL_CONFIG_FILE,\"%s\"\n", newRcfFile);
    fprintf(newDlfFile, "0x0000000000000000,\"%s\"\n", optionVals->partName);
    fprintf(newDlfFile, "0x0000000118000000,\"\"\n");

    /*
     * Need to close 'newDlfFile' here because it is used
     * in the makervm command just below
     */
    if (fclose(newDlfFile) != 0) {
        fprintf (stderr, "%s: Closing new dlf file failed\n", ProgName);
        newDlfFile = NULL;
        goto end;
    }
    newDlfFile = NULL;

    /*
     * Create the disk image by invoking the makervm command
     */

    sprintf(commandBuf, "makervm -gc1 %s %s > makervm.out 2>&1",
                         dlfName, optionVals->outputName);
    if (Verbose) {
        printf ("Image creation command is: %s\n", commandBuf);
    }
    status = system(commandBuf);

    if (status == -1) {
        fprintf (stderr, "%s: fork failed for command '%s'\n",
                 ProgName, commandBuf);
        goto end;
    }
    if (WEXITSTATUS(status) != 0) {
        fprintf (stderr, "%s: Creating the disk image failed (command = '%s').\n",
                 ProgName, commandBuf);
        goto end;
    }
    returnVal = true;

end:
    if (optionVals->keepFiles == false) {
        unlink("makervm.out");
    }
    if (newDlfFile != NULL) {
        if (fclose(newDlfFile) != 0) {
            fprintf (stderr, "%s: Closing new dlf file failed\n", ProgName);
        }
        returnVal = false;
    }
    return(returnVal);
} // produceImage

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