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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <getopt.h>
#include <errno.h>
#include <time.h>
#include <limits.h>
#include <netinet/in.h>
#include <openssl/md5.h>

#include "esl.h"
#include "es_int.h"
#include "csl.h"
#include "rsautil.h"
#include "aes.h"
#include "utils.h"

extern int encryptDiskContent(const char* contentFile, ESContentId cid,
                              const u8* titleKey, u8* const h4Hash);

#if !defined(__CYGWIN__)
#if !defined(RVL_IRD)
static struct option __longOptions[] = {
    {"IN", 1, 0, 'I'},            /* input TMD file */
    {"OUT", 1, 0, 'O'},           /* generate new TMD file */
    {"sub", 1, 0, 'S'},           /* generate new subscription key or TMD
                                     using subscription key */
    {"KEY", 1, 0, 'K'},           /* input titleKey file */
    {"titleId", 1, 0, 'T'},       /* titleId */
    {"titleType", 1, 0, 'C'},     /* title type */
    {"contentFiles", 1, 0, 'n'},  /* list of content files */
    {"cids", 1, 0, 'c'},          /* list of CIDs */
    {"index", 1, 0, 'i'},         /* list of content index */
    {"types", 1, 0, 't'},         /* list of content types */
    {"crlVersions", 1, 0, 'v'},   /* list of CRL versions */
    {"sysVersion", 1, 0, 'o'},    /* os version */
    {"titleVersion", 1, 0, 'm'},  /* title version */
    {"groupId", 1, 0, 'g'},       /* Group ID */
    {"rights", 1, 0, 'r'},        /* title rights bits */
    {"reserved", 1, 0, 'R'},      /* 32 byte reserved data for Nintendo */
    {"reserved2", 1, 0, 'B'},     /* 30 byte reserved data from BroadOn */
    {"bootIndex", 1, 0, 'b'},     /* boot index */
    {"PKI", 1, 0, 'P'},           /* type of PKI */
    {"commonKey", 1, 0, 'k'},     /* commonKey used to encrypt titleKey */
    {"cpCert", 1, 0, 's'},        /* CP server cert */
    {"cpData", 1, 0, 'D'},        /* CP server RSA data file, for signing */
    {"print", 1, 0, 'p'},         /* verify and dump fields of TMD */
    {"disk", 0, 0, 'd'},          /* do NextGen/RVL disk encryption */
    {"cmdOut", 0, 0, 'a'},        /* output CMD files */
    {"cmdIn", 1, 0, 'A'},         /* input CMD files */
    {"size", 0, 0, 'V'},          /* print out sizes of various structs */
    {"help", 0, 0, 'h'},          /* print usage */
    {0, 0, 0, 0}
};
#endif
#endif

#if !defined(RVL_IRD) 
static char* __options = "I:OSK:T:C:n:c:i:t:v:o:m:r:g:N:B:b:P:k:s:D:paA:dVh";
#else
static char* __options = "OK:T:C:n:c:i:o:b:m:g:t:dN:s:P:D:";
#endif

#define ES_NIN_RESERVED_SIZE   32
#define ES_BO_RESERVED_SIZE    30

