/*NB_REVISION*/

/*
 * This code shows a simple AHDLC interface.  It assumes that some
 * kind of serial hardware with FIFOs is in use and that interrupts
 * from this hardware and from the PPP system above can be disabled
 * and that the CPU uses 8 bit bytes and 32 bit longs.
 *
 * It is also assumed that packets sent and received pass through
 * queues and are simple buffers.  Generic "queue_append" and
 * "queue_fetch" functions are used for access, and buffers are
 * acquired through "buffer_fetch" and released back to the system by
 * a "buffer_release" function.  The ACCM mechanism supports escaping
 * of all characters.
 *
 *
 * This code may be used for any purpose as long as the author's
 * copyright is cited in any source code distributed.  This code
 * is also available electronically from the author's web site.
 *
 * http://people.ne.mediaone.net/carlson/ppp
 *
 * Copyright 1997 by James Carlson
 */

// NB Definitions
#include <predef.h>

// NB Libs
#include <buffers.h>
#include <counters.h>
#include <ctype.h>
#include <iosys.h>
#include <nbrtos.h>
#include <serial.h>
#include <startnet.h>
#include <stdio.h>
#include <string.h>
#include <utils.h>
#include <nettypes.h>

/* Interface to networking portion of operating system. */
extern void process_rx(PoolPtr);

typedef unsigned char octet;
typedef unsigned short uint16;
typedef unsigned long uint32;

#define MAXIMUM_MRU 1508
#define PPP_DATAOFFSET 10

/* Standard CRC tables from RFC 1662. */
static uint16 fcstab_16[256] = {
    0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
    0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
    0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
    0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
    0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
    0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
    0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
    0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
    0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
    0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
    0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
    0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
    0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
    0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
    0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
    0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78};

#define PPPINITFCS16 0xFFFF
#define PPPGOODFCS16 0xF0B8

#define PPP_FRAME 0x7E
#define PPP_ESCAPE 0x7D
#define PPP_ESCAPE_BIT 0x20

struct ahdlc_state
{
    /* User controlled variables. */
    octet tx_accm[32], rx_accm[32];
    /* Internal state data. */
    unsigned char *rx_bufp;
    PoolPtr rx_pool;
    beuint16_t rx_crc;
    char escaped;
    OS_SEM TransmitSemaphore;
};

static ahdlc_state TheAhdlcOneState;

/*
 * This function allocates a state structure for AHDLC.  This
 * structure is used to hold all of the variables necessary for AHDLC
 * operation across multiple invocations from the serial interrupt
 * handlers.
 *
 * The 'tosend' argument is a pointer to a system queue where packets
 * waiting to be sent are held.  It is the responsibility of the
 * caller to detect that the tosend queue is empty and to start the
 * transmission process by calling the output routine once.  As long
 * as the queue still has data, the output routine will send packets.
 *
 * The "fromreceive" argument is also a pointer to a system queue.
 * Packets received from the serial interface will be placed there.
 * The caller is responsible for removing packets from this queue.
 * This could be triggered by the "queue_append" routine, depending on
 * system implementation.
 */

void ahdlc_initialize_rxbuffer(ahdlc_state *as)
{
    puint32_t pdw;
    int i;
    as->rx_bufp = as->rx_pool->pData + PPP_DATAOFFSET;
    pdw = (puint32_t)as->rx_pool->pData;
    for (i = 0; i < 5; i++)
    {
        pdw[i] = 0;
    }
    as->rx_crc = PPPINITFCS16;
    as->rx_pool->usedsize = 0;
}

void ahdlc_create()
{
    struct ahdlc_state *as;
    int i;

    as = &TheAhdlcOneState;
    if (as != NULL)
    {
        memset(as, '\0', sizeof(*as));

        for (i = 0; i < 4; i++)
        {
            as->tx_accm[i] = 0xFF;
            as->rx_accm[i] = 0xFF;
        }
        as->tx_accm[PPP_FRAME / 8] |= 1 << (PPP_FRAME & 7);
        as->tx_accm[PPP_ESCAPE / 8] |= 1 << (PPP_ESCAPE & 7);

        as->rx_pool = GetBuffer();
        ahdlc_initialize_rxbuffer(as);
        as->TransmitSemaphore.Init(1);
    }
    return;
}

/*
 * This function removes storage associated with an AHDLC link.  I/O
 * on the link itself should have be stopped before this function is
 * called.
 */
void ahdlc_destroy()
{
    struct ahdlc_state *as = &TheAhdlcOneState;

    if (as != NULL) { FreeBuffer(as->rx_pool); }
}

/*
 * This routine handles a block of data received from the serial
 * interface.
 * When packets are correctly received, this routine will
 * place them on the PPP input queue.
 */
