RealtimeCompLab2

Dependencies:   mbed

Fork of PPP-Blinky by Nicolas Nackel

main.cpp

Committer:
nixnax
Date:
2017-01-02
Revision:
21:66459cb32ce0
Parent:
20:5db9b77b38a6
Child:
22:00df34cd4d7e

File content as of revision 21:66459cb32ce0:

#include "mbed.h"

// Copyright 2016 Nicolas Nackel. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// Proof-of-concept for TCP/IP using Windows 7/8/10 Dial Up Networking over MBED USB Virtual COM Port

// Toggles LED1 every time the PC sends an IP packet over the PPP link

// Note - turn off all authentication, passwords, compression etc. Simplest link possible.

// Handy links
// https://developer.mbed.org/users/nixnax/code/PPP-Blinky/  - introduction and notes
// http://atari.kensclassics.org/wcomlog.htm
// https://technet.microsoft.com/en-us/library/cc957992.aspx
// http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
// https://en.wikibooks.org/wiki/Serial_Programming/IP_Over_Serial_Connections
// http://pingtester.net/ - nice tool for high rate ping testing

Serial pc(USBTX, USBRX); // The USB com port - Set this up as a Dial-Up Modem on your pc
Serial xx(PC_10, PC_11); // debug((((( port - use an additional USB serial port to monitor this

// the second #define below gets rid of all the debug printfs
#define debug(x) xx.printf x
//#define debug(x) {}

DigitalOut led1(LED1);

#define FRAME_7E (0x7e)
#define BUFLEN (1<<14)
char rxbuf[BUFLEN];
char frbuf[6000]; // buffer for ppp frame

struct {
    int online; 
    struct {
        char * buf;
        volatile int head; 
        volatile int tail; 
        int total;
    } rx; // serial port buffer
    struct {
        int id;
        int len;
        int crc;
        char * buf;
    } pkt; // ppp buffer
} ppp;

void pppInitStruct(){ ppp.online=0; ppp.rx.buf=rxbuf; ppp.rx.tail=0; ppp.rx.head=0; ppp.rx.total=0; ppp.pkt.buf=frbuf; ppp.pkt.len=0;}

int crcG; // frame check sequence (CRC) holder
void crcDo(int x){for (int i=0;i<8;i++){crcG=((crcG&1)^(x&1))?(crcG>>1)^0x8408:crcG>>1;x>>=1;}} // crc calculator
void crcReset(){crcG=0xffff;} // crc restart
int crcBuf(char * buf, int size){crcReset();for(int i=0;i<size;i++)crcDo(*buf++);return crcG;} // crc on a block of memory

void rxHandler() // serial port receive interrupt handler
{
    while ( pc.readable() ) {
        int hd = (ppp.rx.head+1)&(BUFLEN-1); // increment/wrap
        if ( hd == ppp.rx.tail ) break; // watch for buffer full
        ppp.rx.buf[ppp.rx.head]=pc.getc(); // insert in rx buffer
        ppp.rx.head = hd; // update head pointer
    }
}

int ledState=0;
void led1Toggle(){ 
    ledState = ledState? 0 : 1;
    led1 = ledState;
}

int pc_readable() // check if buffer has data
{
    return (ppp.rx.head==ppp.rx.tail) ? 0 : 1 ; 
}

int pc_getBuf() // get one character from the buffer
{
    if (ppp.rx.head!=ppp.rx.tail) {
        int x = ppp.rx.buf[ ppp.rx.tail ];
        __disable_irq(); // critical section start
            ppp.rx.tail=(ppp.rx.tail+1)&(BUFLEN-1); // atomic operation
        __enable_irq(); // critical section end
        return x;
    } else return -1;
}

void scanForConnectString(); // scan for connect attempts from pc

