#ident "$Id: partition_common.c,v 1.49 2008/06/17 22:34:16 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.
 *
 */

/*
 * 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 <errno.h>
#include <dirent.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>

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

/*
 * See Makefile for explanation of IRD and PRODUCTION preprocessor flags
 */

#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"group",           1, 0, 'g'},     /* group Id */
    {"titleVersion",    1, 0, 'I'},     /* title version */
    {"ios",             1, 0, 'i'},     /* IOS version */
    {"nand",            0, 0, 'n'},     /* Generate NAND disc application */
    {"output",          1, 0, 'o'},     /* Output image name */
#if !defined(IRD)
    {"production",      1, 0, 'p'},     /* Use production PKI */
                                        /* This only works with */
                                        /* make_ndev_partition */
    {"rm",              1, 0, 'r'},     /* Set RM access control*/
#endif
    {"version",         0, 0, 'q'},     /* Print version and stop */
    {"stopDirectory",   1, 0, 's'},     /* Stop after generating ticket, tmd */
    {"titleId",         1, 0, 't'},     /* Title id */             
    {"tmd",             1, 0, 'T'},     /* Input TMD */
    {"cert",            1, 0, 'x'},     /* Certificate file */
#if defined(ENABLE_DATA_ACCESS_TITLE)
    {"dataTitle",       0, 0, 'd'},     /* data title */
    {"accessTitleId",   0, 0, 'a'},     /* accessTitleId in eTicket */
    {"accessTitleMask", 0, 0, 'A'},     /* accessTitleMask in eTicket */
#endif
#if !defined(IRD)
    {"combine",         1, 0, 'c'},     /* only combine files into partition */
    {"help",            0, 0, 'h'},     /* Print usage */
    {"keep",            0, 0, 'k'},     /* keep intermediate files */
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
#endif
#if defined(PRODUCTION)
    {"acr",             0, 0, 'R'},     /* Allow ACR access */
    {"dvd",             0, 0, 'V'},     /* Allow DVD access */
    {"code",            0, 0, 'L'},     /* limit code(s) string */
    {"limit",           0, 0, 'l'},     /* limit value(s) string */
#endif
    {0, 0, 0, 0}
};
#endif

#if defined(ENABLE_DATA_ACCESS_TITLE)
#if defined(DEVELOPER) && defined(IRD)
static char* options = "g:I:i:no:qs:T:t:x:dA:a:";
#elif defined(DEVELOPER)
static char* options = "c:g:hI:i:kno:pqr:s:T:t:vx:dA:a:";
#elif defined(PRODUCTION)
static char* options = "c:g:hI:i:kL:l:no:pqr:Rs:T:t:Vvx:dA:a:";
#else
#error Must #define either DEVELOPER or PRODUCTION
#endif
#else
#if defined(DEVELOPER) && defined(IRD)
static char* options = "g:I:i:no:qs:T:t:x:";
#elif defined(DEVELOPER)
static char* options = "c:g:hI:i:kno:pqr:s:T:t:vx:";
#elif defined(PRODUCTION)
static char* options = "c:g:hI:i:kL:l:no:pqr:Rs:T:t:Vvx:";
#else
#error Must #define either DEVELOPER or PRODUCTION
#endif
#endif  /* !ENABLE_DATA_ACCESS_TITLE */

#if !defined(IRD)
extern void     usage();
extern bool     Verbose;
#endif
extern char     *ProgName;
static bool     handleTitleId(u64 inputTitleId, u64 *outputTitleId);
/* ------------------------------------------------------------------------ */

/*
 * Process the command line arguments.
 * INPUT:      argc and argv from main()
 *             optionVals struct to be filled in.
 * OUTPUT:
 *              Sets the titleKey
 */

