/*
 *              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 <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>

#define MAX_PKT_SIZE      16384
#define MAX_CMD_SIZE      2048
#define USB_MAX_PKT_SIZE  64
static unsigned char usbRdBuf[MAX_PKT_SIZE + 16];
static unsigned char usbWrBuf[MAX_PKT_SIZE + 16];

int
shellInit(char *server, int port)
{
    struct sockaddr_in addr;
    int fd, addrLen=sizeof(addr);

#ifdef WIN32
    WSADATA            wsd;
	int rv;

    if ((rv = WSAStartup(MAKEWORD(2,2), &wsd)) != 0) {
        printf("WSAStartup() failed: %d\n", rv);
        return -1;
    }
#endif

    fd = (int) socket(AF_INET, SOCK_STREAM, 0); 
    if (fd <= 0) {
        printf("ERROR: Cannot open AF_INET socket\n");
        return -1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(server);
    addr.sin_port = htons(port);

    if (connect(fd, (struct sockaddr *)&addr, addrLen) < 0) {
        close(fd);
        printf("Cannot connect to NC proxy program\n");
        return -2;
    }

    return fd;
}

int
shellClose(int fd)
{
    close(fd);
	return 0;
}

int
hostSend(int fd, void *p, int len)
{
    int wr=0, nwrite, n;
    
    n = len + 4;
    usbWrBuf[0] = 0x41;
    usbWrBuf[1] = 0x67;
    usbWrBuf[2] = (len >> 8) & 0xff;
    usbWrBuf[3] = len & 0xff;
    memcpy(usbWrBuf+4, p, len);

    while(wr < n) {
        nwrite = send(fd, usbWrBuf+wr, n-wr, 0);
        if (nwrite < 0)  {
            printf("ERROR: socket send failed errno=%d\n", errno);
            return -1;
        }
        wr += nwrite;
    } 

    return 0;
}

int 
hostRecv(int fd, void *p, int len)
{
    int rd=0, nread, n;
    
    n =  len + 4;
    while(rd < n) {
        nread = recv(fd, usbRdBuf+rd, n-rd, 0);
        if (nread < 0) {
            if (errno == EINTR) nread = 0;
            else {
                printf("ERROR: socket recv failed errno=%d\n", errno);
                return -1;
            }
        }
        rd += nread;
        if (rd >= 4) n = ((usbRdBuf[2] << 8) | usbRdBuf[3]) + 4;
    }
    
    memcpy(p, usbRdBuf+4, n-4);

    return n-4;
}