void processFrame(int start, int end) { // process received frame
    led1Toggle(); // change led1 state when frames are received
    if(start==end) {  pc.putc(0x7e); return; }
    crcReset();
    char * dest = ppp.pkt.buf;
    ppp.pkt.len=0;
    int unstuff=0;
    int idx = start;
    while(1) {
        if (unstuff==0) {
            if (rxbuf[idx]==0x7d) unstuff=1; 
            else { *dest = rxbuf[idx]; ppp.pkt.len++; dest++; crcDo(rxbuf[idx]); }
        } else { // unstuff
            *dest = rxbuf[idx]^0x20; ppp.pkt.len++; dest++; crcDo(rxbuf[idx]^0x20);
            unstuff=0;
        }
        idx = (idx+1) & (BUFLEN-1);
        if (idx == end) break;
    }
    ppp.pkt.crc = crcG & 0xffff;
    if (ppp.pkt.crc == 0xf0b8) { // check for good CRC
        void determinePacketType(); // declaration only
        determinePacketType();
    } else { // crc error
         debug(("CRC is %x Len is %d\n",ppp.pkt.crc,ppp.pkt.len));
         for(int i=0;i<ppp.pkt.len;i++) debug(("%02x ", ppp.pkt.buf[i]));
         debug(("\n"));
    }
}

void dumpFrame() {
    for(int i=0;i<ppp.pkt.len;i++) debug(("%02x ", ppp.pkt.buf[i]));
    debug((" C=%02x %02x L=%d\n", ppp.pkt.crc&0xff, (ppp.pkt.crc>>8)&0xff, ppp.pkt.len));
}

void hdlcPut(int ch) { // do hdlc handling of special (flag) characters
    if ( (ch<0x20) || (ch==0x7d) || (ch==0x7e) ) { pc.putc(0x7d); pc.putc(ch^0x20); } else { pc.putc(ch); }
}

void sendFrame(){
    int crc = crcBuf(ppp.pkt.buf, ppp.pkt.len-2); // update crc
    ppp.pkt.buf[ ppp.pkt.len-2 ] = (~crc>>0); // fcs lo (crc)
    ppp.pkt.buf[ ppp.pkt.len-1 ] = (~crc>>8); // fcs hi (crc)
    pc.putc(0x7e); // hdlc start-of-frame "flag"
    for(int i=0;i<ppp.pkt.len;i++) hdlcPut( ppp.pkt.buf[i] );
    pc.putc(0x7e); // hdlc end-of-frame "flag"
}

void ipRequestHandler(){
    debug(("IPCP Conf "));
    if ( ppp.pkt.buf[7] != 4 ) {
        debug(("Rej\n")); // reject if any options are requested
        ppp.pkt.buf[4]=4;
        sendFrame();
    } else  {
        debug(("Ack\n"));
        ppp.pkt.buf[4]=2; // ack the minimum
        sendFrame(); // acknowledge
        debug(("IPCP Ask\n")); 
        // send our own request now
        ppp.pkt.buf[4]=1; // request no options
        ppp.pkt.buf[5]++; // next sequence
        sendFrame(); // this is our request
    }
}

void ipAckHandler(){ debug(("IPCP Grant\n")); }

void ipNackHandler(){ debug(("IPCP Nack\n")); }

void ipDefaultHandler(){ debug(("IPCP Other\n")); }

void IPCPframe() {
    int code = ppp.pkt.buf[4]; // packet type is here
    switch (code) {
        case 1: ipRequestHandler(); break;
        case 2: ipAckHandler(); break;
        case 3: ipNackHandler(); break;
        default: ipDefaultHandler();    
    }
}    

void UDPpacket() {
    char * udpPkt = ppp.pkt.buf+4; // udp packet start
    int headerSizeIP = (( udpPkt[0]&0xf)*4);
    char * udpBlock = udpPkt + headerSizeIP; // udp info start 
    char * udpSrc = udpBlock; // source port
    char * udpDst = udpBlock+2; // destination port
    char * udpLen = udpBlock+4; // udp data length
    char * udpInf = udpBlock+8; // actual start of info
    int srcPort = (udpSrc[0]<<8) | udpSrc[1];
    int dstPort = (udpDst[0]<<8) | udpDst[1];
    char * srcIP = udpPkt+12; // udp src addr
    char * dstIP = udpPkt+16; // udp dst addr
    #define UDP_HEADER_SIZE 8
    int udpLength = ((udpLen[0]<<8) | udpLen[1]) - UDP_HEADER_SIZE; // size of the actual udp data
    debug(("UDP %d.%d.%d.%d:%d ", srcIP[0],srcIP[1],srcIP[2],srcIP[3],srcPort));
    debug(("%d.%d.%d.%d:%d ",    dstIP[1],dstIP[1],dstIP[1],dstIP[1],dstPort));
    debug(("Len %d ", udpLength));
    int printSize = udpLength; if (printSize > 20) printSize = 20; // print only first 20 characters
    for (int i=0; i<printSize; i++) { char ch = udpInf[i]; if (ch>31 && ch<127) { debug(("%c", ch)); } else { debug(("_")); } } 
    debug(("\n"));
}