static char* __inTmdFile = NULL;
static const char* __titleKeyFile = NULL;
static char __commonKeyFile[PATH_MAX];
static char __cpCertFile[PATH_MAX];
static char __cpRsaFile[PATH_MAX];
static char __outTmdFile[PATH_MAX];
static char __outKeyFile[PATH_MAX];
static ESTitleId __tid = 0;
#if defined(RVL_IRD)
static ESTitleType __ttype = ES_TITLE_TYPE_NG_TITLE;
static u16 __groupId=2;
static ESSysVersion __sysVersion=(((u64)ES_SYS_CHANNEL_RVL)<<32) | 4;
static char __pki='d';
#else
static ESTitleType __ttype = ES_TITLE_TYPE_NC_TITLE;
static u16 __groupId=ES_DEFAULT_GID;
static ESSysVersion __sysVersion=0;
static char __pki=0;
#endif
static u16 __numContents = 0;
static u16 __numInCmds = 0;
static char *__contentFiles[ES_MAX_CONTENT];
static char *__cmdFiles[ES_MAX_CONTENT];
static ESContentId __cids[ES_MAX_CONTENT];
static u16 __types[ES_MAX_CONTENT];
static u16 __index[ES_MAX_CONTENT];
static CSLOSSha1Hash __hash[ES_MAX_CONTENT];
static u16 __bidx=0;
static u32 __rights=0;
static u8 __reserved1[ES_NIN_RESERVED_SIZE];
static u8 __reserved2[ES_BO_RESERVED_SIZE];
static ESVersion __caCrlVersion=0;
static ESVersion __cpCrlVersion=0;
static ESTitleVersion __titleVersion=0;
static int __dump=0;
static int __create=0;
static int __diskEncryption=0;
static ESTitleMeta __tmd;
static ESContentMeta __cmds[ES_MAX_CONTENT];
static int __sub = 0;
static int __cmdOut = 0;

static void
usage(const char* progName)
{
#if !defined(RVL_IRD)
    fprintf(stderr, "usage: %s\n", progName);
    fprintf(stderr,
        " -I, --IN <file>       - input TMD file name\n" 
        " -O, --OUT             - generate new TMD\n" 
        " -S, --sub             - generate new subscription key or TMD\n"
        "                         using a subscription key\n"
        " -K, --KEY <file>      - input encrypted titleKey file name\n" 
        " -T, --titleId <tid>   - title ID\n" 
        "                         also used as filename for TMD and titleKey\n" 
        "                         <tid>.tmd and <tid>.titleKey\n"
        " -C, --titleType <type>- title type, default 0\n"
        "                         0: ES_TITLE_TYPE_NC_TITLE\n" 
        "                         1: ES_TITLE_TYPE_NG_TITLE\n" 
        " -n, --contentFileNames <file1,file2,...>\n"
        "                       - comma delimited content file names\n" 
        " -c, --cids <cid1,cid2...>\n"
        "                       - comma delimited CIDs\n" 
        " -i, --index <cidx1,cidx2,...>\n"
        "                       - comma delimited content index\n" 
        " -t, --types <type1,type2,...>\n"
        "                       - comma delimited content types, default 0\n" 
        "                       - 0: ES_CONTENT_TYPE_NC_EXE\n"
        "                       - 1: ES_CONTENT_TYPE_NG_EXE\n"
        "                       - (1<<15): ES_CONTENT_TYPE_SHARED\n"
        "                       - (1<<14): ES_CONTENT_TYPE_DISC\n"
        " -b, --bootIndex <bidx>- boot content index, default 0\n" 
        " -v, --crlVersions <caCrlVersion,signerCrlVersion> \n" 
        "                       - comma delimited CRL versions for CA and CP\n" 
        "                       - defaults to 0\n"
        " -o, --sysVersion <os> - sysVersion, defaults to 0\n" 
        " -m, --titleVersion <titleVersion>\n"
        "                       - title version, defaults to 0\n" 
        " -g  --groupId <groupId>\n"
        " -r, --rights <rights> - title rights bits, default 0\n" 
        " -N, --reserved <datafile> - 32 byte Nintendo custom data, default 0\n" 
        " -B, --reserved2 <datafile> - 30 byte BroadOn custom data, default 0\n" 
        " -P, --PKI <t|b|d|p|c> - PKI type, defaults to 't'\n" 
        "                         't': test PKI\n"
        "                         'b': beta PKI\n"
        "                         'd': development PKI\n"
        "                         'p': production PKI\n"
        "                         'c': user provide k,S,D options below\n" 
        " -k, --commonKey <file>- common key file used to encrypt titleKey\n" 
        " -s, --cpCert <file>   - CP server cert\n" 
        " -D, --cpData <file>   - CP server RSA data file, used for signing\n" 
        " -d, --disk            - Do Revolution disk encryption\n" 
        " -p, --print           - verify TMD and dump fields of TMD\n"
        " -a, --cmdOut          - output all CMDs in files named <cid>.cmd\n"
        " -A, --cmdIn <cmd1,cmd2,...>\n"
        "                       - comma delimited input CMD files\n"
        " -V, --size            - print out sizes of various data structures.\n"
        " -h, --help            - print this message.\n"
        "Example: To create a simple TMD using test PKI: \n"
        "tmd -O -C <title type>\n"
        "       -T <title ID> \n"
        "       -n <comma delimited content files>\n"
        "       -c <comma delimited content IDs>\n"
        "       -i <comma delimited content index>\n"
        "       -t <comma delimited content type>\n"
        "       -b <boot content index>\n");
#endif
    exit(1);
} 

