/*---------------------------------------------------------------------------*
Project: NitroDWC - demos - nhttp
File: main.c

Copyright 2006 Nintendo.  All rights reserved.

These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., 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 Nintendo.

$Log: main.c,v $
Revision 1.12  2008/02/15 20:47:55  achan
- removed NSSL_Init from the NHTTP library and put it into the applications inst
ead (normal Nintendo convention)
- set verifyOption when calling NSSL_NewClient, applications should call NHTTPSe
tVerifyOption

Revision 1.11  2007/12/18 23:10:07  achan
- combine the TWL and DS versions of nhttp_test.c

Revision 1.10  2007/10/19 02:04:08  achan
NHTTP test now works on TWL
- splitted NHTTP test into platform-dependent and independent components
- ported TWL version of NHTTP test
- moved ssl.h to a more appropriate location

Revision 1.9  2007/10/17 00:05:06  achan
Disabled old NHTTP, NUP, and EC for NetCard.  Imported new NHTTP based on the Wii version:
- common/Makefile: added tests subdir
- common/lib/Makefile: removed nup for now
- common/lib/nhttp: added new version of NHTTP
- common/tests/Makefile: removed nup for now
- common/tests/ec: modified EC tests to suit the new EC APIs
- ds/lib/Makefile: removed nup for now, added NHTTP
- ds/lib/nhttp: new version of NHTTP
- ds/lib/p2p/Makefile: added shared subdir
- ds/test/Makefile: removed nup for now
- ds/test/ec/Makefile.nitro: added NON_SHIM for now
- ds/test/nhttp: new version of NHTTP
- gba/lib, gba/tests, sc/lib's Makefiles - removed nup, ec
- tools: removed nup, added shared, nhttp

Revision 1.8  2007/06/08 23:37:55  achan
- This check-in moved the NUP functionality to the NetCard side
- By default, only the NUP shim layer is exported to the NitroDWC SDK now
- The EC functionality on DS is temporarily broken (because of some API changes to add "mode" as an argument)
- scanf: return 1 instead of 0
- NHTTP: changed SetMode to become request-specific
- NUP: added "mode", also changed status string to be a char array instead of a pointer so that the buffer resides in the caller side
- devroot, elf-merge, addr_map: added address space for EC resource manager
- ds-sdk, sdk, Makefiles: modified the list of files to be exported, added/removed build steps

Revision 1.7  2007/05/25 18:52:43  achan
- Ported nup to SC, it compiles but not tested
- added sscanf
- changed _SHR_thread_join to take in a pointer to the thread structure, since the Nitro SDK requires passing in the original pointer
- ohter minor fixes

Revision 1.6  2007/05/11 23:54:52  achan
- nhttp, nup: change to use port 16990 instead of 16992 for NUS
- sktp: changed comment

Revision 1.5  2007/05/09 00:37:48  achan
- added code to run tests in USB mode

Revision 1.4  2007/01/30 19:34:18  achan
- Changed NUP to use https instead of http (only applicable to WiFi, since VNG uses the host name specified in EC Proxy instead
- Changed the CA info in NHTTP and NUP tests to match lab1
- Changed NHTTP test to use the correct https port number for lab1
- Changed the NUP test to use NHTTP by default (instead of VNG)
- Added more EC tests (some of them not working yet)

Revision 1.3  2006/12/13 22:45:31  achan
- Removed extra carriage return at the end of the line

Revision 1.2  2006/12/12 03:34:56  achan
- Added SSL usage
- Responded to '!' by calling CleanupAsync and exiting

Revision 1.1  2006/12/02 00:10:51  achan
- Simple HTTP client that uses NHTTP to do GET from specified URL
- If "?" is specified instead of an URL, the client will do a POST to nus.lab3 instead
- The result is simply printed out on the debug console

Revision 1.6  03/10/2006 09:22:43  kitase_hirotake
  INDENT SOURCE

Revision 1.5  01/16/2006 01:40:58  kitase_hirotake
Edited sitedefs for publication

Revision 1.4  01/12/2006 00:10:21  kitase_hirotake
2005->2006 Edited

Revision 1.3  01/10/2006 04:18:39  kitase_hirotake
Changed features to samples

Revision 1.2  01/06/2006 00:44:47  kitase_hirotake
Version compatible with PAD input
  
Revision 1.1  12/22/2005 04:34:06  adachi_hiroaki
replaced HTTP client demo with SOC version

$NoKeywords$
 *---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*
This is a sample program that runs as an http client.
It connects to the server by entering the URL with the PAD.

How to enter characters with the PAD:
1. Enter text using the PAD.
Switch between DIRECT_MODE and INDERECT_MODE by pressing the L button.
Text input is done in INDIRECT_MODE.
2. Change the characters being selected with the up and down keys.
Character types can be switched between numbers, upper-case, lower-case, and symbols with the R button.
Confirm the current character and move to the next character input with the A button.
You can highlight and change characters entered up to this point with the left and right keys.
3. Delete the selected character with the B button.
4. Send the string entered to this point with the X button.
    
 *---------------------------------------------------------------------------*/