int dataCheckSum(char * ptr, int len) {
    int sum=0;
    for (int i=0;i<len/2;i++) {
        int hi = *ptr; ptr++;
        int lo = *ptr; ptr++;
        int val = ( lo & 0xff ) | ( (hi<<8) & 0xff00 );
        sum = sum + val;
    }
    sum = sum + (sum>>16);
    return ~sum;
}    

void headerCheckSum() {
    int len =(ppp.pkt.buf[4]&0xf)*4; // length of header in bytes
    char * ptr = ppp.pkt.buf+4; // start of ip packet
    int sum=0;

    for (int i=0;i<len/2;i++) {
        int hi = *ptr; ptr++;
        int lo = *ptr; ptr++;
        int val = ( lo & 0xff ) | ( (hi<<8) & 0xff00 );
        sum = sum + val;
    }
    sum = sum + (sum>>16);
    sum = ~sum;
    ppp.pkt.buf[14]= (sum>>8);
    ppp.pkt.buf[15]= (sum   );
}    

void ICMPpacket() { // internet control message protocol
    char * ipPkt = ppp.pkt.buf+4; // ip packet start
    char * pktLen = ipPkt+2;
    int packetLength = (pktLen[0]<<8) | pktLen[1]; // icmp packet length
    int headerSizeIP = (( ipPkt[0]&0xf)*4);
    char * icmpType = ipPkt + headerSizeIP; // icmp data start
    char * icmpSum = icmpType+2; // icmp checksum

    #define ICMP_TYPE_PING_REQUEST 8
    if ( icmpType[0] == ICMP_TYPE_PING_REQUEST ) { 
        char * ipTTL = ipPkt+8; // time to live
        ipTTL[0]--; // decrement time to live
        char * srcAdr = ipPkt+12;
        char * dstAdr = ipPkt+16;
        int icmpIdent = (icmpType[4]<<8)|icmpType[5];
        int icmpSequence = (icmpType[6]<<8)|icmpType[7];     
        debug(("ICMP PING %d.%d.%d.%d %d.%d.%d.%d Ident %04x Sequence %04d ", srcAdr[0],srcAdr[1],srcAdr[2],srcAdr[3],dstAdr[0],dstAdr[1],dstAdr[2],dstAdr[3],icmpIdent,icmpSequence));
        char src[4]; char dst[4];
        memcpy(src, srcAdr,4);
        memcpy(dst, dstAdr,4);
        memcpy(srcAdr, dst,4);
        memcpy(dstAdr, src,4); // swap src & dest ip
        char * chkSum = ipPkt+10;
        chkSum[0]=0; chkSum[1]=0;
        headerCheckSum();  // new ip header checksum
        #define ICMP_TYPE_ECHO_REPLY 0
        icmpType[0]=ICMP_TYPE_ECHO_REPLY; // icmp echo reply
        icmpSum[0]=0; icmpSum[1]=0; // zero the checksum for recalculation
        int icmpLength = packetLength - headerSizeIP; // length of ICMP data portion
        int sum = dataCheckSum( icmpType, icmpLength); // this checksum on icmp data portion
        icmpSum[0]=sum>>8; icmpSum[1]=sum; // new checksum for ICMP data portion

        int printSize = icmpLength-8; // exclude size of icmp header
        char * icmpData = icmpType+8; // the actual data is after the header
        if (printSize > 10) printSize = 10; // print only first 20 characters
        for (int i=0; i<printSize; i++) { char ch = icmpData[i]; if (ch>31 && ch<127) { debug(("%c",ch)); } else { debug(("%c",'_')); }}
        debug(("%c",'\n'));
        sendFrame(); // reply to the ping
    } else {
        debug(("ICMP type=%d \n", icmpType[0])); 
    }
}

void IGMPpacket() { // internet group management protocol
    debug(("IGMP type=%d \n", ppp.pkt.buf[28])); 
}    

void TCPpacket() {
    debug(("TCP\n"));
    /*
    switch (protocol) {
        case  2: TCPsyn();  break;
        case 17: TCPack();   break;
        case  6: TCPpacket();   break;
        default: debug(((( "Other \n");
    }        
    */
}    

void otherProtocol() {
    debug(("Other IP protocol"));
}

