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

/*---------------------------------------------------------------------------*
 * 
 * Socket Layer RM
 * 
 *---------------------------------------------------------------------------*/

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <priority.h>
#include <iosresource.h>

#include <socket.h>
#include <iop_sock.h>
#include <iop_netif.h>
#include "iop_resolver.h"
#include "dolphin/os.h"

// TODO: THIS SHOULD BE REMOVED
#include <private/eth.h>

/*---------------------------------------------------------------------------*
 * 
 * global variables
 * 
 *---------------------------------------------------------------------------*/

extern SOResolver __SOResolver;

const u8 _initStack[NET_SOCK_STACK_SIZE] ATTRIBUTE_ALIGN(4);
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = IOS_PRIORITY_NET;

static char __netSockStack[(SO_SOCKET_MAX-1) * NET_SOCK_STACK_SIZE] ATTRIBUTE_ALIGN(4);
static IOSMessageQueueId __qid;
static IOSMessage __msgQ[NET_SOCK_MSGQ_SIZE];

extern int   SOGetInterfaceOpt( IPInterface* interface, int level, int optname,
                         void* optval, int* optlen );
extern int   SOSetInterfaceOpt( IPInterface* interface, int level, int optname,
                         const void* optval, int optlen );

/*---------------------------------------------------------------------------*
 * 
 * Socket Layer Resource Manager
 * 
 *---------------------------------------------------------------------------*/