static void 
processOptions(int argc, char* argv[])
{
    char* ptr;
    int err=0, i=0, j=0, gotContents=0, gotCids=0, gotIndex=0;
    int gotCommonKey=0, gotCert=0, gotRsa=0;
#if defined(RVL_IRD)
    u32 channel=0;
#endif

    if (argc==1) 
        usage(argv[0]);

    while (1) {
#if defined(__CYGWIN__) || defined(RVL_IRD)
        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 'O':
                __create=1;
                break;
            case 'K':
                __titleKeyFile = optarg;
                break;
            case 'T':
                __tid = strtoull(optarg, 0, 0);
#if defined(RVL_IRD)
                channel = (__tid&ES_CHANNEL_MASK)>>32;
                if (channel == ES_SYS_CHANNEL_RVL || 
                    channel == ES_SYS_CHANNEL_NC || 
                    channel == ES_SYS_CHANNEL_BB) {
                    fprintf(stderr, "incorrect title id\n"); 
                    usage(argv[0]); 
                }
#endif
                break;
            case 'n':
                __contentFiles[0] = strtok(optarg, ",");
                i=1;
                while ((__contentFiles[i]=strtok(NULL, ","))!=NULL) {
                    i++;
                }
                if (__numContents<=0) 
                    __numContents = i;
                else if (__numContents!=i) {
                    fprintf(stderr, "incorrect number of contents, numContents=%d n=%d\n", __numContents, i);
                    usage(argv[0]);
                }
                gotContents = 1;
                break;
            case 'c':
                ptr = strtok(optarg, ",");
                if(ptr!=NULL) {
                    __cids[0] = strtoul(ptr, 0, 0);
                    i=1;
                }
                while ((ptr=strtok(NULL, ","))!=NULL) {
                    __cids[i] = strtoul(ptr, 0, 0);
                    i++;
                }
                if (__numContents==0) 
                    __numContents = i;
                else if (__numContents!=i) {
                    fprintf(stderr, "incorrect number of contents, numContents=%d n=%d\n", __numContents, i);
                    usage(argv[0]);
                }
                gotCids = 1;
                break;
            case 'i':
                ptr = strtok(optarg, ",");
                if(ptr!=NULL) {
                    __index[0] = strtoul(ptr, 0, 0);
                    i=1;
                }
                while ((ptr=strtok(NULL, ","))!=NULL) {
                    __index[i] = strtoul(ptr, 0, 0);
                    i++;
                }
                if (__numContents==0) 
                    __numContents = i;
                else if (__numContents!=i) {
                    fprintf(stderr, "incorrect number of contents, numContents=%d n=%d\n", __numContents, i);
                    usage(argv[0]);
                }
                gotIndex = 1;
                break;
            case 't':
                ptr = strtok(optarg, ",");
                if(ptr!=NULL) {
                    __types[0] = strtoul(ptr, 0, 0);
                    i=1;
                }
                while ((ptr=strtok(NULL, ","))!=NULL) {
                    __types[i] = strtoul(ptr, 0, 0);
                    i++;
                }
                if (__numContents==0) 
                    __numContents = i;
                else if (__numContents!=i) {
                    fprintf(stderr, "incorrect number of contents, numContents=%d i=%d\n", __numContents, i);
                    usage(argv[0]);
                }
#if defined(RVL_IRD)
                for (i=0; i<__numContents; i++) {
                    if (    __types[i] != 0
                         && __types[i] != ES_CONTENT_TYPE_NG_EXE
                         && __types[i] != (ES_CONTENT_TYPE_NG_EXE | ES_CONTENT_TYPE_OPTIONAL) 
                         && __types[i] != (ES_CONTENT_TYPE_NG_EXE | ES_CONTENT_TYPE_SHARED)
                         && __types[i] != (ES_CONTENT_TYPE_NG_EXE | ES_CONTENT_TYPE_SHARED | ES_CONTENT_TYPE_OPTIONAL)
                         && __types[i] != (ES_CONTENT_TYPE_NG_EXE | ES_CONTENT_TYPE_DISC | ES_CONTENT_TYPE_OPTIONAL)
                         && __types[i] != (ES_CONTENT_TYPE_NG_EXE | ES_CONTENT_TYPE_DISC)) {
                        fprintf(stderr, "incorrect content type\n"); 
                        usage(argv[0]);
                    }
                }
#endif
                break;
            case 'o':
                __sysVersion = strtoull(optarg, 0, 0);
#if defined(RVL_IRD)
                if ((__sysVersion&ES_CHANNEL_MASK)>>32 != ES_SYS_CHANNEL_RVL) {
                    fprintf(stderr, "incorrect system version\n");
                    usage(argv[0]);
                }
#endif
                break;
            case 'm':
                __titleVersion = strtoul(optarg, 0, 0);
                break;
            case 'g':
                __groupId = strtoul(optarg, 0, 0);
#if defined(RVL_IRD)
                if (__groupId==0 || __groupId==ES_DEFAULT_GID) {
                    fprintf(stderr, "incorrect group ID\n");
                    usage(argv[0]);
                }
#endif
                break;
            case 'd':
                __diskEncryption=1;
                break;
            case 'N':
                utilFread(optarg, __reserved1, ES_NIN_RESERVED_SIZE);
                break;
            case 'B':
                utilFread(optarg, __reserved2, ES_BO_RESERVED_SIZE);
                break;
            case 'b':
                __bidx = strtoul(optarg, 0, 0);
                break;
            case 'a':
                __cmdOut = 1;
                break;
            case 'A': 
                __cmdFiles[0] = strtok(optarg, ",");
                i=1;
                while ((__cmdFiles[i]=strtok(NULL, ","))!=NULL) {
                    i++;
                }
                __numInCmds = i;
                for (i=0; i<__numInCmds; i++)  
                    utilFread(__cmdFiles[i], (u8*)(&(__cmds[i])), sizeof(ESContentMeta));
                break;
            case 'C':
                __ttype = strtoul(optarg, 0, 0);
#if defined(RVL_IRD)
                if (__ttype != ES_TITLE_TYPE_NG_TITLE &&
                    __ttype != (ES_TITLE_TYPE_NG_TITLE|ES_TITLE_TYPE_STREAM) && 
                    __ttype != (ES_TITLE_TYPE_NG_TITLE|ES_TITLE_TYPE_DATA) &&
                    __ttype != (ES_TITLE_TYPE_NG_TITLE|
                                ES_TITLE_TYPE_CACHE_DATA) && 
                    __ttype != (ES_TITLE_TYPE_NG_TITLE|ES_TITLE_TYPE_DATA|
                                ES_TITLE_TYPE_CACHE_DATA)) { 
                    fprintf(stderr, "incorrect title type\n"); 
                    usage(argv[0]);
                }
#endif
                break;
#if !defined(RVL_IRD)
            case 'S':
                __sub=1;
                break;
            case 'I':
                __inTmdFile = optarg;
                break;
            case 'v':
                __caCrlVersion = strtoul(strtok(optarg, ","), 0, 0);
                __cpCrlVersion = strtoul(strtok(NULL, ","), 0, 0);
                break;
            case 'r':
                __rights = strtoul(optarg, 0, 0);
                break;
            case 'P':
                __pki = *optarg;
                if (__pki!='t' && __pki!='b' && __pki!='p' && __pki!='c'&& __pki!='d') {
                    fprintf(stderr, "incorrect PKI type, has to be t,b,d,p or c.\n");
                    usage(argv[0]);
                }
                break;
            case 'k':
                sprintf(__commonKeyFile, "%s", optarg);
                gotCommonKey=1;
                break;
            case 's':
                sprintf(__cpCertFile, "%s", optarg);
                gotCert=1;
                break;
            case 'D':
                sprintf(__cpRsaFile, "%s", optarg);
                gotRsa=1;
                break;
            case 'p':
                __dump=1;
                break;
            case 'V': 
                printf("size of max ESTitleMeta: %d bytes, %s ES_MAX_TMD_SIZE\n", sizeof(ESTitleMeta), sizeof(ESTitleMeta)==ES_MAX_TMD_SIZE ? "same as" : "different from" );
                printf("size of CSLOSSha1Hash: %d bytes, %s ES_HASH_SIZE\n", sizeof(CSLOSSha1Hash), sizeof(CSLOSSha1Hash)==ES_HASH_SIZE ? "same as": "different from" );
                printf("size of CSLOSAesKey: %d bytes, %s ES_AES_KEY_SIZE\n", sizeof(CSLOSAesKey), sizeof(CSLOSAesKey)==ES_AES_KEY_SIZE ? "same as": "different from");
                exit(0);
                break;
#endif
            default:
                usage(argv[0]);
                break;
        }
    }

    if (__inTmdFile==NULL && !__create) {
        fprintf(stderr, "provide input TMD file using -I or create a new one using -O\n");
        usage(argv[0]);
    }

    if (__create) {
        if (__tid==0) {
            fprintf(stderr, "title ID undefined.\n");
            usage(argv[0]);
        }
        sprintf(__outKeyFile, "%llx.titleKey", __tid);
        sprintf(__outTmdFile, "%llx.tmd", __tid);
        if (!__sub) {
            if (__numContents>0) {
                if (!gotContents) {
                    fprintf(stderr, "need content files\n");
                    usage(argv[0]);
                }
                if (!gotCids) {
                    fprintf(stderr, "need content IDs\n");
                    usage(argv[0]);
                }
                if (!gotIndex) {
                    fprintf(stderr, "need content index\n");
                    usage(argv[0]);
                }
            }
            if (__numInCmds<=0) {
                if (__numContents<=0) {
                    fprintf(stderr, "number of contents incorrect\n");
                    usage(argv[0]);
                }
                if (__bidx>=__numContents && __bidx!=ES_MAX_CONTENT-1) {
                    /* data titles have bidx=511 */
                    fprintf(stderr, "boot content index incorrect bidx=%d numContents=%d\n", __bidx, __numContents);
                    usage(argv[0]);
                }
                int zero=0;
                for (i=0; i<__numContents; i++) {
                    if (__index[i]==0) 
                        zero=1;
                    if (__index[i]>=__numContents) {
                        fprintf(stderr, "content index has to be zero based and less than the number of contents %d\n", __numContents);
                        usage(argv[0]);
                    }
                }
                if (!zero) {
                    fprintf(stderr, "content index has to be zero based and less than the number of contents %d\n", __numContents);
                    usage(argv[0]);
                }
            } 
            if (__numContents>0 && __numInCmds>0) {
                for (i=0; i<__numContents; i++) {
                    for (j=0; j<__numInCmds; j++) {
                        if (__index[i] == ntohs(__cmds[j].index)) {
                            fprintf(stderr, "conflicting content index '%hu'\n",
                                    __index[i]);
                            err = 1;
                            break;
                        }
                        else if (__cids[i] == ntohl(__cmds[j].cid)) {
                            fprintf(stderr, "conflicting content id '%u'\n",
                                    __cids[i]);
                            err = 1;
                            break;
                        }
                    }
                }
                if (err) {
                    usage(argv[0]);
                }
            }
        }
    }

    if (__pki==0) {
        __pki = 'b';
    }
    if (__pki!='c') {
        ptr = getenv(RVL_ROOT);
        if (ptr==NULL) {
            ptr = getenv(DEV_ROOT);
            sprintf(__commonKeyFile, "%s%scommon_%cpki.aesKey", ptr, PKI_PATH_1, __pki);
            sprintf(__cpCertFile, "%s%scp_%cpki.cert", ptr, PKI_PATH_1, __pki);
            sprintf(__cpRsaFile, "%s%scp_%cpki.rsa", ptr, PKI_PATH_1, __pki);
        } else {
            sprintf(__commonKeyFile, "%s%scommon_%cpki.aesKey", ptr, PKI_PATH_2, __pki);
            sprintf(__cpCertFile, "%s%scp_%cpki.cert", ptr, PKI_PATH_2, __pki);
            sprintf(__cpRsaFile, "%s%scp_%cpki.rsa", ptr, PKI_PATH_2, __pki);
        }
    } else {
        if (!gotCommonKey) {
            fprintf(stderr, "need common key\n");
            usage(argv[0]);
        }
        if (!gotCert) {
            fprintf(stderr, "need content publishing server cert\n");
            usage(argv[0]);
        }
        if (!gotRsa) {
            fprintf(stderr, "need content publishing server RSA data file\n");
            usage(argv[0]);
        }
    }
}