void
processOptions(int argc, char* argv[], optionVals_t* const optionVals)
{
    u64         inputTitleId;

    ProgName = argv[0];

    // Default values
    optionVals->outputName              = NULL;
    optionVals->titleId                 = ((u64) NINTENDO_PARTNER_ID << ES_PARTNER_ID_SHIFT) | 
                                          ((u64) NINTENDO_PERM_TITLE_CHANNEL << ES_CHANNEL_ID_SHIFT) |
                                          0xdead;
    optionVals->IOSversion              = "0x0000000100000004";
    optionVals->titleVersion            = "0x0";
    optionVals->groupId                 = "0x0002";
    optionVals->accessBits              = 0;
    optionVals->keepFiles               = false;
    optionVals->limitCodes              = NULL;
    optionVals->limitValues             = NULL;
    optionVals->useProduction           = false;
    optionVals->isNand                  = false;
    optionVals->inputTmd                = NULL;
    optionVals->stopDirectory           = NULL;
    optionVals->combineDirectory        = NULL;
    optionVals->certFile                = NULL;
    optionVals->versionOnly             = false;
    optionVals->rmAccess                = NULL;
    optionVals->bootIndex               = 0;
    optionVals->accessTitleId           = 0;
    optionVals->accessTitleMask         = 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':
            optionVals->groupId = optarg;
            break;


        case 'I':
            optionVals->titleVersion = optarg;
            break;

        case 'i':
            optionVals->IOSversion = optarg;
            break;


        case 'L':
            optionVals->limitCodes = optarg;
            break;

        case 'l':
            optionVals->limitValues = optarg;
            break;

        case 'n':
            optionVals->isNand = true;
            break;

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

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

        case 'q':
            optionVals->versionOnly = true;
            break;

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

#if defined(ENABLE_DATA_ACCESS_TITLE)
        case 'd':
            optionVals->bootIndex = ES_MAX_CONTENT-1;
            break;

        case 'a':
            optionVals->accessTitleId = strtoull(optarg, NULL, 0);
            break;

        case 'A':
            optionVals->accessTitleMask = strtoull(optarg, NULL, 0);
            break;
#endif

        case 's':
            optionVals->stopDirectory = optarg;
            break;

        case 'T':
            optionVals->inputTmd = optarg;
            break;

        case 't':
            /* Input string can be base 8, 10, or 16 */
            inputTitleId = strtoull(optarg, NULL, 0);
            if (handleTitleId(inputTitleId, &(optionVals->titleId)) == false) {
                fprintf (stderr,
                         "%s: Error - Illegal title ID '%s' - exiting\n",
                         ProgName, optarg);
                exit(1);
            }
            break;

        /*
         * This is used by the Content licensing server software
         * It doesn't use the PKI files in $ROOT
         */
        case 'x':
            optionVals->certFile = optarg;
            break;

#if !defined(IRD)
        case 'c':
            optionVals->combineDirectory = optarg;
            break;

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

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

        case 'v':
            Verbose = true;
            break;
#endif
#if defined(PRODUCTION)
        case 'R':
            optionVals->accessBits |= TMD_ACR_ACCESS_BIT;
            break;

        case 'V':
            optionVals->accessBits |= TMD_DVD_ACCESS_BIT;
            break;
#endif

        default:
            fprintf (stderr, "Unknown option '%c' - exit\n", ch);
#if !defined(IRD)
            usage();
#endif
            exit(1);
        }
    }
    if (optind >= argc
        && optionVals->combineDirectory == NULL
        && optionVals->versionOnly == false) {
        fprintf (stderr, "%s: Need partition name\n", argv[0]);
#if !defined(IRD)
        usage();
#endif
        exit(1);
    }
    if (optind < argc) {
        optionVals->contentOrPrefixName = argv[optind];
    }
    /*
    if (optionVals->inputTmd != NULL && optionVals->isNand == false) {
        fprintf (stderr,
                 "%s: Error - input TMD given, but nand flag not given - exit\n",
                 argv[0]);
        exit(1);
    }
    */

    if (optionVals->outputName == NULL) {
        optionVals->outputName = "output.image";
    }
    if (   optionVals->combineDirectory != NULL
        && optionVals->stopDirectory    != NULL) {
        fprintf (stderr, "%s: Error - Can't specify both combine and stop at the same time\n", ProgName);
        exit(1);
    }
} // processOptions

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

/*
 * Given an input title id, do the following:
 *
 * - If the upper 32 bits are 0, make the upper 32 bits the Nintendo
 *   partner id and permanent channel id.
 *   Return true;
 *
 * - If the upper 32 bits are not zero, check to see if the value is
 *   on the allowed list.  If so, set ouputTitleId equal to
 *   inputTitleId and return true.
 *   If not, return false.
 *
 */
static u32 allowedUpperTitleId[] = {  
                                        NINTENDO_PARTNER_ID << 16
                                      | NINTENDO_PERM_TITLE_CHANNEL,
                                        NINTENDO_PARTNER_ID << 16
                                      | NINTENDO_DISC_NAND_CHANNEL,

                                     0x00000001};
static bool
handleTitleId(u64 inputTitleId, u64 *outputTitleId)
{
    u32         upperId, lowerId;
    bool        returnVal = false;

    lowerId = inputTitleId & 0xFFFFFFFF;
    upperId = inputTitleId >> 32;
    *outputTitleId = 0xdeadcafebeefbeef;   // Init to nonsense value

    /*
     * Zero is not a legal value, so substitute the correct value
     */
    if (upperId == 0x0) {
        *outputTitleId = ((u64) NINTENDO_PARTNER_ID << ES_PARTNER_ID_SHIFT) | 
                         ((u64) NINTENDO_PERM_TITLE_CHANNEL << ES_CHANNEL_ID_SHIFT) |
                         lowerId;
        returnVal = true;
    }
    else {
        int     numLegalUpperIds;

        numLegalUpperIds = sizeof(allowedUpperTitleId) / sizeof(u32);
        for (int i = 0; i < numLegalUpperIds; i++) {
            if (allowedUpperTitleId[i] == upperId) {
                *outputTitleId = inputTitleId;
                returnVal = true;
                break;
            }
        }
    }
    return(returnVal);
}
/* ------------------------------------------------------------------------ */

