#ident "$Id: rvl_partition.c,v 1.7 2006/06/30 04:08:31 craig Exp $"
/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/*
 * Program to generate RVL secure DVD images.
 * By default, only generates file bytes from the security
 * area onwards.
 *
 * 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 <getopt.h>
#include <inttypes.h>
#include <netinet/in.h>         // For htonl()
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

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

#if defined(DEVELOPER)
#include "devel_key.h"
// This should have been declared in stdlib.h
int mkstemp(char *template);
#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 char* const contentName, const u64 titleId,
                 char *tmdFileName,
                 char *encryptedContentName, char *h3FileName,
                 char *titleKeyName, const char* const IOSversion,
                 const char* const groupID, const bool keepFiles,
                 const u64 accessBits);

bool generatePartition(const char* const contentName,
                       const char* const outputName,
                       const u32         inputTitleId,
                       const char* const IOSversion,
                       const char* const groupID,
                       const bool        keepFiles,
                       const u64         accessBits);


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

char            *ProgName;

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

void
usage()
{
    fprintf (stderr, "Usage: %s [options] raw_partition\n", ProgName);
    fprintf (stderr,
        " -g, --group <group ID>    - specify group ID\n"
        " -h, --help            - print usage message\n"
        " -k, --keep            - keep intermediate files\n"
        " -i, --ios <ios version>   - specify IOS version\n"
        " -o, --out <file>      - output image name [default: output.image]\n"
        " -t, --titleId <id>    - title key         [default: 0xdead]\n"
        " -v, --verbose         - print out messages as image is created\n"
        " -R, --acr             - allow partition to have ACR access\n"
        " -V, --dvd             - allow partition to have DVD access\n");
     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");

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

int
main(int argc, char *argv[])
{
    char        *contentName, *outputFileName;
    char        *IOSversion, *groupID;
    u32         inputTitleId;
    u64         accessBits;
    bool        keepFiles;

    ProgName = argv[0];

    processOptions(argc, argv, &contentName, &outputFileName, &inputTitleId,
                   &IOSversion, &groupID, &keepFiles, &accessBits);

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

    if (generatePartition(contentName, outputFileName,
                          inputTitleId, IOSversion, groupID, keepFiles,
                          accessBits) == false) {
        fprintf (stderr, "%s: Generation of partition failed\n",
                 ProgName);
        exit(1);
    }
    exit(0);
}


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


/*
 * INPUT:  an unsigned integer N which is a power of 2
 * OUTPUT: an unsigned integer which has log2(N) 1 bits in the lower
 *         part of the word
 */

inline off_t
log2Mask(off_t powerOf2)
{
    off_t    mask;

    if (powerOf2 == 0) {
        printf ("(%s) Error: can't take log of 0\n", ProgName);
        exit(1);
    }

    mask = 0;
    for (int i = 0; i < sizeof(off_t) * 8; i++) {
        if ((powerOf2 & 0x1) == 0x1) {
            return(mask);
        }
        else {
            mask <<= 1;
            mask |= 0x1;
            powerOf2 >>= 1;
        }
    }
    fprintf (stderr, "Code should never reach here!\n");
    exit(1);
}

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

inline off_t
alignOffset(off_t address, const u32 alignment)
{
    u32    alignmentMask;
    off_t       addVal;

    alignmentMask = log2Mask((off_t) alignment);
    if ((address & alignmentMask) == 0) {
        return(address);
    }
    else {
        addVal = alignmentMask + 1;
        address &= ~alignmentMask;
        address += addVal;
        return(address);
    }
}

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

bool
generateTmd(const char* const binRoot, const char* const pkiRoot,
            const char* const contentName, const u64 titleId,
            char *tmdName, char *encryptedContentName,
            char* h3HashName, char* titleKeyName,
            const char* const IOSversion, const char* const groupID,
            const bool keepFiles, const u64 accessBits)
{
    char        commandBuf[1024];
    int         status;
    u32         contentCID = 0;
    bool        returnVal = true;
#ifdef DEVELOPER
    char *encryptTitleKeyFile = NULL;
#endif


    sprintf (commandBuf, "%stmd -O -T 0x%" PRIx64
                          " -c 0x%x"
                          " -r 0x%" PRIx64,
                          binRoot, titleId, contentCID, accessBits);
    strcat (commandBuf, " -i 0");               // content index is 0
#if defined(DEVELOPER)
    strcat (commandBuf, " -P d");               // devel PKI
#elif defined (PRODUCTION)
    fprintf(stderr, "Warning: production using developer TMD\n");
    strcat (commandBuf, " -P d");               // devel PKI
#endif
    strcat (commandBuf, " -n  ");               // content name
    strcat (commandBuf, contentName);           // input content
    strcat (commandBuf, " -t 2");               // content is shared
    strcat (commandBuf, " -d ");                // disk encryption
    if (IOSversion != NULL) {
        strcat (commandBuf, " -o ");
        strcat (commandBuf, IOSversion);
    }
    if (groupID != NULL) {
        strcat (commandBuf, " -g ");
        strcat (commandBuf, groupID);
    }
#ifdef DEVELOPER
    encryptTitleKeyFile = createDevelTitleKeyFile(pkiRoot, develKey, titleId);
    if (encryptTitleKeyFile == NULL) {
        returnVal = false;
        goto end;
    }
    strcat (commandBuf, " -K ");
    strcat (commandBuf, encryptTitleKeyFile);
#endif

    strcat (commandBuf, " > tmd.out 2>&1 ");

    if (Verbose) {
        printf ("TMD command is: %s\n", commandBuf);
    }
    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", contentCID);
    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", contentCID);
    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) {
        unlink(encryptTitleKeyFile);
    }