#define ES_DEV_PWD   "rvlwii"
#define ES_TKEY_LEN  (16+strlen(ES_DEV_PWD)) 

static void 
encryptContents()
{
    int i;
    CSLOSAesKey commonKey;
    CSLOSAesKey outKey;
    CSLOSAesKey titleKey;
    CSLOSAesKey iv;
    ESTitleId titleId;
    u8 d[ES_TKEY_LEN+1];

    /* get common key */
    utilFread(__commonKeyFile, commonKey, sizeof(CSLOSAesKey));

    /* get or generate tilteKey */
    if (__titleKeyFile==NULL) {
        snprintf(d, ES_TKEY_LEN+1, "%016llx%s", __tid, ES_DEV_PWD); 
        MD5(d, ES_TKEY_LEN, titleKey);
    } else {
        /*
         * Note: There is NextGen/RVL code which depends on
         * the following code used to decrypt the title key file.
         * If the code is changed, PLEASE send e-mail to 'craig'
         * telling him that this code has changed.
         */
        if (__sub) 
            titleId = htonll(__tid&0xffffffff00000000ULL);
        else
            titleId = htonll(__tid);
        utilFread(__titleKeyFile, outKey, sizeof(CSLOSAesKey));
        memset(iv, 0, sizeof(CSLOSAesIv));
        memcpy(iv, (u8*)(&titleId), sizeof(ESTitleId));
        aes_SwDecrypt(commonKey, iv, outKey, sizeof(CSLOSAesKey), titleKey);
    }

    /* encrypt contents */
    for (i=0; i<__numInCmds; i++) {
        memcpy((u8*)(__hash)+(ntohs(__cmds[i].index))*sizeof(CSLOSSha1Hash), (u8*)(__cmds[i].hash), sizeof(CSLOSSha1Hash));
    }
    for (i=0; i<__numContents; i++) {
        if (__diskEncryption == 0) {
            if ( ES_EncryptContent(__contentFiles[i], __cids[i], __index[i], titleKey, (u8*)(__hash)+(__index[i])*sizeof(CSLOSSha1Hash))!=ES_ERR_OK) {
                fprintf(stderr, "%s encryption failed\n", __contentFiles[i]);
                exit(1);
            }
        }
        else {
            if (encryptDiskContent(__contentFiles[i],
                                   __cids[i],
                                   titleKey,
                                   (u8*) (__hash) + (__index[i]) * sizeof(CSLOSSha1Hash)) != ES_ERR_OK) {
                fprintf(stderr, "%s encryption failed\n", __contentFiles[i]);
                exit(1);
            }
        }
        if (__dump) printf("content file %s encrypted and written to %08x.app\n", __contentFiles[i], __cids[i]);
    }

    /* encrypt titleKey */
    if ((__sub && __numContents<=0) || (!__sub && __numContents>0)) {
        if (ES_CpEncryptTitleKey(commonKey, __tid, titleKey, outKey) !=ES_ERR_OK) {
            fprintf(stderr, "titleKey encryption failed\n");
            exit(1);
        }

        utilFwrite(__outKeyFile, outKey, sizeof(CSLOSAesKey));
        if (__dump) printf("title key written to file %llx.titleKey\n", __tid);
    }
}

