/*
 *               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 <netinet/in.h>

#include "csl.h"
#include "es_int.h"
#include "aes.h"
#include "esl.h"
#include "es_utils.h"

/* 
 * Generate ECC public/private key pair from input random number.
 *
 * Input:
 * randN  - 30byte random number
 *
 * Output:
 * pvtKey - 30byte ECC private key (caller allocates)
 * pubKey - 60byte ECC public key (caller allocates)
 *
 */
int
ES_GenerateEccKeyPair(u8* randN, u8* pvtKey, u8* pubKey)
{

    if ( (CSL_GenerateEccKeyPair(randN, pvtKey, pubKey)) != CSL_OK) 
        return ES_ERR_GENKEY_FAILED;
    else
        return ES_ERR_OK;
}

/*
 * Generate unsigned non-personalized eTicket for a given title 
 * and a given device. 
 *
 * Input: 
 * tktView             - ESTicketView for the eTicket
 * caCrlVersion        - CA CRL version
 * signerCrlVersion    - server (XS, CP, MS) CRL version
 * reserved            - Nintendo custom data
 * encryptedTitleKey   - common key encrypted titkeKey from CP server
 * serverPubKey        - ticketing server's ECC public key
 * signerCertName      - ticketing server's cert name
 * signerCertIssuerName- ticketing server cert issuer's name
 *
 * Output:
 * ticket              - unsigned, non-personalized eTicket (caller allocates)
 *
 * If serverPubKey is NULL, the eTicket generated is not intended to be  
 * personalized. 
 *
 */
int
ES_GenerateUnsignedCommonTicket(const ESTicketView* tktView, ESVersion caCrlVersion, ESVersion signerCrlVersion, const u8* encryptedTitleKey, const u8* serverPubKey, const char* signerCertName, const char* signerCertIssuerName, void* ticket)
{
    int rv = ES_ERR_OK;
    ESTicket* ptr = (ESTicket*)ticket;
    int i;

    memset(ptr, 0, sizeof(ESTicket));

    /* fill eTicket body */
    ptr->version = ES_TICKET_VERSION; 
    ptr->caCrlVersion = caCrlVersion; 
    ptr->signerCrlVersion = signerCrlVersion; 
    if (serverPubKey!=NULL) 
        memcpy((ptr->serverPubKey), serverPubKey, sizeof(IOSCEccPublicKey));
    ptr->ticketId = htonll(tktView->ticketId);
    ptr->deviceId = htonl(tktView->deviceId);
    memcpy(ptr->sysAccessMask, tktView->sysAccessMask, sizeof(ESSysAccessMask));
    ptr->ticketVersion = htons(tktView->ticketVersion);
    ptr->accessTitleId = htonl(tktView->accessTitleId);
    ptr->accessTitleMask = htonl(tktView->accessTitleMask);
    ptr->licenseType = tktView->licenseType;
    ptr->keyId = tktView->pad;  /* This is actually the keyId */
    ptr->audit = tktView->audit;
    memcpy(ptr->reserved, tktView->reserved, sizeof(ESTicketReserved));
    ptr->titleId = htonll(tktView->titleId);
    memcpy((u8*)(ptr->cidxMask), (u8*)(tktView->cidxMask), sizeof(ESCidxMask));
    for (i=0; i<ES_MAX_LIMIT_TYPE; i++) {
        (ptr->limits[i]).code = htonl((tktView->limits[i]).code);
        (ptr->limits[i]).limit = htonl((tktView->limits[i]).limit);
        eslLog("%d",  htonl((tktView->limits[i]).code));
    }
    /* copy commonly encrypted titleKey into eTicket */
    memcpy(ptr->titleKey, encryptedTitleKey, sizeof(IOSCAesKey));

    /* fill sig struct, leave signature blank */
    ptr->sig.sigType = htonl(IOSC_SIG_RSA2048);
    sprintf(ptr->sig.issuer, "%s-%s", signerCertIssuerName, signerCertName);

    return rv;
}

/* 
 * Re-encrypts the titleKey in a signed eTicket, using the computed shared
 * key from the server and the device. 
 *
 * Input: 
 * ticket       - signed eTicket
 * serverPvtKey - ticketing server's ECC private Key
 * devicePubKey - device's ECC private Key
 *
 * Output: 
 * the titleKey in "ticket" is overwritten by the re-encrypted value. 
 *
 */