static IOSError
sockRmIoctl(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceIoctl *ioctl = (IOSResourceIoctl *) &req->args.ioctlv;
    
    switch (ioctl->cmd)
    {
        case NET_SO_ACCEPT:
        {
            int sock = * ((int *) ioctl->inPtr);
            void *sockAddr = ioctl->outPtr;

            rv = SOAccept(sock, sockAddr);
        }
            break;

        case NET_SO_BIND:
        {
            NETSoMap *netSoMap = (NETSoMap *) ioctl->inPtr;

            if (netSoMap->sockAddr != NULL) {
                netSoMap->sockAddr = (void *) &netSoMap->addrBuf;
            }
            rv = SOBind(netSoMap->sock, (const void *) netSoMap->sockAddr);
        }
            break;
            
        case NET_SO_CLOSE:
        {
            int socket = *( (int *) ioctl->inPtr);
            rv = SOClose(socket);
        }
            break;
            
        case NET_SO_CONNECT:
        {
            NETSoMap *netSoMap = (NETSoMap *) ioctl->inPtr;

            if (netSoMap->sockAddr != NULL) {
                netSoMap->sockAddr = (void *) &netSoMap->addrBuf;
            }
            rv = SOConnect(netSoMap->sock, (const void *) netSoMap->sockAddr);
        }

            break;

        case NET_SO_FCNTL:
        {
            NETSoFcntl *netSoFcntl = (NETSoFcntl *) ioctl->inPtr;

            rv = SOFcntl(netSoFcntl->sock, netSoFcntl->cmd, netSoFcntl->flag);
        }
            break;

        case NET_SO_GETPEERNAME:
        {
            int sock = * ((int *) ioctl->inPtr);
            void *sockAddr = ioctl->outPtr;

            rv = SOGetPeerName(sock, sockAddr);
        }
            break;

        case NET_SO_GETSOCKNAME:
        {
            int sock = * ((int *) ioctl->inPtr);
            void *sockAddr = ioctl->outPtr;

            rv = SOGetSockName(sock, sockAddr);
        }
            break;

        case NET_SO_GETSOCKOPT:
        {
            NETSoGetOpt *netSoGetOpt = (NETSoGetOpt *)ioctl->outPtr;

            int socket  = netSoGetOpt->sock;
            int level   = netSoGetOpt->level;
            int optname = netSoGetOpt->optname;
            void *optval= (void *) &netSoGetOpt->optval;
            int *optlen = (int *) &netSoGetOpt->optlen;
            *optlen = MAX_GET_OPTVAL_LEN;

            rv = SOGetSockOpt(socket, level, optname, optval, optlen);
        }
            break;

        case NET_SO_SETSOCKOPT:
        {
            NETSoSetOpt *netSoSetOpt = (NETSoSetOpt *) ioctl->inPtr;

            rv = SOSetSockOpt(netSoSetOpt->sock, netSoSetOpt->level, 
                netSoSetOpt->optname, (void *)&netSoSetOpt->optval, 
                netSoSetOpt->optlen);
        }
            break;

        case NET_SO_LISTEN:
        {
            NETSoListen *netSoListen = (NETSoListen *)ioctl->inPtr;

            rv = SOListen(netSoListen->sock, netSoListen->backlog);
        }
            break;

        case NET_SO_POLL:
        {
            SOPollFD *fds = (SOPollFD *) ioctl->outPtr;
            unsigned nfds = ioctl->outLen / (sizeof(SOPollFD));
            OSTime timeout = * ((OSTime *) ioctl->inPtr);

            rv = SOPoll(fds, nfds, timeout);
        }
            break;

        case NET_SO_SHUTDOWN:
        {
            NETSoShutdown *netSoShutdown = 
                (NETSoShutdown *) ioctl->inPtr;

            rv = SOShutdown(netSoShutdown->sock, netSoShutdown->how);
        }
            break;

        case NET_SO_SOCKET:
        {
            NETSoSocket *netSoSocket = (NETSoSocket *) ioctl->inPtr;
            
            rv = SOSocket(netSoSocket->af, netSoSocket->type, netSoSocket->protocol);
        }
            break;

        case NET_SO_GETHOSTID:
            rv = SOGetHostID();
            break;

        case NET_SO_GETHOSTBYNAME:
        {
            const char *name = (const char *) ioctl->inPtr;
            SOResolver *soResolver = (SOResolver *) ioctl->outPtr;
            SOHostEnt * env  = SOGetHostByName(name);
            
            if (env == NULL)
                rv = IOS_ERROR_INVALID;
            else {
               /* return certain fields of the global __SOResolver structure;
                * note that the structure contains self-referential pointers;
                * the pointers are fixed by the calling routine (since the 
                * caller's address space may be different from ours)
                */
                memcpy(&soResolver->ent,&__SOResolver.ent,sizeof(__SOResolver.ent));
                memcpy(soResolver->name,__SOResolver.name,sizeof(__SOResolver.name));
                memcpy(soResolver->addrList,__SOResolver.addrList,sizeof(__SOResolver.addrList));
                memcpy(soResolver->ptrList,__SOResolver.ptrList,sizeof(__SOResolver.ptrList));
            }
        }
            break;

        case NET_SO_GETHOSTBYADDR:
        {
            NETSoGetHostByAddr *netSoGetHostByAddr = 
                    (NETSoGetHostByAddr *) ioctl->inPtr;
            // netSoGetHostByAddr->addr should be changed to &netSoGetHostByAddr->addrBuf
            // it is left here since it will not be used
            const void *addr    = (void *) &netSoGetHostByAddr->addrBuf;
            int len             = netSoGetHostByAddr->len;
            int type            = netSoGetHostByAddr->type;
            SOResolver *soResolver = (SOResolver *) ioctl->outPtr;
            SOHostEnt * env  = SOGetHostByAddr(addr, len, type);
            
            if (env == NULL)
                rv = IOS_ERROR_INVALID;
            else {
               /* return certain fields of the global __SOResolver structure;
                * note that the structure contains self-referential pointers;
                * the pointers are fixed by the calling routine (since the 
                * caller's address space may be different from ours)
                */
                memcpy(&soResolver->ent,&__SOResolver.ent,sizeof(__SOResolver.ent));
                memcpy(soResolver->name,__SOResolver.name,sizeof(__SOResolver.name));
                memcpy(soResolver->addrList,__SOResolver.addrList,sizeof(__SOResolver.addrList));
                memcpy(soResolver->ptrList,__SOResolver.ptrList,sizeof(__SOResolver.ptrList));
            }
        }
            break;

        case NET_SO_GETLASTERROR:
            rv = SOGetLastError();
            break;

        case NET_SO_InetAtoN:
        {
            const char *cp  = (const char *) ioctl->inPtr;
            SOInAddr *inp   = (SOInAddr *) ioctl->outPtr;

            rv = SOInetAtoN(cp, inp);
        }
            break;

        case NET_SO_InetPtoN:
        {
            NETSoInetPtoN *netSoInetPtoN = (NETSoInetPtoN*) ioctl->outPtr;
            const char *src = (const char *) ioctl->inPtr;

            netSoInetPtoN->dst = (void *) &netSoInetPtoN->addrBuf;
            rv = SOInetPtoN(netSoInetPtoN->af, src, netSoInetPtoN->dst);
        }
            break;

        case NET_SO_InetNtoP:
        {
            NETSoInetNtoP *netSoInetNtoP = (NETSoInetNtoP *) ioctl->inPtr;
            char *dst = (char *) ioctl->outPtr;
            unsigned len = (unsigned) ioctl->outLen;
            const char *ret;

            // IOP can not do byte write on Napa memory region so we use temp buffer
            char dst2[SO_INET_ADDRSTRLEN];

            if (netSoInetNtoP->src != NULL) {
                netSoInetNtoP->src = (void *) &netSoInetNtoP->addrBuf;
            }
            ret = SOInetNtoP(netSoInetNtoP->af, netSoInetNtoP->src, dst2, len);

            if (!ret) {
                rv = IOS_ERROR_INVALID;
            } else {
                if (len > SO_INET_ADDRSTRLEN) {
                    len = SO_INET_ADDRSTRLEN;
                }
                memcpy(dst, dst2, len);
            }
        }
            break;

        case NET_SO_SOCKATMARK:
        {
            int socket = *( (int *) ioctl->inPtr);
            rv = SOSockAtMark(socket);
        }
            break;

        case NET_SO_SETINTERFACE:
        {
            int id = *( (int *) ioctl->inPtr);
            rv = SOSetInterface(id);
        }
            break;

        case NET_SO_INIT:
            SOInit();
            break;

        case NET_SO_STARTUP:
        {
            const SOConfig *config = (const SOConfig *)ioctl->inPtr;
            rv = SOStartup(config);
        }
            break;

        case NET_SO_CLEANUP:
            rv = SOCleanup();
            break;

        case NET_ICMP_SOCKET:
        {
            int af = * ((int *) ioctl->inPtr);

            rv = ICMPSocket(af);
        }
            break;

        case NET_ICMP_CANCEL:
        {
            int fd = *( (int *) ioctl->inPtr);

            rv = ICMPCancel(fd);
        }
            break;

        case NET_ICMP_CLOSE:
        {
            int fd = *( (int *) ioctl->inPtr);

            rv = ICMPClose(fd);
        }
            break;

        default:
            rv = IOS_ERROR_INVALID;
            break;
    }

    return rv;
}