static void 
generateTmd()
{
    int size, i;
    struct stat statBuf;
    IOSCRsa2048RsaCert cert;
    ESTmdView tmdView;
    char server[ES_NAME_SIZE];
    char issuer[ES_NAME_SIZE];
    int ccnt = 0;
    u16 idx=0;

    ccnt = __numContents + __numInCmds;

    size = ES_GetTmdSize(ccnt);

    /* fill ESTmdView struct */
    tmdView.head.version = ES_TMD_VERSION;
    tmdView.head.titleVersion = __titleVersion;
    tmdView.head.type = __ttype;
    tmdView.head.titleId = __tid;
    tmdView.head.groupId = __groupId;
    tmdView.head.numContents = ccnt;
    memcpy(tmdView.head.reserved, __reserved1, ES_NIN_RESERVED_SIZE);
    memcpy((tmdView.head.reserved)+ES_NIN_RESERVED_SIZE, __reserved2, ES_BO_RESERVED_SIZE);
    for (i=0; i<__numContents; i++) {
        tmdView.contents[__index[i]].cid = __cids[i];
        tmdView.contents[__index[i]].index = __index[i];
        tmdView.contents[__index[i]].type = __types[i];
        stat(__contentFiles[i], &statBuf);
        tmdView.contents[__index[i]].size = statBuf.st_size;
    }
    for (i=0; i<__numInCmds; i++) {
        idx = ntohs(__cmds[i].index);
        tmdView.contents[idx].cid = ntohl(__cmds[i].cid);
        tmdView.contents[idx].index = idx;
        tmdView.contents[idx].type = ntohs(__cmds[i].type);
        tmdView.contents[idx].size = ntohll(__cmds[i].size);
    }
    
    /* sanity check */
    for (i=0; i<ccnt; i++) {
        if (tmdView.contents[i].index != i) {
            fprintf(stderr, "incorrect content index %d\n", i);
            exit(1);
        }
    }
    /* generate unsigned TMD */
    utilFread(__cpCertFile, (u8*)(&cert), sizeof(IOSCRsa2048RsaCert));
    if( ES_GetCertNames(&cert, issuer, server) != ES_ERR_OK) {
        fprintf(stderr, "get cert name failed\n");
        exit(1);
    }
    ES_GenerateUnsignedTmd(&tmdView, __caCrlVersion, __cpCrlVersion, __sysVersion, __rights, __bidx, (u8*)__hash, server, issuer, &__tmd);
    if (__dump) printf("TMD issuer:%s\n", __tmd.sig.issuer);

    /* sign */
    if (utilFillSig(__cpRsaFile, sizeof(CSLOSRsaSig2048), (u8*)&__tmd, size)!=ES_ERR_OK) {
        fprintf(stderr, "signing TMD failed\n");
        exit(1);
    };

    /* write TMD file */
    utilFwrite(__outTmdFile, ((u8*)(&__tmd)), size);
    if (__dump) printf("TMD written to file %llx.tmd\n", __tid);
}

