#ident "$Id: partition_common.c,v 1.12 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.
 *
 */

/*
 * Functions common to one or more partition commands
 */

#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 "partition_common.h"


#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"group",           1, 0, 'g'},     /* group ID */
    {"help",            0, 0, 'h'},     /* Print usage */
    {"ios",             1, 0, 'i'},     /* IOS version */
    {"output",          1, 0, 'o'},     /* Output image name */
    {"acr",             0, 0, 'R'},     /* Allow ACR access */
    {"titleId",         1, 0, 't'},     /* Title id */             
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {"dvd",             0, 0, 'V'},     /* Allow DVD access */
    {0, 0, 0, 0}
};
#endif

static char* options = "g:hi:o:Rt:Vv";

extern void     usage();
extern char     *ProgName;
extern bool     Verbose;
static void convertBackwardToForwardSlashes(char *string);
/* ------------------------------------------------------------------------ */

#define TMD_ACR_ACCESS_BIT      0x1
#define TMD_DVD_ACCESS_BIT      0x2

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

void
processOptions(int argc, char* argv[], char **contentName,
               char **outputName, u32 *titleId, char **IOSversion,
               char **groupID, bool *keep, u64 *accessBits)
{
    ProgName = argv[0];

    // Default values
    *outputName    = NULL;
    *titleId       = 0xdead;
    *IOSversion    = NULL;
    *groupID       = NULL;
    *keep          = false;
    *accessBits    = 0;

    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 'g':
            *groupID = optarg;
            break;

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

        case 'i':
            *IOSversion = optarg;
            break;

        case 'k':
            *keep = true;
            break;

        case 'o':
            *outputName = optarg;
            break;

      case 'R':
            *accessBits |= TMD_ACR_ACCESS_BIT;
            break;

        case 't':
            /* Input string can be base 8, 10, or 16 */
            *titleId = strtoull(optarg, NULL, 0);
            break;

        case 'v':
            Verbose = true;
            break;

        case 'V':
            *accessBits |= TMD_DVD_ACCESS_BIT;
            break;

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

    if (*outputName == NULL) {
        *outputName = "output.image";
    }
} // processOptions

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

/*
 * Copy the contents of file named 'inFileName' to the file
 * pointed to by outFile
 */

bool
copyFileToOutFile(FILE *outFile, const char* const inFileName)
{
    FILE        *inFile;
    /* Buffer size is arbitrary - make it bigger or smaller if you like */
    uint8_t     buffer[4 * 1024];
    size_t      numRead, numWritten, bufSize;
    bool        done = false;

    if ((inFile = fopen(inFileName, "r")) == NULL) {
        fprintf (stderr, "(%s) Error: Can't open file '%s'\n",
                 ProgName, inFileName);
        return(false);
    }
    bufSize = sizeof(buffer);
    do {
        numRead = fread(buffer, 1, bufSize, inFile);
        if (numRead != bufSize) {
            done = true;
            if (ferror(inFile)) {
                fprintf(stderr, "Read error on file %s\n", inFileName);
                fclose(inFile);
                return(false);
            }
        }
        numWritten = fwrite(buffer, 1, numRead, outFile);
        if (numWritten != numRead) {
            fprintf(stderr, "Write error when copying file %s\n",
                    inFileName);
            fclose(inFile);
            return(false);
        }
    } while (! done);

    fclose(inFile);
    return(true);
} // copyFileToOutFile

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

/*
 * Returns true and the file size in 'fileSize' on success.
 * Returns false on failure.
 */
bool
fileSize(const char* const fileName, off_t *fileSize)
{
    struct stat statBuf;

    if (stat(fileName, &statBuf) == -1) {
        return(false);
    }
    else {
        *fileSize = statBuf.st_size;
        return(true);
    }
}

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

bool
fileExists(const char* const fileName)
{
    struct stat statBuf;

    if (stat(fileName, &statBuf) == -1) {
        return(false);
    }
    else {
        return(true);
    }
}

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