#include <string.h>
#include <nitro.h>
#include <nnsys/fnd.h>
#include <nitroWiFi.h>
#include <sitedefs.h>
#include <nhttp.h>

#include "nhttp_test.h"
#include "padkeyboard.h"
#include "output.h"
#include "screen.h"
#include "netconnect.h"


//#define GET_SYSTEM_UPDATE_URL   "https://login.live.com"
//#define GET_SYSTEM_UPDATE_URL   "https://benefits.paychex.com"
//#define GET_SYSTEM_UPDATE_URL   "http://nus.lab3.routefree.com:16987/nus/services/NetUpdateSOAP"
//#define GET_SYSTEM_UPDATE_URL   "http://ecs.lab3.routefree.com:17105/ecs/services/ECommerceSOAP"
//#define GET_SYSTEM_UPDATE_URL   "https://nus.lab3.routefree.com:16988/nus/services/NetUpdateSOAP"
//#define GET_SYSTEM_UPDATE_URL   "http://nus.lab1.routefree.com:16987/nus/services/NetUpdateSOAP"
//#define GET_SYSTEM_UPDATE_URL   "http://ecs.lab1.routefree.com:17105/ecs/services/ECommerceSOAP"
#define GET_SYSTEM_UPDATE_URL   "https://nus.lab1.routefree.com:16990/nus/services/NetUpdateSOAP"

#define GET_SYSTEM_UPDATE_SOAP_BODY \
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" \
"  <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n"  \
"                    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" \
"                    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" \
"    <soapenv:Body>\n" \
"      <GetSystemUpdateRequest xmlns=\"urn:nus.wsapi.broadon.com\">\n" \
"        <Version>1.0</Version>\n" \
"        <MessageId>11542385950174174</MessageId>\n" \
"        <DeviceId>4294967797</DeviceId>\n" \
"        <RegionId>JPN</RegionId>\n" \
"        <CountryCode>JP</CountryCode>\n" \
"        <TitleVersion>\n" \
"          <TitleId>0000000200000001</TitleId>\n" \
"          <Version>0</Version>\n" \
"        </TitleVersion>\n" \
"        <TitleVersion>\n" \
"          <TitleId>0000000200000002</TitleId>\n" \
"          <Version>1</Version>\n" \
"        </TitleVersion>\n" \
"        <Attribute>0</Attribute>\n" \
"        <AuditData></AuditData>\n" \
"      </GetSystemUpdateRequest>\n" \
"    </soapenv:Body>\n" \
"  </soapenv:Envelope>\n"


#define NHTTP_DEBUG         printf
#define HEAP_SIZE           (1024 * 1024)
#define SITEDEFS_APCLASS    "WiFi.LAN.1.AP.1"
#define URL_LENGTH          256