static int 
dumpTmd(char* args)
{
    struct stat statBuf;
    int i, j;
    char *file=NULL;
    int status = 0;
    char cfile[]="00000000.cmd";
    int tmdSize;

    /* get TMD */
    if (__create) {
        stat(__outTmdFile, &statBuf);
        file = __outTmdFile;
    } else if (__inTmdFile) {
        stat(__inTmdFile, &statBuf);
        file = __inTmdFile;
    } else {
        fprintf(stderr, "specify input TMD file using -I or create new TMD file using -O\n");
        usage(args);
    }
    utilFread(file, (u8*)&__tmd, statBuf.st_size);

    /* print out TMD fields */
    printf("TMD fields:\n");
    printf("  sigType: %lx\n", (unsigned long)ntohl(__tmd.sig.sigType)); 
    printf("  issuer: %s\n", __tmd.sig.issuer); 
    printf("  version: %d\n", __tmd.head.version); 
    printf("  sysVersion: 0x%llx\n", (long long)(ntohll(__tmd.head.sysVersion))); 
    printf("  caCrlVersion: %d\n", __tmd.head.caCrlVersion); 
    printf("  signerCrlVersion: %d\n", __tmd.head.signerCrlVersion); 
    printf("  titleType: 0x%08lx\n", (unsigned long)ntohl(__tmd.head.type)); 
    printf("  titleId: 0x%llx\n", (long long)(ntohll(__tmd.head.titleId))); 
    printf("   reserved: ");
    for (i=0; i<sizeof(ESTmdReserved); i++) 
        printf("0x%02x ", __tmd.head.reserved[i]); 
    printf("\n");
    printf("  groupId: 0x%04x\n", ntohs(__tmd.head.groupId));
    printf("  accessRights: 0x%08lx\n", (unsigned long)ntohl(__tmd.head.accessRights)); 
    printf("  titleVersion: %d\n", ntohs(__tmd.head.titleVersion)); 
    printf("  numContents: %d\n", ntohs(__tmd.head.numContents)); 
    printf("  bootIndex: %d\n", ntohs(__tmd.head.bootIndex)); 
    for(i=0; i<ntohs(__tmd.head.numContents);i++) {
        printf("  --cid %d: 0x%08lx\n", i, (unsigned long)ntohl(__tmd.contents[i].cid));
        printf("    index %d: %d\n", i, ntohs(__tmd.contents[i].index));
        printf("    type %d: 0x%x ", i, ntohs(__tmd.contents[i].type));
        if ((ntohs(__tmd.contents[i].type) & ES_CONTENT_TYPE_SHARED)
            == ES_CONTENT_TYPE_SHARED) {
            printf("shared ");
        } 
        if ((ntohs(__tmd.contents[i].type) & ES_CONTENT_TYPE_DISC)
            == ES_CONTENT_TYPE_DISC) {
            printf("disc ");
        }
        printf("\n");
        printf("    size %d: %llu\n", i, ntohll(__tmd.contents[i].size));
        printf("    hash %d: ", i);
        for (j=0; j<sizeof(CSLOSSha1Hash); j++) {
            printf("0x%02x ", __tmd.contents[i].hash[j]);
        }
        printf("\n");
    }

    if (__tmd.head.version!=ES_TMD_VERSION) 
    {
        printf("TMD has incorrect version: %d\n", __tmd.head.version);
        return(2); 
    } 

    if (__cmdOut) {
        for (i=0; i<ntohs(__tmd.head.numContents); i++) {
            sprintf(cfile, "%lx.cmd", (unsigned long)ntohl(__tmd.contents[i].cid)); 
            utilFwrite(cfile, (u8*)(&(__tmd.contents[i])), sizeof(ESContentMeta));
        }
    }

    /* verify */

    tmdSize = sizeof(IOSCSigRsa2048) + sizeof(ESTitleMetaHeader) + 
              ntohs(__tmd.head.numContents) * sizeof(ESContentMeta);
    if (utilVerify(__cpCertFile, sizeof(CSLOSRsaSig2048), (u8*)&__tmd, tmdSize)!=ES_ERR_OK) {
        printf("TMD verify failed\n");
        status = 2;
    } else {
        printf("TMD verify successful\n");
        status = 0;
    }
    return(status);
}

int
main(int argc, char* argv[])
{
    processOptions(argc, argv);
    int exitStatus = 0;

    if (__create) {
        encryptContents();
        generateTmd();
    }

    if (__dump || __cmdOut) {
        exitStatus = dumpTmd(argv[0]);
    }

    exit(exitStatus);
}