static IOSError
sockRmIoctlv(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceIoctlv *ioctlv = (IOSResourceIoctlv *) &req->args.ioctlv;
    
    switch (ioctlv->cmd)
    {
        case NET_SO_SENDTO:
        {
            void *buf = (void *)ioctlv->vector[0].base;
            int len = ioctlv->vector[0].length;
            NETSoSend *netSoSend = (NETSoSend *)ioctlv->vector[1].base;
            
            if (netSoSend->sockTo != NULL) {
                netSoSend->sockTo = (void *) &netSoSend->addrBuf;
            }
            rv = SOSendTo(netSoSend->sock, buf, len, 
                netSoSend->flags, netSoSend->sockTo);
        }
            break;

        case NET_SO_RECVFROM:
        {
            NETSoRecv *netSoRecv = (NETSoRecv *)ioctlv->vector[0].base;
            void *buf = ioctlv->vector[1].base;
            int len = ioctlv->vector[1].length;
            void *sockFrom = ioctlv->vector[2].base;

            rv = SORecvFrom(netSoRecv->sock, buf, len, 
                netSoRecv->flags, sockFrom);
        }
            break;

        case NET_SO_GETINTOPT:
        {
            NETSoIntOpt *netSoIntOpt = (NETSoIntOpt *)ioctlv->vector[0].base;
            void *optval = ioctlv->vector[1].base;
            int *optlen = (int *)ioctlv->vector[2].base;

            rv = SOGetInterfaceOpt(NULL, netSoIntOpt->level, netSoIntOpt->optname, 
                optval, optlen);
        }
            break;

        case NET_SO_SETINTOPT:
        {
            NETSoIntOpt *netSoIntOpt = (NETSoIntOpt *)ioctlv->vector[0].base;
            void *optval = ioctlv->vector[1].base;
            int optlen = ioctlv->vector[1].length;

            rv = SOSetInterfaceOpt(NULL, netSoIntOpt->level, netSoIntOpt->optname, 
                optval, optlen);
        }
            break;

        case NET_SO_GETNAMEINFO:
        {
            NETSoNameInfo *netSoNameInfo = (NETSoNameInfo *)ioctlv->vector[0].base;
            char *node              = (char *) ioctlv->vector[1].base;
            unsigned nodeLen        = ioctlv->vector[1].length;
            char *service           = (char *) ioctlv->vector[2].base;
            unsigned serviceLen     = ioctlv->vector[2].length;
            const void *sockAddr    = NULL;
            int flags               = netSoNameInfo->flags;

            // IOP can not do byte write on Napa memory region so we use temp buffer
            char node2[DNS_NAME_MAX+1];
            char serv2[DNS_NAME_MAX+1];

            if (netSoNameInfo->sockAddr) {
                sockAddr = (void *) &netSoNameInfo->addrBuf;
            }
            rv = SOGetNameInfo(sockAddr, node2, DNS_NAME_MAX, serv2, DNS_NAME_MAX, flags);
            if (rv == 0) {
                if (nodeLen > (DNS_NAME_MAX+1))
                    nodeLen = DNS_NAME_MAX+1;
                if (serviceLen > (DNS_NAME_MAX+1))
                    serviceLen = DNS_NAME_MAX+1;
                if (node)
                    memcpy(node, node2, nodeLen);
                if (service)
                    memcpy(service, serv2, serviceLen);
            }
        }
            break;

        case NET_SO_GETADDRINFO:
        {
            const char *nodeName    = (const char *) ioctlv->vector[0].base;
            const char *servName    = (const char *) ioctlv->vector[1].base;
            const SOAddrInfo *hints = (const SOAddrInfo *) ioctlv->vector[2].base;
            SOAddrInfo *resLib      = (SOAddrInfo *) ioctlv->vector[3].base;
            SOAddrInfo *resStack;

            rv = SOGetAddrInfo(nodeName, servName, hints, &resStack);

            // copy *resStack to resLib
            if (rv == IOS_ERROR_OK)
            {
                SOAddrInfo *nodeStack = resStack;
                SOSockAddrIn6 *sockAddrIn6;
                int bufCount = (ioctlv->vector[3].length / sizeof(SOAddrInfo));
   
                sockAddrIn6 = (SOSockAddrIn6 *) (resLib + SO_MAX_ADDRINFO);
                while ((nodeStack != NULL) && (bufCount > 0))
                {
                    memcpy(resLib, nodeStack, sizeof(SOAddrInfo));
                    memcpy(sockAddrIn6, nodeStack->addr, nodeStack->addrLen);
                    sockAddrIn6++;
                    nodeStack = nodeStack->next;

                    if (nodeStack == NULL)
                    {
                        resLib->next = NULL;
                    }
                    else
                    {
                        resLib++;
                    }
                    bufCount--;
                }
                SOFreeAddrInfo(resStack);
            }
        }
            break;

        case NET_ICMP_PING:
        {
            NETIcmpPing *netIcmpPing = (NETIcmpPing *)ioctlv->vector[0].base;
            const void *data = (const void *)ioctlv->vector[1].base;
            int len = ioctlv->vector[1].length;
            
            if (netIcmpPing->remote != NULL) {
                netIcmpPing->remote = (const void *) &netIcmpPing->addrBuf;
            }
            rv = ICMPPing(netIcmpPing->fd, data, len, 
                netIcmpPing->remote, netIcmpPing->timeout);
        }
            break;

        default:
            rv = IOS_ERROR_INVALID;
            break;
    }

    return rv;
}