/*
 * RETURN true      if file 'fileName' exists.
 *        false     otherwise
 */
bool
fileExists(const char* const fileName)
{
    struct stat statBuf;

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

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

/*
 * Read a file of certificates from the PKI root directory
 * into a dynamically-allocated array.
 * INPUTS:
 *          pkiRoot   - The directory containing the certificate file.
 *          certArray - handle to the array.  On return points
 *                      to the block containing the certs
 *          certBlobSize - On return, contains size of cert array.
 */

bool
readCertBlob(const char* const pkiRoot, u8 **certArray, u32 *certBlobSize,
             const bool production)
{
    char        certFileName[FILE_NAME_MAX];

    if (production) {
        sprintf(certFileName, "%scert_ppki.sys", pkiRoot);
    }
    else {
        sprintf(certFileName, "%scert_dpki.sys", pkiRoot);
    }

#if !defined(IRD)
    if (Verbose) {
        printf ("Using certificates from: '%s'\n", certFileName);
    }
#endif
       
    if (readBinFileIntoArray(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         titleID64,
                const char* const limitCodes,
                const char* const limitValues,
                const u32         accessTitleId, 
                const u32         accessTitleMask,
                const bool        production,
                const bool        keepFiles,
                char              *ticketName)
{
    char        commandBuf[COMMAND_BUF_LEN];
    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", "rb")) == NULL) { 
        fprintf (stderr, "%s: Can't open /dev/random for reading\n",
                 ProgName);
        return(false);
    }
    if ( fread(&ticketId, sizeof(u64), 1, randomInput) != 1) {
        fprintf(stderr, "%s: Can't read %u bytes from /dev/random\n",
                ProgName, sizeof(u64));
        return(false);
    }
    if (fclose(randomInput) != 0) {
#if !defined(IRD)
        fprintf(stderr, "%s: Closing of /dev/random failed (%s) - continuing\n",
                ProgName, strerror(errno));
#endif
    }


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

#if defined(ENABLE_DATA_ACCESS_TITLE)
    sprintf (commandBuf, "%s%s -O -t 0x%llx -T 0x%llx -K %s -E 0x%x -e 0x%x ",
             binRoot, TICKET_BINARY,
             ticketId, titleID64, encryptedTitleKeyFile, 
             accessTitleId, accessTitleMask);
#else
    sprintf (commandBuf, "%s%s -O -t 0x%llx -T 0x%llx -K %s",
             binRoot, TICKET_BINARY,
             ticketId, titleID64, encryptedTitleKeyFile);
#endif

    /* Set the sysAccessMask to 0xFFFF */
    strcat (commandBuf, " -a 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15");

    if (production) {
        strcat (commandBuf, " -P p");               // production PKI
    }
    else {
        strcat (commandBuf, " -P d");               // devel PKI
    }
#if defined(PRODUCTION)
    if (limitCodes != NULL) {
        strcat (commandBuf, " -L ");
        strcat (commandBuf, limitCodes);
    }
    if (limitValues != NULL) {
        strcat (commandBuf, " -l ");
        strcat (commandBuf, limitValues);
    }
#endif

    if (keepFiles) {
        strcat (commandBuf, " > ticket.out 2>&1 ");
    }
    else {
        strcat (commandBuf, " > /dev/null 2>&1 ");
    }
#if !defined(IRD)
    if (Verbose) {
        printf ("Ticket command is: '%s'\n", commandBuf);
    }
#endif
    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

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

/*
 * Look through directory entries contained in dirPtr for files
 * ending in 'nameExtension'.  If there is exactly one such file,
 * store it in the array pointed to by 'pathName' and return true.
 * Else, return false
 */
bool
getTypedFileName(DIR *dirPtr, const char* const dirName,
                 const char *nameExtension, char *pathName)
{
    struct dirent       *entry;
    size_t              entryLen, extensionLen;
    char                *entryPtr;
    bool                fileFound = false;
    char                fileName[FILE_NAME_MAX];

    extensionLen = strlen(nameExtension);

    while ((entry = readdir(dirPtr)) != NULL) {
        entryLen = strlen(entry->d_name);
        if (entryLen >= extensionLen) {
            entryPtr = entry->d_name + (entryLen - extensionLen);
            if (strcmp(entryPtr, nameExtension) == 0) {
                if (fileFound == true) {
                    fprintf (stderr, "%s: Two files found with extension %s (%s and %s)\n",
                            ProgName, nameExtension, fileName, entry->d_name);
                    return(false);
                }
                else {
                    fileFound = true;
                    strcpy(fileName, entry->d_name);
                }
            }
        }
    }
    if (fileFound == false) {
        fprintf (stderr, "%s: No files found with extension %s\n",
                 ProgName, nameExtension);
        return(false);
    }
    else {
        sprintf(pathName, "%s/%s", dirName, fileName);
        return(true);
    }
} // getTypedFileName
/* ------------------------------------------------------------------------ */