int 
ES_PersonalizeSignedTicket(void* ticket, const u8* serverPvtKey, const u8* devicePubKey)
{
    int rv = ES_ERR_OK;
    ESTicket* ptr = (ESTicket*)ticket;
    CSLOSEccSharedKey sharedKey; 
    IOSCAesKey outKey;
    IOSCAesIv iv;
    ESTicketId tid;

    if (serverPvtKey!=NULL && devicePubKey!=NULL) {

        if ( (CSL_GenerateEccSharedKey((u8*)serverPvtKey, (u8*)devicePubKey, sharedKey, sizeof(IOSCAesKey)))!=CSL_OK ) {
            rv = ES_ERR_GENKEY_FAILED; 
            goto out;
        }

        tid = ptr->ticketId;
        memset(iv, 0, sizeof(IOSCAesIv));
        memcpy(iv, (u8*)(&tid), sizeof(ESTicketId));
        if ( (aes_SwEncrypt((u8*)sharedKey, iv, 
                            ptr->titleKey, sizeof(IOSCAesKey), outKey)) < 0) {
            rv = ES_ERR_ENCRYPTION_FAILED;
            goto out;
        }

        memcpy(ptr->titleKey, outKey, sizeof(IOSCAesKey));
    }

out:
    return rv;
}

/*
 * Returns the default cidx mask
 *
 * Output:
 * mask - cidx mask (64 bytes) with first 32 bytes 0xff, 
 *        and the next 32 bytes 0. 
 *        It covers the first 256 pieces of content.
 */
void 
ES_GetDefaultCidxMask(ESCidxMask mask)
{
    memset(mask, 0xff, sizeof(ESCidxMask)/2);
    memset(mask+sizeof(ESCidxMask)/2, 0, sizeof(ESCidxMask)/2);
}

/* 
 * Returns the cidx mask OR'ed with the input content index
 *
 * Input: 
 * cidxList - list of content indices
 * numIdx   - number of content indices
 * 
 * Output: 
 * mask - cidx mask (64 bytes, caller allocates) 
 */
void 
ES_MakeCidxMask(ESCidxMask mask, u16* cidxList, int numIdx)
{
    int i;
    u32 bi, oi;

    memset(mask, 0, sizeof(ESCidxMask));
    for (i=0; i<numIdx; i++) {
        bi = cidxList[i]/8;
        oi = cidxList[i]%8;
        mask[bi] = (mask[bi]) | (1 << oi);
    }
}

/* 
 * Returns the sysAccessMask OR'ed with the input content index
 * only content index 0-15 can be the input
 *
 * Input: 
 * cidxList - list of content indices
 * numIdx   - number of content indices
 * 
 * Output: 
 * mask - sysAccessMask (2 bytes, caller allocates) 
 */
int 
ES_MakeSysAccessMask(ESSysAccessMask mask, u16* cidxList, int numIdx)
{
    int i;
    u32 bi, oi;

    memset(mask, 0, sizeof(ESSysAccessMask));
    for (i=0; i<numIdx; i++) {
        if (cidxList[i]>15) 
            return ES_ERR_INVALID;
        bi = cidxList[i]/8;
        oi = cidxList[i]%8;
        mask[bi] = (mask[bi]) | (1 << oi);
    }
    return ES_ERR_OK;
}

/*
 * Set the unaligned bits in mask.  Return the number of bits set.
 */
static inline int
setOddBits(ESCidxMask mask, u16 idx, int numIdx)
{
    int n = numIdx;
    while (n > 0 && idx % 8 != 0) {
	mask[idx / 8] |= (1 << (idx % 8));
	++idx;
	--n;
    }
    return numIdx - n;
}

/* 
 * Returns the cidx mask with bits (startIdx -> startIdx+numIdx-1)
 * OR'ed together 
 *
 * Input: 
 * startIdx - starting content index 
 * numIdx   - number of content indexes 
 * 
 * Output: 
 * mask - cidx mask (64 bytes, caller allocates) 
 */
void 
ES_SetMaskBits(ESCidxMask mask, u16 startIdx, int numIdx)
{
    // wind up
    int n = setOddBits(mask, startIdx, numIdx);
    startIdx += n;
    numIdx -= n;

    // assert that (startIdx % 8) == 0
    
    // main loop, set one byte at a time
    while (numIdx >= 8) {
	mask[startIdx / 8] = 0xff;
	startIdx += 8;
	numIdx -= 8;
    }

    // wind down
    while (numIdx > 0) {
	mask[startIdx / 8] |= (1 << startIdx % 8);
	++startIdx;
	--numIdx;
    }
}