static void
sockRM(u32 arg)
{   
    IOSError rv = IOS_ERROR_OK;
    IOSMessage msg;
    IOSResourceRequest *req;

    /* Sit in a loop processing requests */
    while(1) {
        IOS_ReceiveMessage(__qid, &msg, IOS_MESSAGE_BLOCK);
        req = (IOSResourceRequest *)msg;
        switch(req->cmd) {
            case IOS_OPEN:
            case IOS_CLOSE:
                rv = 0;
                break;
            case IOS_IOCTL:
                rv = sockRmIoctl(req);
                break;
            case IOS_IOCTLV:
                rv = sockRmIoctlv(req);
                break;
            default:
                OSReport("%s: socket RM got UNKNOWN request\n", __FUNCTION__);
                rv = IOS_ERROR_INVALID;
                break;
        }
        IOS_ResourceReply(req, rv);
    }
}

BOOL
NetInitSockRM( void )
{
    IOSThreadId rmThreadId;
    u32 i;

    /* Create a RM message queue for socket interface layer */
    if ( (__qid = IOS_CreateMessageQueue(__msgQ, NET_SOCK_MSGQ_SIZE)) < 0 ) {
        OSReport("%s: creating message queue failed\n", __FUNCTION__);
        return FALSE;
    }
    
    /* Register RM */
    if ( IOS_ERROR_OK != IOS_RegisterResourceManager(NET_RM_SOCK, __qid) ) {
        IOS_DestroyMessageQueue(__qid);
        OSReport("%s: registering network socket RM failed\n", __FUNCTION__);
        return FALSE;
    }

    for (i = 1; i < SO_SOCKET_MAX; i++)
    {
        rmThreadId = IOS_CreateThread(sockRM, NULL, __netSockStack + i*NET_SOCK_STACK_SIZE,
            NET_SOCK_STACK_SIZE, IOS_PRIORITY_NET, IOS_THREAD_CREATE_DETACHED);
    
        if (rmThreadId < 0) {
            OSReport("%s: could not create net socket RM thread - exiting\n", __FUNCTION__);
            return FALSE;
        }
        IOS_SetThreadPriority(rmThreadId, NET_WORK_PRIORITY);
        OSInitThread(rmThreadId, NET_WORK_PRIORITY);
    
        if (IOS_StartThread(rmThreadId) != IOS_ERROR_OK) {
            OSReport("%s: could not start net socket RM thread\n", __FUNCTION__);
            return FALSE;
        }
    }

    return TRUE;
}

BOOL
NetShutdownSockRM( void )
{
    /* Unregister RM. Destroys message queue. */
    IOS_DestroyMessageQueue(__qid);
    return TRUE;
}

/*---------------------------------------------------------------------------*
 * 
 * main functions
 * 
 *---------------------------------------------------------------------------*/

extern BOOL NetInitIfRM(void);

#ifdef _DEBUG
extern int fifo(void);
extern int ringex(void);
extern int reasm(void);
extern int sackhole(void);
extern int sackopt(void);
extern int trim(void);
extern int label(void);
#endif

int
main(void)
{
    OSInitInterrupts();
    initNetMem();
    OSInitThreadPool();
    OSInitAlarm();
    NetInitIfRM();
    NetInitSockRM();

#ifdef _DEBUG
#if 0
    fifo();
    ringex();
    reasm();
    sackhole();
    sackopt();
    trim();
    label();
#endif
#endif // _DEBUG

    IOS_SetThreadPriority(IOS_GetThreadId(), NET_WORK_PRIORITY);
    OSInitThread(IOS_GetThreadId(), NET_WORK_PRIORITY);
    sockRM(0);

    OSDbgReport(("****** This should never be printed *******\n"));
    IOS_DestroyThread(0, NULL);

    return 1;
}