/*
 * Read the contents of the file 'fileName' into an array allocated
 * in this routine.  Output the array and its size.
 * RETURNS:     true            if everything went OK
 *              false           otherwise
 */

bool
readFileIntoArray(const char* const fileName, u8 **array, u32 *size)
{
    FILE        *inFile;
    struct stat statBuf;

    *size = 0;
    *array = NULL;

    if (stat(fileName, &statBuf) == -1) {
        return(false);
    }
    *size = (uint32_t) statBuf.st_size;
    *array = (uint8_t *) malloc(*size);
    if (*array == NULL) {
        fprintf(stderr,
        "Can't allocate %u bytes to hold the contents of file %s\n",
        *size, fileName);
        return(false);
    }
    if ( (inFile = fopen(fileName, "r")) == NULL) {
        fprintf (stderr, "%s: Can't open file %s\n", ProgName, fileName);
        free(*array);
        return(false);
    }
    if (fread(*array, *size, 1, inFile) != 1) {
        fprintf (stderr, "%s: Can't read file %s\n", ProgName, fileName);
        free(*array);
        fclose(inFile);
        return(false);
    }
    fclose(inFile);
    return(true);
}

/* ------------------------------------------------------------------------ */
bool
readCertBlob(const char* const pkiRoot, u8 **certArray, u32 *certBlobSize,
             const bool production, const bool verbose)
{
    char        certFileName[256];

    if (production) {
        fprintf(stderr, "Warning: production using developer certs\n");
        sprintf(certFileName, "%scert_dpki.sys", pkiRoot);
    }
    else {
        sprintf(certFileName, "%scert_dpki.sys", pkiRoot);
    }

    if (verbose) {
        printf ("Using certificates from: '%s'\n", certFileName);
    }
       
    if (readFileIntoArray(certFileName, certArray, certBlobSize) == false) {
        fprintf(stderr, "%s: Reading certificates from %s failed\n",
                ProgName, certFileName);
        return(false);
    }
    else {
        return(true);
    }
}

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

/*
 * INPUTS: encryptedTitleKeyFile
 * OUTPUT: *ticketName
 */
bool
generateEticket(const char* const binRoot,
                const char* const encryptedTitleKeyFile, 
                const u64 titleID,
                const bool production,
                const bool verbose,
                char *ticketName)
{
    char        commandBuf[1024];
    int         status;
    u64         ticketId;
    FILE        *randomInput;


    /*
     * Top 16 bits of ticket id is partner ID, lower 48 bits is random
     */
    if ((randomInput = fopen("/dev/random", "r")) == NULL) { 
        fprintf (stderr, "%s: Can't open /dev/random for reading - exit\n",
                 ProgName);
        exit(1);
    }
    if ( fread(&ticketId, sizeof(u64), 1, randomInput) != 1) {
        fprintf(stderr, "%s: Can't read %u bytes from /dev/random - exit\n",
                ProgName, sizeof(u64));
        exit(1);
    }
    fclose(randomInput);

    ticketId &= ~(0xffffULL << 48); 
    ticketId |=  ((u64) NINTENDO_PARTNER_ID << 48);

    sprintf (commandBuf, "%sticket -O -t 0x%llx -T 0x%llx -K %s",
             binRoot, ticketId, titleID, encryptedTitleKeyFile);
    if (production) {
        fprintf(stderr, "Warning: production using developer ticket\n");
        strcat (commandBuf, " -P d");               // devel PKI
    }
    else {
        strcat (commandBuf, " -P d");               // devel PKI
    }
    strcat (commandBuf, " > ticket.out 2>&1 ");
    if (verbose) {
        printf ("Ticket command is: '%s'\n", commandBuf);
    }
    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: e-ticket create command '%s' failed.\n",
                 ProgName, commandBuf);
        return(false);
    }

    sprintf(ticketName, "%" PRIx64 ".tik", ticketId);
    if (! fileExists(ticketName)) {
        fprintf (stderr, "%s: expected 'ticket' to create file %s\n",
                 ProgName, ticketName);
        return(false);
    }

    return(true);
} // generateEticket

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