void IPframe() {
    int protocol = ppp.pkt.buf[13];
    switch (protocol) {
        case    1: ICMPpacket();  break;
        case    2: IGMPpacket();  break;
        case   17: UDPpacket();   break;
        case    6: TCPpacket();   break;
        default: otherProtocol();
    }        
    //debug((("IP frame proto %3d len %4d %d.%d.%d.%d  %d.%d.%d.%d\n", ppp.pkt.buf[13],(ppp.pkt.buf[6]<<8)+ppp.pkt.buf[7],ppp.pkt.buf[16],ppp.pkt.buf[17],ppp.pkt.buf[18],ppp.pkt.buf[19],ppp.pkt.buf[20],ppp.pkt.buf[21],ppp.pkt.buf[22],ppp.pkt.buf[23] );
}    

void LCPconfReq() {
    debug(("LCP Config "));
    if (ppp.pkt.buf[7] != 4) {
        ppp.pkt.buf[4]=4; // allow only no options
        debug(("Reject\n"));
        sendFrame(); 
    } else {
        ppp.pkt.buf[4]=2; // ack zero conf
        debug(("Ack\n"));
        sendFrame();
        debug(("LCP Ask\n"));
        ppp.pkt.buf[4]=1; // request no options
        sendFrame();
    }
}

void LCPconfAck() {
    debug(("LCP Ack\n"));
} 

void LCPend(){
     debug(("LCP End\n"));
     ppp.online=0; // start hunting for connect string again
     ppp.pkt.buf[4]=6;
     sendFrame(); // acknowledge
}

void LCPother(){
     debug(("LCP Other\n"));
     dumpFrame();
}

void LCPframe(){
     int code = ppp.pkt.buf[4];
     switch (code) {
         case 1:    LCPconfReq(); break; // config request
         case 2:    LCPconfAck(); break; // config ack
         case 5:    LCPend();     break; // end connection
         default:   LCPother();
     }
}

void discardedFrame() {
    debug(("Dropping frame %02x %02x %02x %02x\n", ppp.pkt.buf[0],ppp.pkt.buf[1],ppp.pkt.buf[2],ppp.pkt.buf[3]));
}

void determinePacketType() {
    if ( ppp.pkt.buf[0] != 0xff ) { debug(("byte0 != ff\n")); return;}
    if ( ppp.pkt.buf[1] != 3    ) { debug(("byte1 !=  3\n")); return;}
    if ( ppp.pkt.buf[3] != 0x21 ) { debug(("byte2 != 21\n")); return;}
    int packetType = ppp.pkt.buf[2];
    switch (packetType) {
        case 0xc0:  LCPframe();     break;  // link control
        case 0x80:  IPCPframe();    break;  // IP control
        case 0x00:  IPframe();      break;  // IP itself
        default:    discardedFrame();
    }
}    

void scanForConnectString() {
    if ( ppp.online==0 ) {
        char * clientFound = strstr( (char *)rxbuf, "CLIENTCLIENT" ); // look for PC string
        if( clientFound ) { 
            strcpy( clientFound, "FOUND!FOUND!" ); // overwrite so we don't get fixated
            pc.printf("CLIENTSERVER"); // respond to PC
            ppp.online=1; // we can stop looking for the string
            debug(("Connect string found\n"));
        }
    }
}

int main()
{
    pc.baud(115200); // USB virtual serial port
    xx.baud(115200); // second serial port for debug(((((((( messages
    xx.puts("\x1b[2J\x1b[HReady\n"); // VT100 code for clear screen & home
    
    pppInitStruct(); // initialize all the PPP properties

    pc.attach(&rxHandler,Serial::RxIrq); // start the receive handler

    int frameStartIndex, frameEndIndex; int frameBusy=0;

    while(1) {
        if ( ppp.online==0 ) scanForConnectString(); // try to connect
        while ( pc_readable() ) {
            int rx = pc_getBuf();
            if (frameBusy) { 
                if (rx==FRAME_7E) {
                    frameBusy=0; // done gathering frame
                    frameEndIndex=ppp.rx.tail-1; // remember where frame ends
                    processFrame(frameStartIndex, frameEndIndex);
                }
            } 
            else {
                if (rx==FRAME_7E) {
                    frameBusy=1; // start gathering frame
                    frameStartIndex=ppp.rx.tail; // remember where frame started
                }
            }
        }
    }
}