void ahdlc_receive(char *buffer, int count)
{
    struct ahdlc_state *as = &TheAhdlcOneState;
    octet chr;

    while (--count >= 0)
    {
        chr = 0xFF & (int)*buffer++;

        /*
         * If ACCM bit is set, then this shouldn't be seen.  Drop it.
         * This isn't an error, though.  The receiver may be transparent
         * to control characters which are used for purposes other than
         * PPP.
         */
        if (as->rx_accm[chr / 8] & (1 << (chr & 7))) { continue; }

        if (as->escaped)
        {
            /* Handle the escape mechanism. */
            as->escaped = 0;
            if (chr == PPP_FRAME) { goto reset_buffer; }
            chr ^= PPP_ESCAPE_BIT;
        }
        else if (chr == PPP_FRAME)
        {
            /* End of frame. */
            if (as->rx_crc == PPPGOODFCS16)
            {
                as->rx_pool->usedsize -= 2;
                process_rx(as->rx_pool);
                as->rx_pool = GetBuffer();
                as->rx_pool->usedsize = 0;
            }
            else if (as->rx_pool->usedsize > 3)
            {
                goto notify_error;
            }
            goto reset_buffer;
        }
        else if (chr == PPP_ESCAPE)
        {
            as->escaped = 1;
            continue;
        }

        /* If we're here, then we have an input data octet. */
        if (as->rx_pool->usedsize >= MAXIMUM_MRU)
        {
        notify_error:
            /*
             * Notify PPP of receive error here!  Some protocols, like VJ
             * compressed TCP/IP, work much better when receive errors are
             * caught and reported by the driver.
             */
            frames_rx_ppp_errors++;

        reset_buffer:
            ahdlc_initialize_rxbuffer(as);
        }
        else
        {
            as->rx_crc = (as->rx_crc >> 8) ^ fcstab_16[(as->rx_crc ^ chr) & 0xFF];
            *as->rx_bufp++ = (char)chr;
            as->rx_pool->usedsize++;
            if (as->rx_pool->usedsize == 4)
            {
                /* Time to do some adjusting */
                /* The frame beginign can have several forms */
                /*We want all of the forms to be stored in the buffer as: */
                /*FF03XXXX where XXXX = frame type code  case 1*/
                /*FF03XXDD where 00XX = frame type code  case 2*/
                /*XXXXDDDD where XXXX = frame type code  case 3*/
                /*XXDDDDDD where 00XX = frame type code. case 4*/

                beuint16_t *pWord = (beuint16_t *)(as->rx_pool->pData + PPP_DATAOFFSET);
                if (*pWord != 0xFF03)
                {
                    // Adjust
                    *(pWord + 2) = *(pWord + 1);
                    *(pWord + 1) = *(pWord);
                    *pWord = 0xFF03;
                    as->rx_pool->usedsize += 2;
                    as->rx_bufp += 2;
                }

                pWord++;
                if (*pWord & 0x0100)
                {
                    // Adjust one byte over.
                    // At the code level
                    as->rx_bufp++;
                    as->rx_pool->usedsize++;
                    puint8_t cp = as->rx_bufp;
                    while (cp != (puint8_t)pWord)
                    {
                        *cp = *(cp - 1);
                        cp--;
                    }
                    *cp = 0;
                }
            }   // Time to adjust!
        }
    }
}

extern fd_set write_file_sets;
extern int sel_reason;

void ahdlcrawwrite(int fd, char c)
{
    int rv = write(fd, &c, 1);

    if (rv == 0)
    {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(fd, &fds);
        rv = select(FD_SETSIZE, (fd_set *)0, &fds, (fd_set *)0, 10000);
        if (rv == 0)
        {
            DBPRINT(DB_PPP, "Select failed\n");
            return;
        }
        rv = write(fd, &c, 1);
    }
}

void sendone(int fd, char c, ahdlc_state *as)
{
    static char last_char;

    if ((as->tx_accm[c / 8] & (1 << (c & 7))) || ((last_char == 'A') && (c == 'T')))
    {
        char co = c;
        c = PPP_ESCAPE;
        ahdlcrawwrite(fd, c);
        c = (co) ^ PPP_ESCAPE_BIT;
        ahdlcrawwrite(fd, c);
    }
    else
    {
        ahdlcrawwrite(fd, c);
    }
    last_char = c;
}

/*
 * This routine will place a frame in the output queue for the serial link fd.
 */
void ahdlc_transmit(int fd, char *buffer, int n)
{
    struct ahdlc_state *as = &TheAhdlcOneState;
    char c;
    char *cp = buffer;
    int nleft = n;
    as->TransmitSemaphore.Pend();

    beuint16_t crc = PPPINITFCS16;
    c = PPP_FRAME;
    /* Write start of frame */
    ahdlcrawwrite(fd, c);

    while (nleft)
    {
        char c = *cp++;
        nleft--;
        crc = (crc >> 8) ^ fcstab_16[(crc ^ c) & 0xFF];
        sendone(fd, c, as);
    }
    /* Now to write the CRC */
    crc = ~crc;

    sendone(fd, ((char *)&crc)[1], as);
    sendone(fd, ((char *)&crc)[0], as);
    c = PPP_FRAME;
    ahdlcrawwrite(fd, c);
    as->TransmitSemaphore.Post();
}

/*
 * This routine sets the standard PPP receive and transmit ACCM.  It
 * should be called by LCP.  Again, like the sync routine above, it
 * assumes a number of BSD kernel functions.
 */
void ahdlc_set_tx_accm(uint32 tx_accm)
{
    struct ahdlc_state *as = &TheAhdlcOneState;

    USER_ENTER_CRITICAL();
    as->tx_accm[0] = tx_accm & 0xFF;
    as->tx_accm[1] = (tx_accm >> 8) & 0xFF;
    as->tx_accm[2] = (tx_accm >> 16) & 0xFF;
    as->tx_accm[3] = (tx_accm >> 24) & 0xFF;
    USER_EXIT_CRITICAL();
    PPPDBPRINT("Setting TX ACCM:");
    PPPDBNUM(tx_accm);
    PPPDBPRINT("\r\n");
}

void ahdlc_set_rx_accm(uint32 rx_accm)
{
    struct ahdlc_state *as = &TheAhdlcOneState;

    USER_ENTER_CRITICAL();
    as->rx_accm[0] = rx_accm & 0xFF;
    as->rx_accm[1] = (rx_accm >> 8) & 0xFF;
    as->rx_accm[2] = (rx_accm >> 16) & 0xFF;
    as->rx_accm[3] = (rx_accm >> 24) & 0xFF;
    USER_EXIT_CRITICAL();
    PPPDBPRINT("Setting RX ACCM:");
    PPPDBNUM(rx_accm);
    PPPDBPRINT("\r\n");
}