#endif
    return(returnVal);
} // generateTmd

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

/*
 *
 * 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
 *
 */

bool
generatePartition(const char* const contentName,
                  const char* const outputName,
                  const u32         inputTitleId,
                  const char* const IOSversion,
                  const char* const groupID,
                  const bool        keepFiles,
                  const u64         accessBits)
{
    FILE                *outFile;
    partition_t         partition, partitionOnDisk;
    off_t               fileOffset, partitionStart, tmdStart;
    off_t               certBlobStart, h3HashStart, cryptAreaStart;
    char                tmdName[64], encryptedContentName[64], h3HashName[64];
    char                ticketName[64], titleKeyName[64];
    u32                 ticketSize;
    u8                  *ticket, *tmd, *certBlob;
    u64                 titleId;
    char                *binRoot, *pkiRoot;

    if (Verbose) {
        printf ("Partition size is: %u\n", sizeof(partition_t));
    }
    
    if ((outFile = fopen(outputName, "w")) == NULL) {
        fprintf(stderr, "Can't open output file '%s'\n", outputName);
        return(false);
    }

    titleId = ((u64) NINTENDO_PARTNER_ID         << ES_PARTNER_ID_SHIFT) | 
              ((u64) NINTENDO_PERM_TITLE_CHANNEL << ES_CHANNEL_ID_SHIFT) |
              inputTitleId;

    getRoot(&binRoot, &pkiRoot);

    if (generateTmd(binRoot, pkiRoot, contentName, titleId, tmdName,
                    encryptedContentName,
                    h3HashName, titleKeyName,
                    IOSversion, groupID, keepFiles, accessBits) == false) {
        return(false);
    }
#ifdef DEVELOPER
    if (generateEticket(binRoot, titleKeyName, titleId, false,
                        Verbose, ticketName) == false) {
        return(false);
    }
#else
    if (generateEticket(binRoot, titleKeyName, titleId, true,
                        Verbose, ticketName) == false) {
        return(false);
    }
#endif
    
    /* Read E-ticket into game partition */
    if (readFileIntoArray(ticketName, &ticket, &ticketSize) == false) {
        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);

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

#ifdef DEVELOPER
    if (readCertBlob(pkiRoot, &certBlob, &(partition.certBlobSize), false,
                     Verbose) == false) {
        return(false);
    }
#else
    if (readCertBlob(pkiRoot, &certBlob, &(partition.certBlobSize), true,
        Verbose) == false) {
        return(false);
    }
#endif


    fileOffset = ftell(outFile);

    partitionStart = alignOffset(fileOffset, PARTITION_ALIGN);

    tmdStart = partitionStart + sizeof(partition_t);
    tmdStart = alignOffset(tmdStart, ITEM_ALIGN);
    certBlobStart = alignOffset(tmdStart + partition.tmdSize, ITEM_ALIGN);
    h3HashStart = certBlobStart + partition.certBlobSize;
    h3HashStart = alignOffset(h3HashStart, H3_ALIGN);
    cryptAreaStart = alignOffset(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);

    partitionOnDisk = partition;
    partitionOnDisk.tmdSize      = htonl(partition.tmdSize);
    partitionOnDisk.certBlobSize = htonl(partition.certBlobSize);
    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);
    }
    /*
     * 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 (copyFileToOutFile(outFile, h3HashName) == false) {
        return(false);
    }

    /* Write out content */
    if (fseeko(outFile, cryptAreaStart, SEEK_SET) == -1) {
        perror("fseeko");
        return(false);
    }
    if (copyFileToOutFile(outFile, encryptedContentName) == false) {
        return(false);
    }
    free(tmd);
    free(certBlob);
    fclose(outFile);
    if (keepFiles == false) {
        unlink(encryptedContentName);
        unlink(h3HashName);
        unlink(tmdName);
        unlink(ticketName);
        unlink(titleKeyName);
    }

    return(true);
} // generatePartition

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

#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

char *strdup(const char* const string);
#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.
 */

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[512], *titleKeyName;
    u8     *commonKey;
    u32    commonKeySize;
    int    tempFD;
    u64    titleIdNetwork;


    /* Get the common key used to encrypt the title key */
    sprintf(commonKeyName, "%scommon_dpki.aesKey", pkiRoot);
    if (readFileIntoArray(commonKeyName, &commonKey, &commonKeySize) == false) {
        fprintf(stderr, "Can't read common key file %s\n", commonKeyName);
        return(NULL);
    }
    if (commonKeySize != AES_KEY_LENGTH) {
        fprintf(stderr,
                "Length of file %s (%u) doesn't match AES key length %d\n",
                commonKeyName, commonKeySize, AES_KEY_LENGTH);
        return(NULL);
    }

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

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

    titleKeyName = strdup(FILE_TEMPLATE);
    if ((tempFD = mkstemp(titleKeyName)) == -1) {
        perror("mkstemp");
        return(NULL);
    }
    if (write(tempFD, encryptedKey, AES_KEY_LENGTH) != AES_KEY_LENGTH) {
        fprintf (stderr, "Can't write encrypted key to file %s\n",
                          titleKeyName);
        close(tempFD);
        unlink(titleKeyName);
        return(NULL);
    }
    close(tempFD);
    return(titleKeyName);
}

/* ------------------------------------------------------------------------ */
/*
 * Duplicate a string.  Exit if memory can't be allocated.
 */

char *
strdup(const char* const string)
{
    char        *returnVal;

    returnVal = malloc(strlen(string) + 1);
    if (returnVal == NULL) {
        fprintf (stderr, "Can't allocate storage for string %s\n", string);
        exit(1);
    }
    strcpy(returnVal, string);
    return(returnVal);
}
#endif
/* ------------------------------------------------------------------------ */