/*
 * Get the proper location of the root directory, underneath which
 * is found the binaries.  Look in REVOLUTION_SDK_ROOT, then ROOT.
 * If both are not defined, print an error message.
 *
 * The user of this function should free the returned string
 * after it is done.
 */

#define PLAIN_BIN_PATH "/usr/bin/x86/"
#define PLAIN_PKI_PATH "/usr/etc/pki_data/"

#define RVL_BIN_PATH   "/x86/bin/"
#define RVL_PKI_PATH   "/x86/bin/pki_data/"
void
getRoot(char **binRoot, char **pkiRoot)
{
    char        *root;
    size_t      rootLen, mallocLen;

    if ((root = getenv("REVOLUTION_SDK_ROOT")) != NULL) {
        if (Verbose) {
            printf ("%s: Using REVOLUTION_SDK_ROOT to find binaries\n",
                    ProgName);
        }
        convertBackwardToForwardSlashes(root);
        rootLen = strlen(root);
        // Chop off trailing / in environment variable, if any
        if (root[rootLen - 1] == '/') {
            root[rootLen - 1] = '\0';
        }

        mallocLen = strlen(root) + strlen(RVL_BIN_PATH) + 1;
        if ((*binRoot = malloc(mallocLen)) == NULL) {
            fprintf(stderr, "%s: Malloc of %u bytes failed\n",
                    ProgName, mallocLen);
            exit(1);
        }
        strcpy(*binRoot, root);
        strcat(*binRoot, RVL_BIN_PATH);

        mallocLen = strlen(root) + strlen(RVL_PKI_PATH) + 1;
        if ((*pkiRoot = malloc(mallocLen)) == NULL) {
            fprintf(stderr, "%s: Malloc of %u bytes failed\n",
                    ProgName, mallocLen);
            exit(1);
        }
        strcpy(*pkiRoot, root);
        strcat(*pkiRoot, RVL_PKI_PATH);
    }
    else if ((root = getenv("ROOT")) != NULL) {
        printf ("%s: Note - REVOLUTION_SDK_ROOT not defined, using ROOT\n",
                 ProgName);
        convertBackwardToForwardSlashes(root);
        rootLen = strlen(root);
        // Chop off trailing / in environment variable, if any
        if (root[rootLen - 1] == '/') {
            root[rootLen - 1] = '\0';
        }

        mallocLen = strlen(root) + strlen(PLAIN_BIN_PATH) + 1;
        if ((*binRoot = malloc(mallocLen)) == NULL) {
            fprintf(stderr, "%s: Malloc of %u bytes failed\n",
                    ProgName, mallocLen);
            exit(1);
        }
        strcpy(*binRoot, root);
        strcat(*binRoot, PLAIN_BIN_PATH);

        mallocLen = strlen(root) + strlen(PLAIN_PKI_PATH) + 1;
        if ((*pkiRoot = malloc(mallocLen)) == NULL) {
            fprintf(stderr, "%s: Malloc of %u bytes failed\n",
                    ProgName, mallocLen);
            exit(1);
        }
        strcpy(*pkiRoot, root);
        strcat(*pkiRoot, PLAIN_PKI_PATH);
    }
    else {
        fprintf (stderr, "%s: Must set environment variable REVOLUTION_SDK_ROOT or ROOT - exit\n", ProgName);
        exit(1);
    }
} // getRoot
/* ------------------------------------------------------------------------ */
static void
convertBackwardToForwardSlashes(char *str)
{
    char *ptrToSlash;

    while ( (ptrToSlash = index(str, '\\')) != NULL) {
        *ptrToSlash = '/';
    }
}
/* ------------------------------------------------------------------------ */