static NNSFndAllocator alloc;
extern SOCCaInfo nhttpCaInfo;
static volatile u32 end = 0;


static void
nhttpCleanupCB(void)
{
    end = 1;
    NHTTP_DEBUG("nhttpCleanupCB\n");
}


static void *
nhttpAlloc(u32 size, int align)
{
    return NNS_FndAllocFromExpHeapEx(alloc.pHeap, size, align);
}

static void
nhttpFree(void *p)
{
    NNS_FndFreeToExpHeap(alloc.pHeap, p);
}


void
NitroMain()
{
    int rv = NHTTP_ERROR_NONE;
    char url[URL_LENGTH];
    void *heapStart;
    NNSFndHeapHandle heap = NULL;

    /* Calls the initialization function and the connect function. */
    NcGlobalInit();
    NcStart(SITEDEFS_APCLASS);

    /* Initializes the screen */
    InitScreen();
    FlushScreen();
    FlushDebugOutput();

    /* Initialize the allocator */
    heapStart = OS_Alloc(HEAP_SIZE);
    if (heapStart == NULL) {
        NHTTP_DEBUG("Failed to allocate memory\n");
    }

    heap = NNS_FndCreateExpHeap(heapStart, HEAP_SIZE);
    if (heap == NULL) {
        NHTTP_DEBUG("Failed to create exp heap\n");
    }
    NNS_FndInitAllocatorForExpHeap(&alloc, heap, 0);

    /*
     * Empty call for getting key input data (strategy for pressing
     * A button in IPL)
     */
    (void)PAD_Read();

    /* Initializes the keyboard. */
    InitKeyboardThread();
    KeyboardValid();

    /*
     * Connection to the HTTP server
     * Input the target URL with the Pad
     */
    DebugOutput("http_server_ip>");

    /* The initial URL value is the management screen for the router. */
    MI_CpuClear8(url, URL_LENGTH);
    {
        SOCInAddr addr;
        SOC_GetGateway(NULL, (u8*) &addr);
        (void)OS_SNPrintf(url, sizeof(url), "http://%s/", SOC_InetNtoA(addr));
    }

    /* Initialize NHTTP */
    rv = NHTTPStartup(nhttpAlloc, nhttpFree, 18);
    if (rv != NHTTP_ERROR_NONE) {
        NHTTP_DEBUG("Failed to start NHTTP, rv=%d\n", rv);
        OS_Panic("Panic!\n");
    }

    while (1) {
        PadKeySetString(url);

        /* Enter the URL. */
        PadKeyGetInputString(url, URL_LENGTH);

        {
            NHTTPReqMethod reqMethod;
            SOCCaInfo *caInfo;

            /* Compose the URL */
            if (url[0] == '!') {
                break;
            } else if (url[0] == '?') {
                reqMethod = NHTTP_REQMETHOD_POST;
                (void)OS_SNPrintf(url, sizeof(url), "%s", GET_SYSTEM_UPDATE_URL);
            } else {
                reqMethod = NHTTP_REQMETHOD_GET;
            }
            NHTTP_DEBUG("URL: %s\n", url);

            caInfo = &nhttpCaInfo;
            rv = nhttpOp(url, reqMethod, GET_SYSTEM_UPDATE_SOAP_BODY, (const char *) &caInfo, 1, NULL, 0, NULL, 0, 0, OS_Sleep, (NHTTPDebug) NHTTP_DEBUG);
            if (rv != NHTTP_ERROR_NONE) {
                NHTTP_DEBUG("Failed NHTTP operation to %s, method=%d\n", url, reqMethod);
                OS_Panic("Panic!\n");
            }
        }
    }

    /* De-initialize NHTTP */
    NHTTPCleanupAsync(nhttpCleanupCB);
    while (end == 0) { };
    NHTTP_DEBUG("Exit test client\n");

    NcFinish();
    OS_Terminate();
}
