Small Internet Protocol Stack using a standard serial port.

Dependencies:   mbed

PPP-Blinky - TCP/IP Networking Over a Serial Port

Note: The source code is at the bottom of this page.

/media/uploads/nixnax/blinky-connected.gif
A Windows desktop showing PPP-Blinky in the network connections list.

Describe PPP-Blinky in Three Sentences

PPP-Blinky is a tiny library that enables Internet protocols (IPv4) to any mbed target hardware by using only a serial port.

The code runs on processors with as little as 8k RAM, for example the Nucleo-L053R8 board.

PPP-Blinky uses the industry-standard PPP (Point-to-Point) Protocol and a tiny "stateless" TCP/IP stack.

No Ethernet Port Required

No ethernet port is required - PPP-Blinky uses a serial port to send IP packets to your PC.

PPP-Blinky emulates a standard dial-up modem and therefore connects to Windows, Linux or Adroid machines.

The code runs on most ARM mbed platforms such as the LPC11U24 shown in the picture below:

/media/uploads/nixnax/blinky-to-laptop1.jpg mbed LPC11u24 acting as a webserver to a Windows laptop.

Webserver

The Webserver and WebSocket functions are ideal for building browser-based GUIs on mbed-enabled hardware.

PPP-Blinky's HTTP webserver works with most web clients such as Internet Explorer, Mozilla Firefox, Google Chrome, Safari, Curl, wget and Lynx as well as Microsoft Powershell Invoke-Webrequest command.

In the image below Firefox web browser displays the main web page embedded into PPP-Blinky's code:

/media/uploads/nixnax/ppp-blinky-firefox.jpg Firefox web browser displays a web page embedded into PPP-Blinky's code

WebSocket Service

WebSocket is the most popular protocol standard for real-time bidirectional TCP/IP communication between clients and servers.
In the image below a small Internet Explorer script has connected to PPP-Blinky's WebSocket Service.
A websocket message was then sent by the browser and was echoed back by the WebSocket, triggering the onmessage event in the script.
The WebSocket service enables bidirectional real-time interaction between PPP-Blinky and any element in the browser DOM via JavaScript.
If you already have PPP-Blinky up and running you can test your WebSocket service using this: http://jsfiddle.net/d26cyuh2/112/embedded/result
Websockets are ideal for building browser-based GUIs for mbed hardware.

/media/uploads/nixnax/ppp-blinky-websocke-2.gif

Trying PPP-Blinky on your mbed board

You will need an mbed-enabled hardware board: https://developer.mbed.org/platforms/

Establish a serial port connection between your host PC and your mbed board. The easiest way is to use mbed hardware with a USB serial debug port. I've tried the ST-Micro Nucleo-L476RG, Nucleo-L152RE, Nucleo-F401RE, Nucleo-L432KC, Nucleo-L053R8, mbed-LPC11U24 and mbed-LPC1768 boards and they all work out of the box. Use the mbed online compiler to compile the software for your target board. Save the compiled binary to your hardware.

Before establishing a network connection, you can verify the operation of the code by opening a terminal program such as Tera Term, and setting the baud rate of the COM port on your mbed board to 115200 baud. LED1 should toggle for every two 0x7E (~) (i.e. tilde) characters you type, as 0x7E is the PPP frame start/end marker. Don't forget to close the port when your'e done testing, or else Windows Dial-up Networking will report that the COM port is in use by another program when you try to connect.

Once you are certain that the serial port and firmware is working, proceed to creating a new network connection on your PC -see below.

Creating a Dial-up Connection in Windows

/media/uploads/nixnax/modem.jpg

Setting up Dial-Up Networking (DUN) on your Windows 7 or 8 PC is essentially a two-step process: First, you create a new modem device, because PPP-blinky partially emulates a standard Windows serial port modem device. Second, you create a new Internet connection (in practice, a new network adapter) which is associated with your new "modem".

Step-by-step description of how to configure Windows for PPP-Blinky here:

/users/nixnax/code/PPP-Blinky/wiki/Configuring-Windows-Dial-Up-Networking

There is also a screen on how to set up Linux dial-up networking near the bottom of this page.

Connecting to PPP-Blinky from your PC

Once Windows networking is configured you can establish a dial-up connection to your mbed board over the USB virtual com port.

The IP address you manually assigned to the new dial-up network adapter (172.10.10.1) functions as a gateway to any valid IP address on that subnet. In the screen capture below, I'm sending pings from the Windows 8 command line to my ST-Micro Nucleo-L476RG board over the USB virtual serial Port. I'm also using a second serial port and Tera Term to capture the debug output from a second serial port on the hardware. The optional debug output from the board prints out the IP source and destination address and the first few bytes of the data payload. Note that the source is the adapter IP address, (172.10.10.1 in this case) and the destination is some other address on that subnet - all packets to the subnet are sent to our mbed hardware. For example, you could also ping 172.10.10.123 or, if your PPP-Blinky is running, simply click on this link: http://172.10.10.123

/media/uploads/nixnax/ping-cap-3.gif

One Million Pings!

In the image below the ICMP ("ping") echo reply service was tested by sending one million pings to ppp-Blinky. This took over two hours.
The ping tool used on the Windows 8 PC was psping.exe from PsTools by Mark Russinovich - http://bit.ly/PingFast
The average reply time for a short ping (1 byte of payload data) was 11 milliseconds at 115200 baud on the $10 Nucleo-L053R8 board - barely enough time for 130 bytes to be sent over the port!

/media/uploads/nixnax/ppp-blinky-ping-results.jpg

Monitoring PPP-Blinky Packets

The image below is from a Microsoft Network Monitor 3.4 capture session.

Responses from PPP-Blinky are shown in blue.

Frame 2 - Internet Explorer at IP 172.10.10.1 (the Dial-Up Adapter IP) requests a TCP connection by sending an S (SYN) flag.
Frame 3 - PPP-Blinky at IP 172.10.10.2 responds with an ACK in frame 3. One direction of the link is now established.
Frame 4 - The PC acknowledges the SYN sent by PPP-Blinky in frame 3. The TCP link is now fully established.
Frame 5 - The browser "pushes" (P flag is set) an HTTP GET request to PPP-Blinky.
Frame 6 - PPP-Blinky responds with a standard HTTP response "pushes" (P flag set) back a small web page. It also sets the A (ACK) flag to acknowledge the message sent in frame 6.
Frame 7 - The PC acknowledges reception of the HTTP payload.
Frame 8 - The PC starts to shut down the TCP connection by sending a FIN flag.
Frame 9 - PPP-Blinky acknowledges the FIN request - the connection is now closed in one direction. It also sets a FIN flag in the response to request closure of the opposite direction of the connection.
Frame 10 - The PC acknowledges the FIN request. The closing of the TCP connection is now confirmed in both directions.

/media/uploads/nixnax/ms-network-monitor-http-get-1.gif

Debug Output

PPP-Blinky can output handy debug information to an optional second serial port.
The image below shows the debug output (Ident, Source, Destination, TCP Flags) for a complete HTTP conversation.
The PC messages are displayed in black. PPP-Blinky messages are blue.
Notice how PPP-blinky automatically inserts a blank line after each full HTTP conversation.

/media/uploads/nixnax/tcp-data-3.gif

Creating a Dial-Up Connection in Linux

The screen below shows the required pppd command to connect to PPP-Blinky from a Linux machine. This was much simpler than Windows! The USB serial port of the mbed LPC1768 board registered as /dev/ttyACM0 on my Linux box. Do a websearch on pppd if you want to learn more about pppd, the Linux PPP handler. Near the bottom of the screen below, two webpages are fetched (/ and /y) by using the curl command on the command line. Gnome Webkit and Firefox work fine, too. Also try echo GET / HTTP/1.1 | nc 172.10.10.2 which uses netcat, the "Swiss army knife" of networking tools. PPP-Blinky was also tested with ApacheBench, the Apache server benchmark software. After 100000 fetches, the mean page fetch rate was reported as 6 page fetches per second for a small page.

/media/uploads/nixnax/pppd-screen.png

Caveats

PPP Blinky is an extremely sparse implementation (1.5k lines) of HTTP,WebSocket,TCP, UDP, ICMP, IPCP and LCP over PPP, requiring around 8kB of RAM. The minimum functionality required to establish connectivity is implemented. These are often acceptable tradeoffs for embedded projects as well as a handy tool to learn the practical details of everyday networking implementations.

Committer:
nixnax
Date:
Tue Aug 29 18:42:20 2017 +0000
Revision:
144:01d98cf7738e
Parent:
143:c5019f856a56
Child:
145:098b6ed2f7f2
If UDP message starts with "echo" send it back.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
nixnax 142:54d1543e23e5 1 // PPP-Blinky - "The Most Basic Internet Of a Thing"
nixnax 142:54d1543e23e5 2 // A Tiny HTTP Webserver Using Windows XP/7/8/10/Linux Dial-Up Networking Over A Serial Port.
nixnax 142:54d1543e23e5 3 // Receives UDP packets and responds to ping (ICMP Echo requests)
nixnax 142:54d1543e23e5 4 // WebSocket Service - see https://en.wikipedia.org/wiki/WebSocket
nixnax 142:54d1543e23e5 5
nixnax 142:54d1543e23e5 6 // Copyright 2016/2017 Nicolas Nackel aka Nixnax. 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.
nixnax 142:54d1543e23e5 7
nixnax 142:54d1543e23e5 8 // Notes and Instructions
nixnax 142:54d1543e23e5 9 // http://bit.ly/PPP-Blinky-Instructions
nixnax 142:54d1543e23e5 10 // http://bit.ly/win-rasdial-config
nixnax 142:54d1543e23e5 11
nixnax 142:54d1543e23e5 12 // Handy reading material
nixnax 142:54d1543e23e5 13 // https://technet.microsoft.com/en-us/library/cc957992.aspx
nixnax 142:54d1543e23e5 14 // https://en.wikibooks.org/wiki/Serial_Programming/IP_Over_Serial_Connections
nixnax 142:54d1543e23e5 15 // http://atari.kensclassics.org/wcomlog.htm
nixnax 142:54d1543e23e5 16
nixnax 142:54d1543e23e5 17 // Handy tools
nixnax 142:54d1543e23e5 18 // https://ttssh2.osdn.jp/index.html.en - Tera Term, a good terminal program to monitor the debug output from the second serial port with!
nixnax 142:54d1543e23e5 19 // https://www.microsoft.com/en-us/download/details.aspx?id=4865 - Microsoft network monitor - real-time monitoring of PPP packets
nixnax 142:54d1543e23e5 20 // http://pingtester.net/ - nice tool for high rate ping testing
nixnax 142:54d1543e23e5 21 // http://www.sunshine2k.de/coding/javascript/crc/crc_js.html - Correctly calculates the 16-bit FCS (crc) on our frames (Choose CRC16_CCITT_FALSE), then custom relected-in=1, reflected-out=1
nixnax 142:54d1543e23e5 22 // https://technet.microsoft.com/en-us/sysinternals/pstools.aspx - psping for fast testing of ICMP ping function
nixnax 142:54d1543e23e5 23 // https://eternallybored.org/misc/netcat/ - use netcat -u 172.10.10.1 80 to send/receive UDP packets from PPP-Blinky
nixnax 142:54d1543e23e5 24 // Windows Powershell invoke-webrequest command - use it to stress test the webserver like this: while (1){ invoke-webrequest -uri 172.10.10.1/x }
nixnax 142:54d1543e23e5 25
nixnax 142:54d1543e23e5 26 // Connecting PPP-Blinky to Linux
nixnax 142:54d1543e23e5 27 // PPP-Blinky can be made to talk to Linux - tested on Fedora - the following command, which uses pppd, works:
nixnax 142:54d1543e23e5 28 // pppd /dev/ttyACM0 115200 debug dump local passive noccp novj nodetach nocrtscts 172.10.10.1:172.10.10.2
nixnax 142:54d1543e23e5 29 // in the above command 172.10.10.1 is the adapter IP, and 172.10.10.2 is the IP of PPP-Blinky.
nixnax 142:54d1543e23e5 30 // See also https://en.wikipedia.org/wiki/Point-to-Point_Protocol_daemon
nixnax 142:54d1543e23e5 31
nixnax 142:54d1543e23e5 32 // Special pages when PPP-Blinky is running
nixnax 142:54d1543e23e5 33 // 172.10.10.2 root page
nixnax 143:c5019f856a56 34 // 172.10.10.2/x returns a number that increments every time you request a page - this is handy for testing
nixnax 142:54d1543e23e5 35 // 172.10.10.2/xb also returns a number, but issues a fast refresh command. This allows you to use your browser to benchmark page load speed
nixnax 142:54d1543e23e5 36 // 172.10.10.2/ws a simple WebSocket demo
nixnax 142:54d1543e23e5 37 // http://jsfiddle.net/d26cyuh2/ more complete WebSocket demo in JSFiddle
nixnax 142:54d1543e23e5 38
nixnax 142:54d1543e23e5 39 // Ok, enough talking, time to check out some code!!
nixnax 142:54d1543e23e5 40
nixnax 142:54d1543e23e5 41 #include "ppp-blinky.h"
nixnax 142:54d1543e23e5 42
nixnax 142:54d1543e23e5 43 // The #define below enables/disables a second (OPTIONAL) serial port that prints out interesting diagnostic messages.
nixnax 142:54d1543e23e5 44 // Change to SERIAL_PORT_MONITOR_YES to enable diagnostics messages. You need to wire a second serial port to your mbed hardware to monitor this.
nixnax 142:54d1543e23e5 45 // Using the second serial port will slow down packet response time
nixnax 142:54d1543e23e5 46 // Note - the LPC11U24 does NOT have a second serial port
nixnax 142:54d1543e23e5 47 #define SERIAL_PORT_MONITOR_NO /* change to SERIAL_PORT_MONITOR_YES for debug messages */
nixnax 142:54d1543e23e5 48
nixnax 142:54d1543e23e5 49 // here we define the OPTIONAL, second debug serial port for various mbed target boards
nixnax 142:54d1543e23e5 50 #ifdef SERIAL_PORT_MONITOR_YES
nixnax 142:54d1543e23e5 51 #if defined(TARGET_LPC1768)
nixnax 142:54d1543e23e5 52 Serial xx(p9, p10); // Second serial port on LPC1768 - not required to run, if you get compile error here, change #define SERIAL_PORT_MONITOR_YES to #define SERIAL_PORT_MONITOR_NO
nixnax 142:54d1543e23e5 53 #elif defined(TARGET_NUCLEO_F446RE) || defined(TARGET_NUCLEO_L152RE) || defined(TARGET_NUCLEO_L053R8) || defined(TARGET_NUCLEO_L476RG) || defined(TARGET_NUCLEO_F401RE)
nixnax 142:54d1543e23e5 54 Serial xx(PC_10, PC_11); // Second serial port on NUCLEO boards - not required to run, if you get compile error here, change #define SERIAL_PORT_MONITOR_YES to #define SERIAL_PORT_MONITOR_NO
nixnax 142:54d1543e23e5 55 #elif defined(TARGET_LPC11U24)
nixnax 142:54d1543e23e5 56 #error The LPC11U24 does not have a second serial port to use for debugging - change SERIAL_PORT_MONITOR_YES back to SERIAL_PORT_MONITOR_NO
nixnax 142:54d1543e23e5 57 #elif defined (TARGET_KL46Z) || (TARGET_KL25Z)
nixnax 142:54d1543e23e5 58 Serial xx(PTE0,PTE1); // Second serial port on FRDM-KL46Z board
nixnax 142:54d1543e23e5 59 #elif defined(YOUR_TARGET_BOARD_NAME_HERE)
nixnax 142:54d1543e23e5 60 // change the next line to YOUR target board's second serial port pin definition if it's not present - and if it works, please send it to me - thanks!!!
nixnax 142:54d1543e23e5 61 Serial xx(p9, p10); // change this to YOUR board second serial port pin definition - and please send it to me if it works!!!
nixnax 142:54d1543e23e5 62 #else
nixnax 142:54d1543e23e5 63 #error Add your target board's second serial port here if you want to use debugging - or simply change SERIAL_PORT_MONITOR_YES to SERIAL_PORT_MONITOR_NO
nixnax 142:54d1543e23e5 64 #endif
nixnax 142:54d1543e23e5 65 #define debugPrintf(x...) xx.printf (x) /* if we have a serial port we print debug messages */
nixnax 142:54d1543e23e5 66 #define debugPutc(x...) xx.putc(x)
nixnax 142:54d1543e23e5 67 #define debugBaudRate(x...) xx.baud(x)
nixnax 142:54d1543e23e5 68 #else
nixnax 142:54d1543e23e5 69 // if we don't have a debug port the debug print functions do nothing
nixnax 142:54d1543e23e5 70 #define debugPrintf(x...) {}
nixnax 142:54d1543e23e5 71 #define debugPutc(x...) {}
nixnax 142:54d1543e23e5 72 #define debugBaudRate(x...) {}
nixnax 142:54d1543e23e5 73 #endif
nixnax 142:54d1543e23e5 74
nixnax 142:54d1543e23e5 75 // verbosity flags used in debug printouts - change to 1 to see increasingly more detailed debug info.
nixnax 142:54d1543e23e5 76 #define v0 1
nixnax 142:54d1543e23e5 77 #define v1 0
nixnax 142:54d1543e23e5 78 #define v2 0
nixnax 142:54d1543e23e5 79 #define IP_HEADER_DUMP_YES /* YES for ip header dump */
nixnax 142:54d1543e23e5 80 #define TCP_HEADER_DUMP_YES /* YES for tcp header dump */
nixnax 142:54d1543e23e5 81
nixnax 142:54d1543e23e5 82 // this is the webpage we serve when we get an HTTP request to root (/)
nixnax 142:54d1543e23e5 83 // keep size under ~900 bytes to fit into a single PPP packet
nixnax 142:54d1543e23e5 84
nixnax 142:54d1543e23e5 85 const static char rootWebPage[] = "\
nixnax 142:54d1543e23e5 86 <!DOCTYPE html>\
nixnax 142:54d1543e23e5 87 <html>\
nixnax 142:54d1543e23e5 88 <head>\
nixnax 142:54d1543e23e5 89 <title>mbed PPP-Blinky</title>\
nixnax 142:54d1543e23e5 90 <script>\
nixnax 142:54d1543e23e5 91 window.onload=function(){\
nixnax 142:54d1543e23e5 92 setInterval(function(){function x(){return document.getElementById('w');};\
nixnax 142:54d1543e23e5 93 x().textContent=parseInt(x().textContent)+1;},100);};\
nixnax 142:54d1543e23e5 94 </script>\
nixnax 142:54d1543e23e5 95 </head>\
nixnax 142:54d1543e23e5 96 <body style=\"font-family: sans-serif; font-size:20px; text-align:center; color:#807070\">\
nixnax 142:54d1543e23e5 97 <h1>mbed PPP-Blinky Up and Running</h1>\
nixnax 142:54d1543e23e5 98 <h1 id=\"w\">0</h1>\
nixnax 142:54d1543e23e5 99 <h1><a href=\"http://bit.ly/pppBlink2\">Source on mbed</a></h1>\
nixnax 142:54d1543e23e5 100 <h1><a href=\"/ws\">WebSocket Demo</a></h1>\
nixnax 142:54d1543e23e5 101 <h1><a href=\"/x\">Benchmark 1</a></h1>\
nixnax 142:54d1543e23e5 102 <h1><a href=\"/xb\">Benchmark 2</a></h1>\
nixnax 142:54d1543e23e5 103 <h1><a href=\"http://jsfiddle.net/d26cyuh2/\">JSFiddle Demo</a></h1>\
nixnax 142:54d1543e23e5 104 </body>\
nixnax 142:54d1543e23e5 105 </html>"; // size = 634 bytes plus 1 null byte = 635 bytes
nixnax 142:54d1543e23e5 106
nixnax 142:54d1543e23e5 107 const static char webSocketPage[] = "\
nixnax 142:54d1543e23e5 108 <!DOCTYPE html>\
nixnax 142:54d1543e23e5 109 <html>\
nixnax 142:54d1543e23e5 110 <head>\
nixnax 142:54d1543e23e5 111 <title>mbed PPP-Blinky</title>\
nixnax 142:54d1543e23e5 112 <script>\
nixnax 142:54d1543e23e5 113 window.onload=function(){\
nixnax 142:54d1543e23e5 114 var url=\"ws://172.10.10.2\";\
nixnax 142:54d1543e23e5 115 var sts=document.getElementById(\"sts\");\
nixnax 142:54d1543e23e5 116 var btn=document.getElementById(\"btn\");\
nixnax 142:54d1543e23e5 117 var ctr=0;\
nixnax 142:54d1543e23e5 118 function show(text){sts.textContent=text;}\
nixnax 142:54d1543e23e5 119 btn.onclick=function(){\
nixnax 142:54d1543e23e5 120 if(btn.textContent==\"Connect\"){\
nixnax 142:54d1543e23e5 121 x=new WebSocket(url);\
nixnax 142:54d1543e23e5 122 x.onopen=function(){\
nixnax 142:54d1543e23e5 123 show(\"Connected to : \"+url);\
nixnax 142:54d1543e23e5 124 btn.textContent=\"Send \\\"\"+ctr+\"\\\"\";\
nixnax 142:54d1543e23e5 125 };\
nixnax 142:54d1543e23e5 126 x.onclose=function(){show(\"closed\");};\
nixnax 142:54d1543e23e5 127 x.onmessage=function(msg){show(\"PPP-Blinky Sent: \\\"\"+msg.data+\"\\\"\");};\
nixnax 142:54d1543e23e5 128 } else {\
nixnax 142:54d1543e23e5 129 x.send(ctr);\
nixnax 142:54d1543e23e5 130 ctr=ctr+1;\
nixnax 142:54d1543e23e5 131 btn.textContent=\"Send \\\"\"+ctr+\"\\\"\";\
nixnax 142:54d1543e23e5 132 }\
nixnax 142:54d1543e23e5 133 };\
nixnax 142:54d1543e23e5 134 };\
nixnax 142:54d1543e23e5 135 </script>\
nixnax 142:54d1543e23e5 136 <body style=\"font-family: sans-serif; font-size:25px; color:#807070\">\
nixnax 142:54d1543e23e5 137 <h1>PPP-Blinky WebSocket Test</h1>\
nixnax 142:54d1543e23e5 138 <div id=\"sts\">Idle</div>\
nixnax 142:54d1543e23e5 139 <button id=\"btn\" style=\"font-size: 100%; margin-top: 55px; margin-bottom: 55px;\">Connect</button>\
nixnax 142:54d1543e23e5 140 <h4><a href=\"/\">PPP-Blinky home</a></h4>\
nixnax 142:54d1543e23e5 141 </body>\
nixnax 142:54d1543e23e5 142 </html>"; // size = 916 bytes + 1 null byte = 917 bytes
nixnax 142:54d1543e23e5 143
nixnax 142:54d1543e23e5 144 // The serial port on your mbed hardware. Your PC should be configured to view this port as a standard dial-up networking modem.
nixnax 142:54d1543e23e5 145 // On Windows the model type of the modem should be selected as "Communications cable between two computers"
nixnax 142:54d1543e23e5 146 // The modem baud rate should be set to 115200 baud
nixnax 142:54d1543e23e5 147 // See instructions at the top.
nixnax 142:54d1543e23e5 148 // On a typical mbed hardware platform this serial port is a USB virtual com port (VCP) and the USB serial driver is supplied by the board vendor.
nixnax 142:54d1543e23e5 149 BufferedSerial pc(USBTX, USBRX, 100); // usb virtual com port for mbed hardware
nixnax 142:54d1543e23e5 150
nixnax 142:54d1543e23e5 151 DigitalOut led1(LED1); // this led toggles when a packet is received
nixnax 142:54d1543e23e5 152
nixnax 142:54d1543e23e5 153 // the standard hdlc frame start/end character. It's the tilde character "~"
nixnax 142:54d1543e23e5 154 #define FRAME_7E (0x7e)
nixnax 142:54d1543e23e5 155
nixnax 142:54d1543e23e5 156 /// a structure to keep all our ppp globals in
nixnax 142:54d1543e23e5 157 struct pppType {
nixnax 142:54d1543e23e5 158 int online; // we hunt for a PPP connection if this is zero
nixnax 143:c5019f856a56 159 int hostIP; // ip address of host
nixnax 142:54d1543e23e5 160 int crc; // for calculating IP and TCP CRCs
nixnax 142:54d1543e23e5 161 int ledState; // state of LED1
nixnax 142:54d1543e23e5 162 int httpPageCount;
nixnax 142:54d1543e23e5 163 int firstFrame; // cleared after first frame
nixnax 142:54d1543e23e5 164 struct {
nixnax 142:54d1543e23e5 165 #define RXBUFLEN (1<<11)
nixnax 142:54d1543e23e5 166 // the serial port receive buffer and packet buffer, size is RXBUFLEN (currently 2048 bytes)
nixnax 142:54d1543e23e5 167 char buf[RXBUFLEN]; // RXBUFLEN MUST be a power of two because we use & operator for fast wrap-around in ring buffer
nixnax 142:54d1543e23e5 168 int head;
nixnax 142:54d1543e23e5 169 int tail;
nixnax 142:54d1543e23e5 170 int rtail;
nixnax 142:54d1543e23e5 171 int buflevel;
nixnax 142:54d1543e23e5 172 } rx; // serial port objects
nixnax 142:54d1543e23e5 173 struct {
nixnax 142:54d1543e23e5 174 int len; // number of bytes in buffer
nixnax 142:54d1543e23e5 175 int crc; // PPP CRC (frame check)
nixnax 142:54d1543e23e5 176 #define PPP_max_size 2500
nixnax 142:54d1543e23e5 177 // we are assuming 1000 bytes more than MTU size of 1500 - due to the PPP encoding of special bytes
nixnax 142:54d1543e23e5 178 char buf[PPP_max_size]; // send and receive buffer large enough for raw, encoded PPP/HDLC frames
nixnax 142:54d1543e23e5 179 } pkt; // ppp buffer objects
nixnax 142:54d1543e23e5 180 struct {
nixnax 142:54d1543e23e5 181 int frameStartIndex; // frame start marker
nixnax 142:54d1543e23e5 182 int frameEndIndex; // frame end marker
nixnax 142:54d1543e23e5 183 } hdlc; // hdlc frame objects
nixnax 142:54d1543e23e5 184 struct {
nixnax 142:54d1543e23e5 185 unsigned int ident; // our IP ident value (outgoing frame count)
nixnax 142:54d1543e23e5 186 } ip; // ip related object
nixnax 142:54d1543e23e5 187 };
nixnax 142:54d1543e23e5 188
nixnax 142:54d1543e23e5 189 pppType ppp; // our global - definitely not thread safe
nixnax 142:54d1543e23e5 190
nixnax 142:54d1543e23e5 191 /// Initialize the ppp structure and clear the receive buffer
nixnax 142:54d1543e23e5 192 void pppInitStruct()
nixnax 142:54d1543e23e5 193 {
nixnax 142:54d1543e23e5 194 memset( ppp.rx.buf, 0, RXBUFLEN);
nixnax 142:54d1543e23e5 195 ppp.online=0;
nixnax 142:54d1543e23e5 196 ppp.rx.tail=0;
nixnax 142:54d1543e23e5 197 ppp.rx.rtail=0;
nixnax 142:54d1543e23e5 198 ppp.rx.head=0;
nixnax 142:54d1543e23e5 199 ppp.rx.buflevel=0;
nixnax 142:54d1543e23e5 200 ppp.pkt.len=0;
nixnax 142:54d1543e23e5 201 ppp.ip.ident=10000; // easy to recognize in ip packet dumps
nixnax 142:54d1543e23e5 202 ppp.ledState=0;
nixnax 142:54d1543e23e5 203 ppp.hdlc.frameStartIndex=0;
nixnax 142:54d1543e23e5 204 ppp.httpPageCount=0;
nixnax 142:54d1543e23e5 205 ppp.firstFrame=1;
nixnax 142:54d1543e23e5 206 }
nixnax 142:54d1543e23e5 207
nixnax 142:54d1543e23e5 208 /// Toggle the LED on every second PPP packet received
nixnax 142:54d1543e23e5 209 void led1Toggle()
nixnax 142:54d1543e23e5 210 {
nixnax 142:54d1543e23e5 211 led1 = (ppp.ledState >> 1) & 1; // use second bit, in other words toggle LED only every second packet
nixnax 143:c5019f856a56 212 ppp.ledState++;
nixnax 142:54d1543e23e5 213
nixnax 142:54d1543e23e5 214 }
nixnax 142:54d1543e23e5 215
nixnax 142:54d1543e23e5 216 /// returns 1 after a connect messasge, 0 at startup or after a disconnect message
nixnax 142:54d1543e23e5 217 int connected()
nixnax 142:54d1543e23e5 218 {
nixnax 142:54d1543e23e5 219 return ppp.online;
nixnax 143:c5019f856a56 220 }
nixnax 142:54d1543e23e5 221
nixnax 143:c5019f856a56 222 /// Check for available characters from the PC and read them into our own circular serial receive buffer at ppp.rx.buf.
nixnax 143:c5019f856a56 223 /// Also, if we are offline and a 0x7e frame start character is seen, we go online immediately
nixnax 142:54d1543e23e5 224 void checkPc()
nixnax 142:54d1543e23e5 225 {
nixnax 142:54d1543e23e5 226 char ch;
nixnax 142:54d1543e23e5 227 if ( pc.readable() ) {
nixnax 142:54d1543e23e5 228 int hd = (ppp.rx.head+1)&(RXBUFLEN-1); // increment/wrap head index
nixnax 142:54d1543e23e5 229 if ( hd == ppp.rx.rtail ) {
nixnax 142:54d1543e23e5 230 debugPrintf("\nReceive buffer full\n");
nixnax 142:54d1543e23e5 231 return;
nixnax 142:54d1543e23e5 232 }
nixnax 142:54d1543e23e5 233 ch = pc.getc(); // read new character
nixnax 142:54d1543e23e5 234 ppp.rx.buf[ppp.rx.head] = ch; // insert in our receive buffer
nixnax 142:54d1543e23e5 235 if ( ppp.online == 0 ) {
nixnax 142:54d1543e23e5 236 if (ch == 0x7E) {
nixnax 142:54d1543e23e5 237 ppp.online = 1;
nixnax 142:54d1543e23e5 238 }
nixnax 142:54d1543e23e5 239 }
nixnax 142:54d1543e23e5 240 ppp.rx.head = hd; // update head pointer
nixnax 142:54d1543e23e5 241 ppp.rx.buflevel++;
nixnax 142:54d1543e23e5 242 }
nixnax 142:54d1543e23e5 243 }
nixnax 142:54d1543e23e5 244
nixnax 142:54d1543e23e5 245 /// print to debug port while checking for incoming characters
nixnax 142:54d1543e23e5 246 void putcWhileCheckingInput( char outByte )
nixnax 142:54d1543e23e5 247 {
nixnax 142:54d1543e23e5 248 #ifdef SERIAL_PORT_MONITOR_YES
nixnax 142:54d1543e23e5 249 checkPc();
nixnax 142:54d1543e23e5 250 debugPutc( outByte );
nixnax 142:54d1543e23e5 251 checkPc();
nixnax 142:54d1543e23e5 252 #endif
nixnax 142:54d1543e23e5 253 }
nixnax 142:54d1543e23e5 254
nixnax 142:54d1543e23e5 255 /// puts to debug port while checking the PPP input stream
nixnax 142:54d1543e23e5 256 void putsWhileCheckingInput( char * data )
nixnax 142:54d1543e23e5 257 {
nixnax 142:54d1543e23e5 258 #ifdef SERIAL_PORT_MONITOR_YES
nixnax 142:54d1543e23e5 259 char * nextChar = data;
nixnax 142:54d1543e23e5 260 while( *nextChar != 0 ) {
nixnax 142:54d1543e23e5 261 putcWhileCheckingInput( *nextChar ); // write one character to debug port while checking input
nixnax 142:54d1543e23e5 262 nextChar++;
nixnax 142:54d1543e23e5 263 }
nixnax 142:54d1543e23e5 264 #endif
nixnax 142:54d1543e23e5 265 }
nixnax 142:54d1543e23e5 266
nixnax 142:54d1543e23e5 267 /// a sniffer tool to assist in figuring out where in the code we are having characters in the input buffer
nixnax 142:54d1543e23e5 268 void qq()
nixnax 142:54d1543e23e5 269 {
nixnax 142:54d1543e23e5 270 if ( pc.readable() ) putsWhileCheckingInput( "Character available!\n" );
nixnax 142:54d1543e23e5 271 }
nixnax 142:54d1543e23e5 272
nixnax 142:54d1543e23e5 273 /// Initialize the PPP CRC total
nixnax 142:54d1543e23e5 274 void crcReset()
nixnax 142:54d1543e23e5 275 {
nixnax 142:54d1543e23e5 276 ppp.crc=0xffff; // crc restart
nixnax 142:54d1543e23e5 277 }
nixnax 142:54d1543e23e5 278
nixnax 142:54d1543e23e5 279 /// update the cumulative PPP CRC
nixnax 142:54d1543e23e5 280 void crcDo(int x)
nixnax 142:54d1543e23e5 281 {
nixnax 142:54d1543e23e5 282 for (int i=0; i<8; i++) {
nixnax 142:54d1543e23e5 283 ppp.crc=((ppp.crc&1)^(x&1))?(ppp.crc>>1)^0x8408:ppp.crc>>1; // crc calculator
nixnax 142:54d1543e23e5 284 x>>=1;
nixnax 142:54d1543e23e5 285 }
nixnax 142:54d1543e23e5 286 checkPc(); // handle input
nixnax 142:54d1543e23e5 287 }
nixnax 142:54d1543e23e5 288
nixnax 142:54d1543e23e5 289 /// calculate the PPP CRC on an entire block of memory
nixnax 142:54d1543e23e5 290 int crcBuf(char * buf, int size) // crc on an entire block of memory
nixnax 142:54d1543e23e5 291 {
nixnax 142:54d1543e23e5 292 crcReset();
nixnax 142:54d1543e23e5 293 for(int i=0; i<size; i++)crcDo(*buf++);
nixnax 142:54d1543e23e5 294 return ppp.crc;
nixnax 142:54d1543e23e5 295 }
nixnax 142:54d1543e23e5 296
nixnax 142:54d1543e23e5 297 /// Get one character from our received PPP buffer
nixnax 142:54d1543e23e5 298 int pc_getBuf()
nixnax 142:54d1543e23e5 299 {
nixnax 142:54d1543e23e5 300 int x = ppp.rx.buf[ ppp.rx.tail ];
nixnax 142:54d1543e23e5 301 ppp.rx.tail=(ppp.rx.tail+1)&(RXBUFLEN-1);
nixnax 142:54d1543e23e5 302 ppp.rx.buflevel--;
nixnax 142:54d1543e23e5 303 return x;
nixnax 142:54d1543e23e5 304 }
nixnax 142:54d1543e23e5 305
nixnax 142:54d1543e23e5 306 /// Dump a PPP frame to the debug serial port
nixnax 142:54d1543e23e5 307 /// Note - the hex output of dumpPPPFrame() can be imported into WireShark
nixnax 142:54d1543e23e5 308 /// Capture the frame's hex output in your terminal program and save as a text file
nixnax 142:54d1543e23e5 309 /// In WireShark, use "Import Hex File". Options are: Offset=None, Protocol=PPP.
nixnax 142:54d1543e23e5 310 void dumpPPPFrame()
nixnax 142:54d1543e23e5 311 {
nixnax 142:54d1543e23e5 312 char pbuf[30];
nixnax 142:54d1543e23e5 313 for(int i=0; i<ppp.pkt.len; i++) {
nixnax 142:54d1543e23e5 314 checkPc();
nixnax 142:54d1543e23e5 315 sprintf(pbuf, "%02x ", ppp.pkt.buf[i]);
nixnax 142:54d1543e23e5 316 checkPc();
nixnax 142:54d1543e23e5 317 putsWhileCheckingInput(pbuf);
nixnax 142:54d1543e23e5 318 }
nixnax 142:54d1543e23e5 319 checkPc();
nixnax 142:54d1543e23e5 320 sprintf(pbuf, " CRC=%04x Len=%d\n", ppp.pkt.crc, ppp.pkt.len);
nixnax 142:54d1543e23e5 321 checkPc();
nixnax 142:54d1543e23e5 322 putsWhileCheckingInput(pbuf);
nixnax 142:54d1543e23e5 323 }
nixnax 142:54d1543e23e5 324
nixnax 142:54d1543e23e5 325 /// Process a received PPP frame
nixnax 142:54d1543e23e5 326 void processPPPFrame(int start, int end)
nixnax 142:54d1543e23e5 327 {
nixnax 142:54d1543e23e5 328 led1Toggle(); // change led1 state on every frame we receive
nixnax 142:54d1543e23e5 329 if(start==end) {
nixnax 142:54d1543e23e5 330 return; // empty frame
nixnax 142:54d1543e23e5 331 }
nixnax 142:54d1543e23e5 332 crcReset();
nixnax 142:54d1543e23e5 333 char * dest = ppp.pkt.buf;
nixnax 142:54d1543e23e5 334 ppp.pkt.len=0;
nixnax 142:54d1543e23e5 335 int unstuff=0;
nixnax 142:54d1543e23e5 336 int idx = start;
nixnax 142:54d1543e23e5 337 while(1) {
nixnax 142:54d1543e23e5 338 checkPc();
nixnax 142:54d1543e23e5 339 if (unstuff==0) {
nixnax 142:54d1543e23e5 340 if (ppp.rx.buf[idx]==0x7d) unstuff=1;
nixnax 142:54d1543e23e5 341 else {
nixnax 142:54d1543e23e5 342 *dest = ppp.rx.buf[idx];
nixnax 142:54d1543e23e5 343 ppp.pkt.len++;
nixnax 142:54d1543e23e5 344 dest++;
nixnax 142:54d1543e23e5 345 crcDo(ppp.rx.buf[idx]);
nixnax 142:54d1543e23e5 346 }
nixnax 142:54d1543e23e5 347 } else { // unstuff characters prefixed with 0x7d
nixnax 142:54d1543e23e5 348 *dest = ppp.rx.buf[idx]^0x20;
nixnax 142:54d1543e23e5 349 ppp.pkt.len++;
nixnax 142:54d1543e23e5 350 dest++;
nixnax 142:54d1543e23e5 351 crcDo(ppp.rx.buf[idx]^0x20);
nixnax 142:54d1543e23e5 352 unstuff=0;
nixnax 142:54d1543e23e5 353 }
nixnax 142:54d1543e23e5 354 idx = (idx+1) & (RXBUFLEN-1);
nixnax 142:54d1543e23e5 355 if (idx == end) break;
nixnax 142:54d1543e23e5 356 }
nixnax 142:54d1543e23e5 357 ppp.pkt.crc = ppp.crc & 0xffff;
nixnax 142:54d1543e23e5 358 if(0) dumpPPPFrame(); // set to 1 to dump ALL ppp frames
nixnax 142:54d1543e23e5 359 if (ppp.pkt.crc == 0xf0b8) { // check for good CRC
nixnax 142:54d1543e23e5 360 determinePacketType();
nixnax 142:54d1543e23e5 361 } else {
nixnax 142:54d1543e23e5 362 #define REPORT_FCS_ERROR_YES
nixnax 142:54d1543e23e5 363 #ifdef REPORT_FCS_ERROR_YES
nixnax 142:54d1543e23e5 364 char pbuf[50]; // local print buffer
nixnax 142:54d1543e23e5 365 checkPc();
nixnax 142:54d1543e23e5 366 sprintf(pbuf, "\nPPP FCS(crc) Error CRC=%x Length = %d\n",ppp.pkt.crc,ppp.pkt.len); // print a debug line
nixnax 142:54d1543e23e5 367 checkPc();
nixnax 142:54d1543e23e5 368 putsWhileCheckingInput( pbuf );
nixnax 142:54d1543e23e5 369 if(0) dumpPPPFrame(); // set to 1 to dump frames with errors in them
nixnax 142:54d1543e23e5 370 #endif
nixnax 142:54d1543e23e5 371 }
nixnax 142:54d1543e23e5 372 }
nixnax 142:54d1543e23e5 373
nixnax 142:54d1543e23e5 374 /// output a character to the PPP port while checking for incoming characters
nixnax 142:54d1543e23e5 375 void pcPutcWhileCheckingInput(int ch)
nixnax 142:54d1543e23e5 376 {
nixnax 142:54d1543e23e5 377 checkPc(); // check input
nixnax 142:54d1543e23e5 378 pc.putc(ch);
nixnax 142:54d1543e23e5 379 checkPc();
nixnax 142:54d1543e23e5 380 }
nixnax 142:54d1543e23e5 381
nixnax 142:54d1543e23e5 382 /// do PPP HDLC-like handling of special (flag) characters
nixnax 143:c5019f856a56 383 void hdlcPut(int ch)
nixnax 142:54d1543e23e5 384 {
nixnax 142:54d1543e23e5 385 if ( (ch<0x20) || (ch==0x7d) || (ch==0x7e) ) {
nixnax 142:54d1543e23e5 386 pcPutcWhileCheckingInput(0x7d);
nixnax 142:54d1543e23e5 387 pcPutcWhileCheckingInput(ch^0x20); // these characters need special handling
nixnax 142:54d1543e23e5 388 } else {
nixnax 142:54d1543e23e5 389 pcPutcWhileCheckingInput(ch);
nixnax 142:54d1543e23e5 390 }
nixnax 142:54d1543e23e5 391 }
nixnax 142:54d1543e23e5 392
nixnax 142:54d1543e23e5 393 /// send a PPP frame in HDLC format
nixnax 144:01d98cf7738e 394 void sendPppFrame()
nixnax 143:c5019f856a56 395 {
nixnax 142:54d1543e23e5 396 int crc = crcBuf(ppp.pkt.buf, ppp.pkt.len-2); // update crc
nixnax 142:54d1543e23e5 397 ppp.pkt.buf[ ppp.pkt.len-2 ] = (~crc>>0); // fcs lo (crc)
nixnax 142:54d1543e23e5 398 ppp.pkt.buf[ ppp.pkt.len-1 ] = (~crc>>8); // fcs hi (crc)
nixnax 142:54d1543e23e5 399 pcPutcWhileCheckingInput(0x7e); // hdlc start-of-frame "flag"
nixnax 142:54d1543e23e5 400 for(int i=0; i<ppp.pkt.len; i++) {
nixnax 142:54d1543e23e5 401 wait_us(86); // wait one character time
nixnax 142:54d1543e23e5 402 checkPc();
nixnax 142:54d1543e23e5 403 hdlcPut( ppp.pkt.buf[i] ); // send a character
nixnax 142:54d1543e23e5 404 }
nixnax 142:54d1543e23e5 405 pcPutcWhileCheckingInput(0x7e); // hdlc end-of-frame "flag"
nixnax 142:54d1543e23e5 406 }
nixnax 142:54d1543e23e5 407
nixnax 143:c5019f856a56 408 /// convert a network ip address in the buffer to an integer (IP adresses are big-endian, i.e most significant byte first)
nixnax 143:c5019f856a56 409 int bufferToIP(char * buffer)
nixnax 143:c5019f856a56 410 {
nixnax 143:c5019f856a56 411 int result=0;
nixnax 143:c5019f856a56 412 for(int i=0; i<4; i++) result = (result<<8)|(*buffer++ & 0xff);
nixnax 143:c5019f856a56 413 return result;
nixnax 143:c5019f856a56 414 }
nixnax 143:c5019f856a56 415
nixnax 142:54d1543e23e5 416 /// handle IPCP configuration requests
nixnax 142:54d1543e23e5 417 void ipcpConfigRequestHandler()
nixnax 142:54d1543e23e5 418 {
nixnax 142:54d1543e23e5 419 debugPrintf("Their IPCP Config Req, Our Ack\n");
nixnax 143:c5019f856a56 420 if(ppp.pkt.buf[8]==3) {
nixnax 143:c5019f856a56 421 ppp.hostIP = bufferToIP(ppp.pkt.buf+10);
nixnax 143:c5019f856a56 422 debugPrintf("Host IP = %d.%d.%d.%d (%08x)\n", ppp.pkt.buf[10],ppp.pkt.buf[11],ppp.pkt.buf[12],ppp.pkt.buf[13],ppp.hostIP);
nixnax 143:c5019f856a56 423 }
nixnax 143:c5019f856a56 424
nixnax 142:54d1543e23e5 425 ppp.pkt.buf[4]=2; // change code to ack
nixnax 144:01d98cf7738e 426 sendPppFrame(); // acknowledge everything they ask for - assume it's IP addresses
nixnax 142:54d1543e23e5 427
nixnax 142:54d1543e23e5 428 debugPrintf("Our IPCP Ask (no options)\n");
nixnax 142:54d1543e23e5 429 ppp.pkt.buf[4]=1; // change code to request
nixnax 142:54d1543e23e5 430 ppp.pkt.buf[7]=4; // no options in this request
nixnax 142:54d1543e23e5 431 ppp.pkt.len=10; // no options in this request shortest ipcp packet possible (4 ppp + 4 ipcp + 2 crc)
nixnax 144:01d98cf7738e 432 sendPppFrame(); // send our request
nixnax 142:54d1543e23e5 433 }
nixnax 142:54d1543e23e5 434
nixnax 142:54d1543e23e5 435 /// handle IPCP acknowledge (do nothing)
nixnax 142:54d1543e23e5 436 void ipcpAckHandler()
nixnax 142:54d1543e23e5 437 {
nixnax 142:54d1543e23e5 438 debugPrintf("Their IPCP Grant\n");
nixnax 142:54d1543e23e5 439 }
nixnax 142:54d1543e23e5 440
nixnax 143:c5019f856a56 441 /// Handle IPCP NACK by sending our suggested IP address if there is an IP involved.
nixnax 143:c5019f856a56 442 /// This is how Linux responds to an IPCP request with no options - Windows assumes any IP address on the submnet is OK.
nixnax 142:54d1543e23e5 443 void ipcpNackHandler()
nixnax 142:54d1543e23e5 444 {
nixnax 143:c5019f856a56 445 debugPrintf("Their IPCP Nack");
nixnax 142:54d1543e23e5 446 if (ppp.pkt.buf[8]==3) { // check if the NACK contains an IP address parameter
nixnax 142:54d1543e23e5 447 ppp.pkt.buf[4]=1; // assume the NACK contains our "suggested" IP address
nixnax 144:01d98cf7738e 448 sendPppFrame(); // let's request this IP address as ours
nixnax 143:c5019f856a56 449 debugPrintf("Our IPCP ACK (received an IP)\n");
nixnax 142:54d1543e23e5 450 } // if it's not an IP nack we ignore it
nixnax 142:54d1543e23e5 451 }
nixnax 142:54d1543e23e5 452
nixnax 142:54d1543e23e5 453 /// handle all other IPCP requests (by ignoring them)
nixnax 142:54d1543e23e5 454 void ipcpDefaultHandler()
nixnax 142:54d1543e23e5 455 {
nixnax 142:54d1543e23e5 456 debugPrintf("Their IPCP Other\n");
nixnax 142:54d1543e23e5 457 }
nixnax 142:54d1543e23e5 458
nixnax 142:54d1543e23e5 459 /// process an incoming IPCP packet
nixnax 142:54d1543e23e5 460 void IPCPframe()
nixnax 142:54d1543e23e5 461 {
nixnax 142:54d1543e23e5 462 int code = ppp.pkt.buf[4]; // packet type is here
nixnax 142:54d1543e23e5 463 switch (code) {
nixnax 142:54d1543e23e5 464 case 1:
nixnax 142:54d1543e23e5 465 ipcpConfigRequestHandler();
nixnax 142:54d1543e23e5 466 break;
nixnax 142:54d1543e23e5 467 case 2:
nixnax 142:54d1543e23e5 468 ipcpAckHandler();
nixnax 142:54d1543e23e5 469 break;
nixnax 142:54d1543e23e5 470 case 3:
nixnax 142:54d1543e23e5 471 ipcpNackHandler();
nixnax 142:54d1543e23e5 472 break;
nixnax 142:54d1543e23e5 473 default:
nixnax 142:54d1543e23e5 474 ipcpDefaultHandler();
nixnax 142:54d1543e23e5 475 }
nixnax 142:54d1543e23e5 476 }
nixnax 142:54d1543e23e5 477
nixnax 142:54d1543e23e5 478 /// process an incoming UDP packet
nixnax 142:54d1543e23e5 479 void UDPpacket()
nixnax 142:54d1543e23e5 480 {
nixnax 142:54d1543e23e5 481 char * udpPkt = ppp.pkt.buf+4; // udp packet start
nixnax 142:54d1543e23e5 482 int headerSizeIP = (( udpPkt[0]&0xf)*4);
nixnax 142:54d1543e23e5 483 char * udpBlock = udpPkt + headerSizeIP; // udp info start
nixnax 143:c5019f856a56 484 char * udpInf = udpBlock+8; // actual start of info
nixnax 142:54d1543e23e5 485 char * udpSrc = udpBlock; // source port
nixnax 142:54d1543e23e5 486 char * udpDst = udpBlock+2; // destination port
nixnax 142:54d1543e23e5 487 char * udpLen = udpBlock+4; // udp data length
nixnax 144:01d98cf7738e 488 char * udpCks = udpBlock+6; // udp checksum
nixnax 143:c5019f856a56 489 char * srcIP = udpPkt+12; // udp src addr
nixnax 143:c5019f856a56 490 char * dstIP = udpPkt+16; // udp dst addr
nixnax 144:01d98cf7738e 491 if (udpLen); // shut up compiler warning for unused udpLen
nixnax 144:01d98cf7738e 492 #ifdef SERIAL_PORT_MONITOR_YES
nixnax 142:54d1543e23e5 493 int srcPort = (udpSrc[0]<<8) | udpSrc[1];
nixnax 142:54d1543e23e5 494 int dstPort = (udpDst[0]<<8) | udpDst[1];
nixnax 143:c5019f856a56 495 int udpLength = ((udpLen[0]<<8) | udpLen[1]) - 8; // size of the actual udp data
nixnax 142:54d1543e23e5 496 if(v0) debugPrintf("UDP %d.%d.%d.%d:%d ", srcIP[0],srcIP[1],srcIP[2],srcIP[3],srcPort);
nixnax 142:54d1543e23e5 497 if(v0) debugPrintf("%d.%d.%d.%d:%d ", dstIP[0],dstIP[1],dstIP[2],dstIP[3],dstPort);
nixnax 142:54d1543e23e5 498 if(v0) debugPrintf("Len %03d", udpLength);
nixnax 142:54d1543e23e5 499 if (v1) {
nixnax 143:c5019f856a56 500 int printSize = udpLength;
nixnax 143:c5019f856a56 501 if (printSize > 20) printSize = 20; // print only first 20 characters
nixnax 142:54d1543e23e5 502 for (int i=0; i<printSize; i++) {
nixnax 142:54d1543e23e5 503 char ch = udpInf[i];
nixnax 142:54d1543e23e5 504 if (ch>31 && ch<127) {
nixnax 142:54d1543e23e5 505 debugPrintf("%c", ch);
nixnax 142:54d1543e23e5 506 } else {
nixnax 142:54d1543e23e5 507 debugPrintf("_");
nixnax 142:54d1543e23e5 508 }
nixnax 142:54d1543e23e5 509 }
nixnax 142:54d1543e23e5 510 }
nixnax 142:54d1543e23e5 511 if (v0) debugPrintf("\n");
nixnax 143:c5019f856a56 512 #endif
nixnax 144:01d98cf7738e 513 if (strncmp(udpInf,"echo", 4)==0) { // if the UDP string starts with "echo" we echo it back
nixnax 144:01d98cf7738e 514 char tempHold[12]; // it's 12 long because we later reuse it when building the TCP pseudo-header
nixnax 144:01d98cf7738e 515 memcpy(tempHold, srcIP,4);
nixnax 144:01d98cf7738e 516 memcpy(srcIP, dstIP,4);
nixnax 144:01d98cf7738e 517 memcpy(dstIP, tempHold,4); // swap ip address source/dest
nixnax 144:01d98cf7738e 518 memcpy(tempHold, udpSrc,2);
nixnax 144:01d98cf7738e 519 memcpy(udpSrc, udpDst,2);
nixnax 144:01d98cf7738e 520 memcpy(udpDst, tempHold,2); // swap udp port source/dest
nixnax 144:01d98cf7738e 521 memcpy(udpInf,"Got:",4);
nixnax 144:01d98cf7738e 522 memset(udpCks,0,2); // we don't compute the checksum (it's optional), so have to zero it
nixnax 144:01d98cf7738e 523 sendPppFrame();
nixnax 144:01d98cf7738e 524 }
nixnax 142:54d1543e23e5 525 }
nixnax 142:54d1543e23e5 526
nixnax 142:54d1543e23e5 527 /// perform a 16-bit checksum. if the byte count is odd, stuff in an extra zero byte.
nixnax 142:54d1543e23e5 528 unsigned int dataCheckSum(unsigned char * ptr, int len)
nixnax 142:54d1543e23e5 529 {
nixnax 142:54d1543e23e5 530 unsigned int i,hi,lo,sum;
nixnax 142:54d1543e23e5 531 unsigned char placeHolder;
nixnax 142:54d1543e23e5 532 if (len&1) {
nixnax 142:54d1543e23e5 533 placeHolder = ptr[len];
nixnax 142:54d1543e23e5 534 ptr[len]=0; // if the byte count is odd, insert one extra zero byte is after the last real byte because we sum byte PAIRS
nixnax 142:54d1543e23e5 535 }
nixnax 142:54d1543e23e5 536 sum=0;
nixnax 142:54d1543e23e5 537 i=0;
nixnax 142:54d1543e23e5 538 while ( i<len ) {
nixnax 142:54d1543e23e5 539 checkPc();
nixnax 142:54d1543e23e5 540 hi = ptr[i++];
nixnax 142:54d1543e23e5 541 lo = ptr[i++];
nixnax 142:54d1543e23e5 542 sum = sum + ( (hi<<8) | lo );
nixnax 142:54d1543e23e5 543 }
nixnax 142:54d1543e23e5 544 if (len&1) {
nixnax 142:54d1543e23e5 545 ptr[len] = placeHolder; // restore the extra byte we made zero
nixnax 142:54d1543e23e5 546 }
nixnax 142:54d1543e23e5 547 sum = (sum & 0xffff) + (sum>>16);
nixnax 142:54d1543e23e5 548 sum = (sum & 0xffff) + (sum>>16); // sum one more time to catch any carry from the carry
nixnax 142:54d1543e23e5 549 return ~sum;
nixnax 142:54d1543e23e5 550 }
nixnax 142:54d1543e23e5 551
nixnax 142:54d1543e23e5 552 /// perform the checksum on an IP header
nixnax 142:54d1543e23e5 553 void headerCheckSum()
nixnax 142:54d1543e23e5 554 {
nixnax 142:54d1543e23e5 555 int len =(ppp.pkt.buf[4]&0xf)*4; // length of header in bytes
nixnax 142:54d1543e23e5 556 char * ptr = ppp.pkt.buf+4; // start of ip packet
nixnax 142:54d1543e23e5 557 int sum=0;
nixnax 142:54d1543e23e5 558
nixnax 142:54d1543e23e5 559 for (int i=0; i<len/2; i++) {
nixnax 142:54d1543e23e5 560 int hi = *ptr;
nixnax 142:54d1543e23e5 561 ptr++;
nixnax 142:54d1543e23e5 562 int lo = *ptr;
nixnax 142:54d1543e23e5 563 ptr++;
nixnax 142:54d1543e23e5 564 int val = ( lo & 0xff ) | ( (hi<<8) & 0xff00 );
nixnax 142:54d1543e23e5 565 sum = sum + val;
nixnax 142:54d1543e23e5 566 checkPc();
nixnax 142:54d1543e23e5 567 }
nixnax 142:54d1543e23e5 568 sum = sum + (sum>>16);
nixnax 142:54d1543e23e5 569 sum = ~sum;
nixnax 142:54d1543e23e5 570 ppp.pkt.buf[14]= (sum>>8);
nixnax 142:54d1543e23e5 571 ppp.pkt.buf[15]= (sum );
nixnax 142:54d1543e23e5 572 }
nixnax 142:54d1543e23e5 573
nixnax 142:54d1543e23e5 574 /// handle a PING ICMP (internet control message protocol) packet
nixnax 142:54d1543e23e5 575 void ICMPpacket() // internet control message protocol
nixnax 142:54d1543e23e5 576 {
nixnax 142:54d1543e23e5 577 char * ipPkt = ppp.pkt.buf+4; // ip packet start
nixnax 142:54d1543e23e5 578 char * pktLen = ipPkt+2;
nixnax 142:54d1543e23e5 579 int packetLength = (pktLen[0]<<8) | pktLen[1]; // icmp packet length
nixnax 142:54d1543e23e5 580 int headerSizeIP = (( ipPkt[0]&0xf)*4);
nixnax 142:54d1543e23e5 581 char * icmpType = ipPkt + headerSizeIP; // icmp data start
nixnax 142:54d1543e23e5 582 char * icmpSum = icmpType+2; // icmp checksum
nixnax 142:54d1543e23e5 583 #define ICMP_TYPE_PING_REQUEST 8
nixnax 142:54d1543e23e5 584 if ( icmpType[0] == ICMP_TYPE_PING_REQUEST ) {
nixnax 142:54d1543e23e5 585 char * ipTTL = ipPkt+8; // time to live
nixnax 142:54d1543e23e5 586 ipTTL[0]--; // decrement time to live
nixnax 142:54d1543e23e5 587 char * srcAdr = ipPkt+12;
nixnax 142:54d1543e23e5 588 char * dstAdr = ipPkt+16;
nixnax 142:54d1543e23e5 589 #ifdef SERIAL_PORT_MONITOR_YES
nixnax 142:54d1543e23e5 590 int icmpIdent = (icmpType[4]<<8)|icmpType[5];
nixnax 142:54d1543e23e5 591 int icmpSequence = (icmpType[6]<<8)|icmpType[7];
nixnax 142:54d1543e23e5 592 if(1) {
nixnax 142:54d1543e23e5 593 char pbuf[50];
nixnax 142:54d1543e23e5 594 checkPc();
nixnax 142:54d1543e23e5 595 sprintf(pbuf, "ICMP PING %d.%d.%d.%d %d.%d.%d.%d ", srcAdr[0],srcAdr[1],srcAdr[2],srcAdr[3],dstAdr[0],dstAdr[1],dstAdr[2],dstAdr[3]);
nixnax 142:54d1543e23e5 596 putsWhileCheckingInput( pbuf );
nixnax 142:54d1543e23e5 597 checkPc();
nixnax 142:54d1543e23e5 598 sprintf(pbuf, "Ident %04x Sequence %04d \n",icmpIdent,icmpSequence);
nixnax 142:54d1543e23e5 599 checkPc();
nixnax 142:54d1543e23e5 600 putsWhileCheckingInput( pbuf );
nixnax 142:54d1543e23e5 601 }
nixnax 142:54d1543e23e5 602 #endif
nixnax 142:54d1543e23e5 603 char src[4];
nixnax 142:54d1543e23e5 604 char dst[4];
nixnax 142:54d1543e23e5 605 memcpy(src, srcAdr,4);
nixnax 142:54d1543e23e5 606 memcpy(dst, dstAdr,4);
nixnax 142:54d1543e23e5 607 memcpy(srcAdr, dst,4);
nixnax 142:54d1543e23e5 608 memcpy(dstAdr, src,4); // swap src & dest ip
nixnax 142:54d1543e23e5 609 char * chkSum = ipPkt+10;
nixnax 142:54d1543e23e5 610 chkSum[0]=0;
nixnax 142:54d1543e23e5 611 chkSum[1]=0;
nixnax 142:54d1543e23e5 612 headerCheckSum(); // new ip header checksum
nixnax 142:54d1543e23e5 613 #define ICMP_TYPE_ECHO_REPLY 0
nixnax 142:54d1543e23e5 614 icmpType[0]=ICMP_TYPE_ECHO_REPLY; // icmp echo reply
nixnax 142:54d1543e23e5 615 icmpSum[0]=0;
nixnax 142:54d1543e23e5 616 icmpSum[1]=0; // zero the checksum for recalculation
nixnax 142:54d1543e23e5 617 int icmpLength = packetLength - headerSizeIP; // length of ICMP data portion
nixnax 142:54d1543e23e5 618 unsigned int sum = dataCheckSum( (unsigned char *)icmpType, icmpLength); // this checksum on icmp data portion
nixnax 142:54d1543e23e5 619 icmpSum[0]=(sum>>8)&0xff;
nixnax 142:54d1543e23e5 620 icmpSum[1]=(sum )&0xff; // new checksum for ICMP data portion
nixnax 142:54d1543e23e5 621
nixnax 142:54d1543e23e5 622 int printSize = icmpLength-8; // exclude size of icmp header
nixnax 142:54d1543e23e5 623 char * icmpData = icmpType+8; // the actual payload data is after the header
nixnax 142:54d1543e23e5 624 if (printSize > 10) printSize = 10; // print up to 20 characters
nixnax 142:54d1543e23e5 625 if (0) {
nixnax 142:54d1543e23e5 626 for (int i=0; i<printSize; i++) {
nixnax 142:54d1543e23e5 627 char ch = icmpData[i];
nixnax 142:54d1543e23e5 628 if (ch>31 && ch<127) {
nixnax 142:54d1543e23e5 629 putcWhileCheckingInput(ch);
nixnax 142:54d1543e23e5 630 } else {
nixnax 142:54d1543e23e5 631 putcWhileCheckingInput('_');
nixnax 142:54d1543e23e5 632 }
nixnax 142:54d1543e23e5 633 }
nixnax 142:54d1543e23e5 634 putcWhileCheckingInput('\n');
nixnax 142:54d1543e23e5 635 }
nixnax 144:01d98cf7738e 636 sendPppFrame(); // reply to the ping
nixnax 142:54d1543e23e5 637 } else {
nixnax 142:54d1543e23e5 638 if (v0) {
nixnax 142:54d1543e23e5 639 debugPrintf("ICMP type=%d \n", icmpType[0]);
nixnax 142:54d1543e23e5 640 }
nixnax 142:54d1543e23e5 641 }
nixnax 142:54d1543e23e5 642 }
nixnax 142:54d1543e23e5 643
nixnax 142:54d1543e23e5 644 /// handle an IGMP (internet group managment protocol) packet (by ignoring it)
nixnax 142:54d1543e23e5 645 void IGMPpacket()
nixnax 142:54d1543e23e5 646 {
nixnax 142:54d1543e23e5 647 if (v0) debugPrintf("IGMP type=%d \n", ppp.pkt.buf[28]);
nixnax 142:54d1543e23e5 648 }
nixnax 142:54d1543e23e5 649
nixnax 142:54d1543e23e5 650 /// dump the header of an IP pakcet on the (optional) debug serial port
nixnax 142:54d1543e23e5 651 void dumpHeaderIP (int outGoing)
nixnax 142:54d1543e23e5 652 {
nixnax 142:54d1543e23e5 653 #if defined(IP_HEADER_DUMP_YES) && defined(SERIAL_PORT_MONITOR_YES)
nixnax 142:54d1543e23e5 654 checkPc(); // we are expecting the first character of the next packet
nixnax 142:54d1543e23e5 655 char * ipPkt = ppp.pkt.buf+4; // ip packet start
nixnax 142:54d1543e23e5 656 char * ident = ipPkt+4; // 2 bytes
nixnax 142:54d1543e23e5 657 #ifdef UNUSED_IP_VARIABLES
nixnax 142:54d1543e23e5 658 char * srcAdr = ipPkt+12; // 4 bytes
nixnax 142:54d1543e23e5 659 char * dstAdr = ipPkt+16; // 4 bytes = total of 20 bytes
nixnax 142:54d1543e23e5 660 char * version = ipPkt; // top 4 bits
nixnax 142:54d1543e23e5 661 char * ihl = ipPkt; // bottom 4 bits
nixnax 142:54d1543e23e5 662 char * dscp = ipPkt+1; // top 6 bits
nixnax 142:54d1543e23e5 663 char * ecn = ipPkt+1; // lower 2 bits
nixnax 142:54d1543e23e5 664 char * pktLen = ipPkt+2; // 2 bytes
nixnax 142:54d1543e23e5 665 char * flags = ipPkt+6; // 2 bits
nixnax 142:54d1543e23e5 666 char * ttl = ipPkt+8; // 1 byte
nixnax 142:54d1543e23e5 667 char * protocol = ipPkt+9; // 1 byte
nixnax 142:54d1543e23e5 668 char * headercheck= ipPkt+10; // 2 bytes
nixnax 142:54d1543e23e5 669 int versionIP = (version[0]>>4)&0xf;
nixnax 142:54d1543e23e5 670 int headerSizeIP = (ihl[0]&0xf)*4;
nixnax 142:54d1543e23e5 671 int dscpIP = (dscp[0]>>2)&0x3f;
nixnax 142:54d1543e23e5 672 int ecnIP = ecn[0]&3;
nixnax 142:54d1543e23e5 673 int packetLength = (pktLen[0]<<8)|pktLen[1]; // ip total packet length
nixnax 142:54d1543e23e5 674 int flagsIP = flags[0]>>14&3;
nixnax 142:54d1543e23e5 675 int ttlIP = ttl[0];
nixnax 142:54d1543e23e5 676 int protocolIP = protocol[0];
nixnax 142:54d1543e23e5 677 unsigned int checksumIP = (headercheck[0]<<8)|headercheck[1];
nixnax 142:54d1543e23e5 678 #endif
nixnax 142:54d1543e23e5 679 int IPv4Id = (ident[0]<<8)|ident[1];
nixnax 142:54d1543e23e5 680 char pbuf[50]; // local print buffer
nixnax 142:54d1543e23e5 681 int n=0;
nixnax 142:54d1543e23e5 682 n=n+sprintf(pbuf+n, outGoing ? "\x1b[34m" : "\x1b[30m" ); // VT100 color code, print black for incoming, blue for outgoing headers
nixnax 142:54d1543e23e5 683 n=n+sprintf(pbuf+n, "%05d ",IPv4Id); // IPv4Id is a good way to correlate our dumps with net monitor or wireshark traces
nixnax 142:54d1543e23e5 684 #define DUMP_FULL_IP_ADDRESS_YES
nixnax 142:54d1543e23e5 685 #ifdef DUMP_FULL_IP_ADDRESS_YES
nixnax 142:54d1543e23e5 686 char * srcAdr = ipPkt+12; // 4 bytes
nixnax 142:54d1543e23e5 687 char * dstAdr = ipPkt+16; // 4 bytes = total of 20 bytes
nixnax 142:54d1543e23e5 688 n=n+sprintf(pbuf+n, " %d.%d.%d.%d %d.%d.%d.%d ",srcAdr[0],srcAdr[1],srcAdr[2],srcAdr[3], dstAdr[0],dstAdr[1],dstAdr[2],dstAdr[3]); // full ip addresses
nixnax 142:54d1543e23e5 689 #endif
nixnax 142:54d1543e23e5 690 putsWhileCheckingInput( pbuf );
nixnax 142:54d1543e23e5 691 #ifndef TCP_HEADER_DUMP_YES
nixnax 142:54d1543e23e5 692 putsWhileCheckingInput('\x1b[30m\n'); // there is no TCP header dump, so terminate the line with \n and VT100 code for black
nixnax 142:54d1543e23e5 693 #endif
nixnax 142:54d1543e23e5 694 #endif
nixnax 142:54d1543e23e5 695 }
nixnax 142:54d1543e23e5 696
nixnax 142:54d1543e23e5 697 /// dump a TCP header on the optional debug serial port
nixnax 142:54d1543e23e5 698 void dumpHeaderTCP(int outGoing)
nixnax 142:54d1543e23e5 699 {
nixnax 142:54d1543e23e5 700 #if defined(TCP_HEADER_DUMP_YES) && defined(SERIAL_PORT_MONITOR_YES)
nixnax 142:54d1543e23e5 701 int headerSizeIP = (ppp.pkt.buf[4]&0xf)*4; // header size of ip portion
nixnax 142:54d1543e23e5 702 char * tcpStart = ppp.pkt.buf+4+headerSizeIP; // start of tcp packet
nixnax 142:54d1543e23e5 703 char * seqtcp = tcpStart + 4; // 4 bytes
nixnax 142:54d1543e23e5 704 char * acktcp = tcpStart + 8; // 4 bytes
nixnax 142:54d1543e23e5 705 char * flagbitstcp = tcpStart + 12; // 9 bits
nixnax 142:54d1543e23e5 706 unsigned int seq = (seqtcp[0]<<24)|(seqtcp[1]<<16)|(seqtcp[2]<<8)|(seqtcp[3]);
nixnax 142:54d1543e23e5 707 unsigned int ack = (acktcp[0]<<24)|(acktcp[1]<<16)|(acktcp[2]<<8)|(acktcp[3]);
nixnax 142:54d1543e23e5 708 if (seq && ack) {} // shut up the compiler about unused variables
nixnax 142:54d1543e23e5 709 int flags = ((flagbitstcp[0]&1)<<8)|flagbitstcp[1];
nixnax 142:54d1543e23e5 710 char flagInfo[9]; // text string presenting the 8 most important TCP flags
nixnax 142:54d1543e23e5 711 #define PRINT_ALL_TCP_FLAGS_YES
nixnax 142:54d1543e23e5 712 #ifdef PRINT_ALL_TCP_FLAGS_YES
nixnax 142:54d1543e23e5 713 memset(flagInfo,'.', 8); // fill string with "........"
nixnax 142:54d1543e23e5 714 flagInfo[8]=0; // null terminate string
nixnax 142:54d1543e23e5 715 if (flags & (1<<0)) flagInfo[7]='F';
nixnax 142:54d1543e23e5 716 if (flags & (1<<1)) flagInfo[6]='S';
nixnax 142:54d1543e23e5 717 if (flags & (1<<2)) flagInfo[5]='R';
nixnax 142:54d1543e23e5 718 if (flags & (1<<3)) flagInfo[4]='P';
nixnax 142:54d1543e23e5 719 if (flags & (1<<4)) flagInfo[3]='A';
nixnax 142:54d1543e23e5 720 if (flags & (1<<5)) flagInfo[2]='U';
nixnax 142:54d1543e23e5 721 if (flags & (1<<6)) flagInfo[1]='E';
nixnax 142:54d1543e23e5 722 if (flags & (1<<7)) flagInfo[0]='C';
nixnax 142:54d1543e23e5 723 #else
nixnax 142:54d1543e23e5 724 if (flags & (1<<4)) flagInfo[0]='A'; // choose the most important flag to print
nixnax 142:54d1543e23e5 725 if (flags & (1<<1)) flagInfo[0]='S';
nixnax 142:54d1543e23e5 726 if (flags & (1<<0)) flagInfo[0]='F';
nixnax 142:54d1543e23e5 727 if (flags & (1<<3)) flagInfo[0]='P';
nixnax 142:54d1543e23e5 728 if (flags & (1<<2)) flagInfo[0]='R';
nixnax 142:54d1543e23e5 729 flagInfo[1]=0; // ' '
nixnax 142:54d1543e23e5 730 flagInfo[2]=0;
nixnax 142:54d1543e23e5 731 #endif
nixnax 142:54d1543e23e5 732 putsWhileCheckingInput( flagInfo );
nixnax 142:54d1543e23e5 733 #define EVERY_PACKET_ON_A_NEW_LINE_YES
nixnax 142:54d1543e23e5 734 #ifdef EVERY_PACKET_ON_A_NEW_LINE_YES
nixnax 142:54d1543e23e5 735 putsWhileCheckingInput("\x1b[30m\n"); // write a black color and newline after every packet
nixnax 142:54d1543e23e5 736 #endif
nixnax 142:54d1543e23e5 737 if( outGoing && ( flags == 0x11 ) ) { // ACK/FIN - if this is an outgoing ACK/FIN its the end of a tcp conversation
nixnax 142:54d1543e23e5 738 putcWhileCheckingInput('\n'); // insert an extra new line to mark the end of an HTTP the conversation
nixnax 142:54d1543e23e5 739 }
nixnax 142:54d1543e23e5 740 #endif
nixnax 142:54d1543e23e5 741 }
nixnax 142:54d1543e23e5 742
nixnax 143:c5019f856a56 743 /// Encode a buffer in base-64
nixnax 142:54d1543e23e5 744 void enc64(char * in, char * out, int len)
nixnax 142:54d1543e23e5 745 {
nixnax 142:54d1543e23e5 746 const static char lut [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
nixnax 142:54d1543e23e5 747 int i,j,a,b,c;
nixnax 142:54d1543e23e5 748 i=0;
nixnax 142:54d1543e23e5 749 j=0;
nixnax 142:54d1543e23e5 750 while(1) {
nixnax 142:54d1543e23e5 751 if (i<len) {
nixnax 142:54d1543e23e5 752 a = in[i++];
nixnax 142:54d1543e23e5 753 out[j++] = lut[ ( (a >> 2) & 0x3f) ];
nixnax 142:54d1543e23e5 754 } else break;
nixnax 142:54d1543e23e5 755 if (i<len) {
nixnax 142:54d1543e23e5 756 b = in[i++];
nixnax 142:54d1543e23e5 757 out[j++] = lut[ ( (a << 4) & 0x30) | ( (b >> 4) & 0x0f) ];
nixnax 142:54d1543e23e5 758 out[j++] = lut[ ( (b << 2) & 0x3c) ];
nixnax 142:54d1543e23e5 759 } else out[j++] = '=';
nixnax 142:54d1543e23e5 760 if (i<len) {
nixnax 142:54d1543e23e5 761 c = in[i++];
nixnax 142:54d1543e23e5 762 j--;
nixnax 142:54d1543e23e5 763 out[j++] = lut[ ( (b << 2) & 0x3c) | ( (c >> 6) & 0x03) ];
nixnax 142:54d1543e23e5 764 out[j++] = lut[ ( (c >> 0) & 0x3f) ];
nixnax 142:54d1543e23e5 765 } else out[j++] = '=';
nixnax 142:54d1543e23e5 766 }
nixnax 142:54d1543e23e5 767 out[j]=0;
nixnax 142:54d1543e23e5 768 }
nixnax 142:54d1543e23e5 769
nixnax 142:54d1543e23e5 770 /// handle a request for an http websocket
nixnax 142:54d1543e23e5 771 /// we end up here if we enter the following javascript in a web browser console: x = new WebSocket("ws://172.10.10.2");
nixnax 142:54d1543e23e5 772 int webSocketHandler(char * dataStart)
nixnax 142:54d1543e23e5 773 {
nixnax 142:54d1543e23e5 774 int n=0; // byte counter
nixnax 142:54d1543e23e5 775 char * key = strstr(dataStart, "Sec-WebSocket-Key: "); // search for the key in the payload
nixnax 142:54d1543e23e5 776 if (key != NULL) {
nixnax 142:54d1543e23e5 777 if (v0) putsWhileCheckingInput("WebSocket Request\n");
nixnax 142:54d1543e23e5 778 char challenge [70];
nixnax 142:54d1543e23e5 779 strncpy(challenge,key+19,70); // a local buffer
nixnax 142:54d1543e23e5 780 *strchr(challenge,'\r')=0; // insert null so we can use sprintf
nixnax 142:54d1543e23e5 781 strncat(challenge,"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",70); // append websocket gui code
nixnax 142:54d1543e23e5 782 char shaOutput [20]; // sha1 output
nixnax 142:54d1543e23e5 783 sha1( shaOutput, challenge, strlen(challenge));
nixnax 142:54d1543e23e5 784 char encOut[50];
nixnax 142:54d1543e23e5 785 enc64( shaOutput, encOut, 20);
nixnax 142:54d1543e23e5 786 char * versionstring = strstr(dataStart, "Sec-WebSocket-Version:");
nixnax 142:54d1543e23e5 787 char * version = challenge;
nixnax 142:54d1543e23e5 788 strncpy(version, versionstring,70); // copy version string
nixnax 142:54d1543e23e5 789 *strchr(version,'\r')=0; // null terminate so we can sprintf it
nixnax 142:54d1543e23e5 790 memset(dataStart,0,500); // blank out old data befor send the websocket response header
nixnax 142:54d1543e23e5 791 n=n+sprintf(dataStart+n, "HTTP/1.1 101 Switching Protocols\r\n");
nixnax 142:54d1543e23e5 792 n=n+sprintf(dataStart+n, "Upgrade: websocket\r\n");
nixnax 142:54d1543e23e5 793 n=n+sprintf(dataStart+n, "Connection: Upgrade\r\n");
nixnax 142:54d1543e23e5 794 n=n+sprintf(dataStart+n, "Sec-WebSocket-Accept: %s\r\n",encOut);
nixnax 142:54d1543e23e5 795 n=n+sprintf(dataStart+n, "%s\r\n",version);
nixnax 142:54d1543e23e5 796 n=n+sprintf(dataStart+n, "mbed-Code: PPP-Blinky\r\n");
nixnax 142:54d1543e23e5 797 n=n+sprintf(dataStart+n, "\r\n"); // websocket response header ending
nixnax 142:54d1543e23e5 798 }
nixnax 142:54d1543e23e5 799 return n; // this response should satisfy a web browser's websocket protocol request
nixnax 142:54d1543e23e5 800 }
nixnax 142:54d1543e23e5 801
nixnax 142:54d1543e23e5 802 #define TCP_FLAG_ACK (1<<4)
nixnax 142:54d1543e23e5 803 #define TCP_FLAG_SYN (1<<1)
nixnax 142:54d1543e23e5 804 #define TCP_FLAG_PSH (1<<3)
nixnax 142:54d1543e23e5 805 #define TCP_FLAG_RST (1<<2)
nixnax 142:54d1543e23e5 806 #define TCP_FLAG_FIN (1<<0)
nixnax 142:54d1543e23e5 807
nixnax 142:54d1543e23e5 808 /// respond to an HTTP request
nixnax 142:54d1543e23e5 809 int httpResponse(char * dataStart)
nixnax 142:54d1543e23e5 810 {
nixnax 142:54d1543e23e5 811 int n=0; // number of bytes we have printed so far
nixnax 142:54d1543e23e5 812 n = webSocketHandler( dataStart ); // test for and handle WebSocket upgrade requests
nixnax 142:54d1543e23e5 813 if (n>0) return n; // if it's a WebSocket we already have the response, so return
nixnax 142:54d1543e23e5 814
nixnax 142:54d1543e23e5 815 int nHeader; // byte size of HTTP header
nixnax 142:54d1543e23e5 816 int contentLengthStart; // index where HTML starts
nixnax 142:54d1543e23e5 817 int httpGet5,httpGet6,httpGetx, httpGetRoot; // temporary storage of strncmp results
nixnax 142:54d1543e23e5 818
nixnax 142:54d1543e23e5 819 ppp.httpPageCount++; // increment the number of frames we have made
nixnax 142:54d1543e23e5 820
nixnax 142:54d1543e23e5 821 httpGetRoot = strncmp(dataStart, "GET / HTTP/1.", 13); // found a GET to the root directory
nixnax 142:54d1543e23e5 822 httpGetx = strncmp(dataStart, "GET /x", 6); // found a GET to /x which we will treat special (anything starting with /x, e.g. /x, /xyz, /xABC?pqr=123
nixnax 142:54d1543e23e5 823 httpGet5 = dataStart[5]; // the first character in the path name, we use it for special functions later on
nixnax 142:54d1543e23e5 824 httpGet6 = dataStart[6]; // the second character in the path name, we use it for special functions later on
nixnax 142:54d1543e23e5 825 // for example, you could try this using netcat (nc): echo "GET /x" | nc 172.10.10.2
nixnax 142:54d1543e23e5 826 if( (httpGetRoot==0) || (httpGetx==0) ) {
nixnax 142:54d1543e23e5 827 n=n+sprintf(n+dataStart,"HTTP/1.1 200 OK\r\nServer: mbed-PPP-Blinky-v1\r\n"); // 200 OK header
nixnax 142:54d1543e23e5 828 } else {
nixnax 142:54d1543e23e5 829 n=n+sprintf(n+dataStart,"HTTP/1.1 404 Not Found\r\nServer: mbed-PPP-Blinky\r\n"); // 404 header
nixnax 142:54d1543e23e5 830 }
nixnax 142:54d1543e23e5 831 n=n+sprintf(n+dataStart,"Content-Length: "); // http header
nixnax 142:54d1543e23e5 832 contentLengthStart = n; // remember where Content-Length is in buffer
nixnax 142:54d1543e23e5 833 n=n+sprintf(n+dataStart,"?????\r\n"); // leave five spaces for content length - will be updated later
nixnax 142:54d1543e23e5 834 n=n+sprintf(n+dataStart,"Connection: close\r\n"); // close connection immediately
nixnax 142:54d1543e23e5 835 n=n+sprintf(n+dataStart,"Content-Type: text/html; charset=us-ascii\r\n\r\n"); // http header must end with empty line (\r\n)
nixnax 142:54d1543e23e5 836 nHeader=n; // size of HTTP header
nixnax 142:54d1543e23e5 837 if( httpGetRoot == 0 ) {
nixnax 142:54d1543e23e5 838 // this is where we insert our web page into the buffer
nixnax 142:54d1543e23e5 839 memcpy(n+dataStart,rootWebPage,sizeof(rootWebPage));
nixnax 142:54d1543e23e5 840 n = n + sizeof(rootWebPage)-1; // one less than sizeof because we don't count the null byte at the end
nixnax 142:54d1543e23e5 841 } else if ( (httpGet5 == 'w') && (httpGet6 == 's') ) { // "ws" is a special page for websocket demo
nixnax 142:54d1543e23e5 842 memcpy(n+dataStart,webSocketPage,sizeof(webSocketPage));
nixnax 142:54d1543e23e5 843 n = n + sizeof(webSocketPage)-1; // one less than size
nixnax 142:54d1543e23e5 844 } else {
nixnax 142:54d1543e23e5 845 if (httpGetx == 0) { // the page request started with "GET /x" - here we treat anything starting with /x special:
nixnax 142:54d1543e23e5 846
nixnax 142:54d1543e23e5 847 #define W3C_COMPLIANT_RESPONSE_NO
nixnax 142:54d1543e23e5 848 // change the above to W3C_COMPLIANT_RESPONSE_YES if you want a W3C.org compliant HTTP response
nixnax 142:54d1543e23e5 849 #ifdef W3C_COMPLIANT_RESPONSE_YES
nixnax 142:54d1543e23e5 850 n=n+sprintf(n+dataStart,"<!DOCTYPE html><title>mbed PPP-Blinky</title>"); // html title (W3C.org required elements)
nixnax 142:54d1543e23e5 851 n=n+sprintf(n+dataStart,"<body>%d</body>",ppp.httpPageCount); // body = the http frame count
nixnax 142:54d1543e23e5 852 #else
nixnax 142:54d1543e23e5 853 if( httpGet6 == 'b' ) { // if the fetched page is "xb" send a meta command to let the browser continuously reload
nixnax 142:54d1543e23e5 854 n=n+sprintf(n+dataStart, "<meta http-equiv=\"refresh\" content=\"0\">"); // reload loop - handy for benchmarking
nixnax 142:54d1543e23e5 855 }
nixnax 142:54d1543e23e5 856 // /x is a very short page, in fact, it is only a decimal number showing the http Page count
nixnax 142:54d1543e23e5 857 n=n+sprintf(n+dataStart,"%d ",ppp.httpPageCount); // not really valid html but most browsers and curl are ok with it
nixnax 142:54d1543e23e5 858 #endif
nixnax 142:54d1543e23e5 859 } else {
nixnax 142:54d1543e23e5 860 // all other requests get 404 Not Found response with a http frame count - nice for debugging
nixnax 142:54d1543e23e5 861 n=n+sprintf(n+dataStart,"<!DOCTYPE html><title>mbed PPP-Blinky</title>"); // html title (required element)
nixnax 142:54d1543e23e5 862 n=n+sprintf(n+dataStart,"<body>Not Found</body>"); // not found message
nixnax 142:54d1543e23e5 863 }
nixnax 142:54d1543e23e5 864 }
nixnax 142:54d1543e23e5 865 #define CONTENTLENGTHSIZE 5
nixnax 142:54d1543e23e5 866 char contentLengthString[CONTENTLENGTHSIZE+1];
nixnax 142:54d1543e23e5 867 snprintf(contentLengthString,CONTENTLENGTHSIZE+1,"%*d",CONTENTLENGTHSIZE,n-nHeader); // print Content-Length with leading spaces and fixed width equal to csize
nixnax 142:54d1543e23e5 868 memcpy(dataStart+contentLengthStart, contentLengthString, CONTENTLENGTHSIZE); // copy Content-Length to it's place in the send buffer
nixnax 142:54d1543e23e5 869 return n; // total byte size of our response
nixnax 142:54d1543e23e5 870 }
nixnax 142:54d1543e23e5 871
nixnax 142:54d1543e23e5 872 /// handle TCP data that is not an HTTP get
nixnax 142:54d1543e23e5 873 /// this is the response if we have TCP data but it's not an HTTP GET
nixnax 142:54d1543e23e5 874 /// this is handy when you for example want to use netcat (nc.exe) to talk to PPP-Blinky
nixnax 142:54d1543e23e5 875 /// this could also be a websocket receive event - especially if the first byte is 0x81 (websocket data push)
nixnax 142:54d1543e23e5 876 int tcpResponse(char * dataStart, int len, int * outFlags)
nixnax 142:54d1543e23e5 877 {
nixnax 142:54d1543e23e5 878 int n=0; // number of bytes we have printed so far
nixnax 142:54d1543e23e5 879 if (dataStart[0] == 0x81) { // check if this is a websocket push message
nixnax 142:54d1543e23e5 880 // this is most likely a websocket push message. you get this when you enter this in your browser console: x.send("my message");
nixnax 142:54d1543e23e5 881 if (0) putsWhileCheckingInput( "Got data from websocket send()\n" );
nixnax 142:54d1543e23e5 882
nixnax 142:54d1543e23e5 883 // for now we simply echo the websocket data back to the client - the client should therefore see an onmessage event
nixnax 142:54d1543e23e5 884 // to display the echoed data in your browser, enter the following into the browser console: x.onmessage = function(msg){ console.log( msg.data ); }
nixnax 142:54d1543e23e5 885 if (1) {
nixnax 142:54d1543e23e5 886 char mask [4];
nixnax 142:54d1543e23e5 887 memcpy ( mask, dataStart+2, 4); // websocket messages are "masked", so first we obtain the 4-byte mask
nixnax 142:54d1543e23e5 888 int websocketMessageSize = len - 6; // 1 byte prefix (0x81), 1 byte, 4 bytes mask = 6 bytes
nixnax 142:54d1543e23e5 889 if((dataStart[1]&0x80)==0x80) // test if the mask bit is set, which means all data is xor'ed with the mask
nixnax 142:54d1543e23e5 890 for (int i=0; i<websocketMessageSize; i++) dataStart[i+6]^= mask[i%4]; // unmask each byte with one of the mask bytes
nixnax 142:54d1543e23e5 891 dataStart[1] = len-2; // add four extra bytes to the message length because we don't use mask bytes for the send
nixnax 142:54d1543e23e5 892 memcpy(dataStart+2, "Got:",4); // insert our own text into the four mask bytes
nixnax 142:54d1543e23e5 893 n = len; // our response size remains exactly the same length as what we received
nixnax 142:54d1543e23e5 894 }
nixnax 142:54d1543e23e5 895 } else if ( (dataStart[0]==0x88) && (dataStart[1]==0x80) && (len == 6) ) { // test for a websocket close request
nixnax 142:54d1543e23e5 896 n=2; // our close command is only two bytes long because we don't use the four mask bytes
nixnax 142:54d1543e23e5 897 dataStart[1]=0; // we don't have mask bytes on
nixnax 142:54d1543e23e5 898 } else if (v1) putsWhileCheckingInput("TCP data received\n");
nixnax 142:54d1543e23e5 899 return n; // total byte size of our response
nixnax 142:54d1543e23e5 900 }
nixnax 142:54d1543e23e5 901
nixnax 142:54d1543e23e5 902 /// handle an incoming TCP packet
nixnax 142:54d1543e23e5 903 /// use the first few bytes to figure out if it's a websocket, an http request or just pure incoming TCP data
nixnax 142:54d1543e23e5 904 void tcpHandler()
nixnax 142:54d1543e23e5 905 {
nixnax 142:54d1543e23e5 906 // IP header
nixnax 142:54d1543e23e5 907 char * ipPkt = ppp.pkt.buf+4; // ip packet start
nixnax 142:54d1543e23e5 908 char * ihl = ipPkt; // bottom 4 bits
nixnax 142:54d1543e23e5 909 char * pktLen = ipPkt+2; // 2 bytes
nixnax 142:54d1543e23e5 910 char * ident = ipPkt+4; // 2 bytes
nixnax 142:54d1543e23e5 911 char * protocol = ipPkt+9; // 1 byte
nixnax 142:54d1543e23e5 912 char * headercheck= ipPkt+10; // 2 bytes
nixnax 142:54d1543e23e5 913 char * srcAdr = ipPkt+12; // 4 bytes
nixnax 142:54d1543e23e5 914 char * dstAdr = ipPkt+16; // 4 bytes = total of 20 bytes
nixnax 142:54d1543e23e5 915 int headerSizeIP = (ihl[0]&0xf)*4;
nixnax 142:54d1543e23e5 916 int packetLength = (pktLen[0]<<8)|pktLen[1]; // ip total packet length
nixnax 142:54d1543e23e5 917
nixnax 142:54d1543e23e5 918 // TCP header
nixnax 142:54d1543e23e5 919 char * tcp = ppp.pkt.buf+4+headerSizeIP; // start of tcp packet
nixnax 142:54d1543e23e5 920 char * srctcp = tcp + 0; // 2 bytes
nixnax 142:54d1543e23e5 921 char * dsttcp = tcp + 2; // 2 bytes
nixnax 142:54d1543e23e5 922 char * seqtcp = tcp + 4; // 4 bytes
nixnax 142:54d1543e23e5 923 char * acktcp = tcp + 8; // 4 bytes
nixnax 142:54d1543e23e5 924 char * offset = tcp + 12; // 4 bits
nixnax 142:54d1543e23e5 925 char * flagbitstcp = tcp + 12; // 9 bits
nixnax 142:54d1543e23e5 926 char * windowsizetcp = tcp + 14; // 2 bytes
nixnax 142:54d1543e23e5 927 char * checksumtcp = tcp + 16; // 2 bytes
nixnax 142:54d1543e23e5 928
nixnax 142:54d1543e23e5 929 if(ident) {}; // shut up unused variable reference warning
nixnax 142:54d1543e23e5 930 int tcpSize = packetLength - headerSizeIP;
nixnax 142:54d1543e23e5 931 int headerSizeTCP = ((offset[0]>>4)&0x0f)*4; // size of tcp header only
nixnax 142:54d1543e23e5 932 int protocolIP = protocol[0];
nixnax 142:54d1543e23e5 933 char * tcpDataIn = tcp + headerSizeTCP; // start of data block after TCP header
nixnax 142:54d1543e23e5 934 int tcpDataSize = tcpSize - headerSizeTCP; // size of data block after TCP header
nixnax 142:54d1543e23e5 935 char * tcpDataOut = tcp + 20; // start of outgoing data
nixnax 142:54d1543e23e5 936 unsigned int seq_in = (seqtcp[0]<<24)|(seqtcp[1]<<16)|(seqtcp[2]<<8)|(seqtcp[3]);
nixnax 142:54d1543e23e5 937 unsigned int ack_in = (acktcp[0]<<24)|(acktcp[1]<<16)|(acktcp[2]<<8)|(acktcp[3]);
nixnax 142:54d1543e23e5 938 unsigned int ack_out = seq_in + tcpDataSize;
nixnax 142:54d1543e23e5 939 unsigned int seq_out = ack_in; // use their version of our current sequence number
nixnax 142:54d1543e23e5 940
nixnax 142:54d1543e23e5 941 // first we shorten the TCP response header to only 20 bytes. This means we ignore all TCP option requests
nixnax 142:54d1543e23e5 942 tcpSize = 20; // shorten total TCP packet size to 20 bytes (no data)
nixnax 142:54d1543e23e5 943 headerSizeTCP = 20; // shorten outgoing TCP header size 20 bytes
nixnax 142:54d1543e23e5 944 offset[0] = (headerSizeTCP/4)<<4; // shorten tcp header size to 20 bytes
nixnax 142:54d1543e23e5 945 packetLength = 40; // shorten total packet size to 40 bytes (20 ip + 20 tcp)
nixnax 142:54d1543e23e5 946 pktLen[1] = 40; // set total packet size to 40 bytes (20 ip + 20 tcp)
nixnax 142:54d1543e23e5 947 pktLen[0] = 0; // set total packet size to 40 bytes (20 ip + 20 tcp)
nixnax 142:54d1543e23e5 948
nixnax 142:54d1543e23e5 949 int dataLen = 0; // most of our responses will have zero TCP data, only a header
nixnax 142:54d1543e23e5 950 int flagsOut = TCP_FLAG_ACK; // the default case is an ACK packet
nixnax 142:54d1543e23e5 951 int flagsTCP = ((flagbitstcp[0]&1)<<8)|flagbitstcp[1]; // the tcp flags we received
nixnax 142:54d1543e23e5 952 windowsizetcp[0] = (700 >> 8 ); // tcp window size hi byte
nixnax 142:54d1543e23e5 953 windowsizetcp[1] = (700 & 0xff); // tcp window size lo byte
nixnax 142:54d1543e23e5 954
nixnax 142:54d1543e23e5 955 // A sparse TCP flag interpreter that implements stateless TCP connections
nixnax 142:54d1543e23e5 956
nixnax 142:54d1543e23e5 957 switch ( flagsTCP ) {
nixnax 142:54d1543e23e5 958 case TCP_FLAG_ACK:
nixnax 142:54d1543e23e5 959 return;
nixnax 142:54d1543e23e5 960 case TCP_FLAG_SYN:
nixnax 142:54d1543e23e5 961 flagsOut = TCP_FLAG_SYN | TCP_FLAG_ACK; // something wants to connect - acknowledge it
nixnax 142:54d1543e23e5 962 seq_out = seq_in+0x10000000U; // create a new sequence number using their sequence as a starting point, increase the highest digit
nixnax 142:54d1543e23e5 963 ack_out++; // for SYN flag we have to increase the sequence by 1
nixnax 142:54d1543e23e5 964 break;
nixnax 142:54d1543e23e5 965 case TCP_FLAG_ACK | TCP_FLAG_PSH:
nixnax 142:54d1543e23e5 966 if ( (strncmp(tcpDataIn, "GET /", 5) == 0) ) { // check for an http GET command
nixnax 142:54d1543e23e5 967 flagsOut = TCP_FLAG_ACK | TCP_FLAG_PSH; // set outgoing FIN flag to ask them to close from their side
nixnax 142:54d1543e23e5 968 dataLen = httpResponse(tcpDataOut); // send an http response
nixnax 142:54d1543e23e5 969 } else {
nixnax 142:54d1543e23e5 970 dataLen = tcpResponse(tcpDataOut,tcpDataSize, &flagsOut); // not a web request, send a packet reporting number of received bytes
nixnax 142:54d1543e23e5 971 }
nixnax 142:54d1543e23e5 972 break;
nixnax 142:54d1543e23e5 973 case TCP_FLAG_FIN:
nixnax 142:54d1543e23e5 974 case TCP_FLAG_FIN | TCP_FLAG_ACK:
nixnax 142:54d1543e23e5 975 case TCP_FLAG_FIN | TCP_FLAG_PSH | TCP_FLAG_ACK:
nixnax 142:54d1543e23e5 976 flagsOut = TCP_FLAG_ACK | TCP_FLAG_FIN; // set outgoing FIN flag to ask them to close from their side
nixnax 142:54d1543e23e5 977 ack_out++; // for FIN flag we have to increase the sequence by 1
nixnax 142:54d1543e23e5 978 break;
nixnax 142:54d1543e23e5 979 default:
nixnax 142:54d1543e23e5 980 return; // ignore remaining packets
nixnax 142:54d1543e23e5 981 } // switch
nixnax 142:54d1543e23e5 982
nixnax 142:54d1543e23e5 983 // The TCP flag handling is now done
nixnax 142:54d1543e23e5 984 // first we swap source and destination TCP addresses and insert the new ack and seq numbers
nixnax 142:54d1543e23e5 985 char tempHold[12]; // it's 12 long because we later reuse it when building the TCP pseudo-header
nixnax 142:54d1543e23e5 986 memcpy(tempHold, srcAdr,4);
nixnax 142:54d1543e23e5 987 memcpy(srcAdr, dstAdr,4);
nixnax 142:54d1543e23e5 988 memcpy(dstAdr, tempHold,4); // swap ip address source/dest
nixnax 142:54d1543e23e5 989 memcpy(tempHold, srctcp,2);
nixnax 142:54d1543e23e5 990 memcpy(srctcp, dsttcp,2);
nixnax 142:54d1543e23e5 991 memcpy(dsttcp, tempHold,2); // swap ip port source/dest
nixnax 142:54d1543e23e5 992
nixnax 142:54d1543e23e5 993 acktcp[0]=ack_out>>24;
nixnax 142:54d1543e23e5 994 acktcp[1]=ack_out>>16;
nixnax 142:54d1543e23e5 995 acktcp[2]=ack_out>>8;
nixnax 142:54d1543e23e5 996 acktcp[3]=ack_out>>0; // save ack 32-bit integer
nixnax 142:54d1543e23e5 997 seqtcp[0]=seq_out>>24;
nixnax 142:54d1543e23e5 998 seqtcp[1]=seq_out>>16;
nixnax 142:54d1543e23e5 999 seqtcp[2]=seq_out>>8;
nixnax 142:54d1543e23e5 1000 seqtcp[3]=seq_out>>0; // save seq 32-bit integer
nixnax 142:54d1543e23e5 1001
nixnax 142:54d1543e23e5 1002 flagbitstcp[1] = flagsOut; // update the TCP flags
nixnax 142:54d1543e23e5 1003
nixnax 142:54d1543e23e5 1004 // increment our outgoing ip packet counter
nixnax 142:54d1543e23e5 1005 ppp.ip.ident++; // get next ident number for our packet
nixnax 142:54d1543e23e5 1006
nixnax 142:54d1543e23e5 1007 // Now we recalculate all the header sizes
nixnax 142:54d1543e23e5 1008 tcpSize = headerSizeTCP + dataLen; // tcp packet size
nixnax 142:54d1543e23e5 1009 int newPacketSize = headerSizeIP + tcpSize; // calculate size of the outgoing packet
nixnax 142:54d1543e23e5 1010 pktLen[0] = (newPacketSize>>8);
nixnax 142:54d1543e23e5 1011 pktLen[1]=newPacketSize; // ip total packet size
nixnax 142:54d1543e23e5 1012 ppp.pkt.len = newPacketSize+4+2; // ip packet length + 4-byte ppp prefix (ff 03 00 21) + 2 fcs (crc) bytes bytes at the end of the packet
nixnax 142:54d1543e23e5 1013
nixnax 142:54d1543e23e5 1014 // the header is all set up, now do the IP and TCP checksums
nixnax 142:54d1543e23e5 1015 headercheck[0]=0; // IP header checksum
nixnax 142:54d1543e23e5 1016 headercheck[1]=0; // IP header checksum
nixnax 142:54d1543e23e5 1017 headerCheckSum(); // calculate the IP header checksum
nixnax 142:54d1543e23e5 1018
nixnax 142:54d1543e23e5 1019 // now we have to build the so-called 12-byte TCP "pseudo-header" in front of the TCP header (containing some IP header values) in order to correctly calculate the TCP checksum
nixnax 142:54d1543e23e5 1020 // this header contains the most important parts of the IP header, i.e. source and destination address, protocol number and data length.
nixnax 142:54d1543e23e5 1021 char * pseudoHeader = tcp-12; // mark the start of the TCP pseudo-header
nixnax 142:54d1543e23e5 1022 memcpy(tempHold, pseudoHeader, 12); // preserve the 12 bytes of the IP header where the TCP pseudo-Header will be built
nixnax 142:54d1543e23e5 1023 memcpy( pseudoHeader+0, srcAdr, 8); // IP source and destination addresses from IP header
nixnax 142:54d1543e23e5 1024 memset( pseudoHeader+8, 0, 1); // reserved, set to zero
nixnax 142:54d1543e23e5 1025 memset( pseudoHeader+9, protocolIP, 1); // protocol from IP header
nixnax 142:54d1543e23e5 1026 memset( pseudoHeader+10, tcpSize>>8, 1); // size of IP data (TCP packet size)
nixnax 142:54d1543e23e5 1027 memset( pseudoHeader+11, tcpSize, 1); // size of IP data (TCP packet size)
nixnax 142:54d1543e23e5 1028
nixnax 142:54d1543e23e5 1029 // pseudo-header built, now we can calculate TCP checksum
nixnax 142:54d1543e23e5 1030 checksumtcp[0]=0;
nixnax 142:54d1543e23e5 1031 checksumtcp[1]=0;
nixnax 142:54d1543e23e5 1032 unsigned int pseudoHeaderSum=dataCheckSum((unsigned char *)pseudoHeader,tcpSize+12); // calculate the TCP checksum starting at the pseudo-header
nixnax 142:54d1543e23e5 1033 checksumtcp[0]=pseudoHeaderSum>>8;
nixnax 142:54d1543e23e5 1034 checksumtcp[1]=pseudoHeaderSum;
nixnax 142:54d1543e23e5 1035 memcpy( tcp-12, tempHold, 12); // restore the 12 bytes that the pseudo-header overwrote
nixnax 142:54d1543e23e5 1036 dumpHeaderIP(1); // dump outgoing IP header
nixnax 142:54d1543e23e5 1037 dumpHeaderTCP(1); // dump outgoing TCP header
nixnax 142:54d1543e23e5 1038 for (int i=0; i<45*1000/10; i++) { // 45 ms delay before sending frame - a typical internet delay time
nixnax 142:54d1543e23e5 1039 checkPc(); // catch any incoming characters
nixnax 142:54d1543e23e5 1040 wait_us(10); // wait less than 1 character duration at 115200
nixnax 142:54d1543e23e5 1041 }
nixnax 144:01d98cf7738e 1042 sendPppFrame(); // All preparation complete - send the TCP response
nixnax 142:54d1543e23e5 1043 if(0) dumpPPPFrame(); // set to 1 to dump transmitted ppp frame
nixnax 142:54d1543e23e5 1044 memset(ppp.pkt.buf+44,0,500); // flush out traces of previous data that we may scan for
nixnax 142:54d1543e23e5 1045 }
nixnax 142:54d1543e23e5 1046
nixnax 142:54d1543e23e5 1047
nixnax 142:54d1543e23e5 1048 /// dump the TCP data to the debug serial port
nixnax 142:54d1543e23e5 1049 void dumpDataTCP()
nixnax 142:54d1543e23e5 1050 {
nixnax 142:54d1543e23e5 1051 int ipPktLen = (ppp.pkt.buf[6]<<8)|ppp.pkt.buf[7]; // overall length of ip packet
nixnax 142:54d1543e23e5 1052 int ipHeaderLen = (ppp.pkt.buf[4]&0xf)*4; // length of ip header
nixnax 142:54d1543e23e5 1053 int headerSizeTCP = ((ppp.pkt.buf[4+ipHeaderLen+12]>>4)&0xf)*4;; // length of tcp header
nixnax 142:54d1543e23e5 1054 int dataLen = ipPktLen - ipHeaderLen - headerSizeTCP; // data is what's left after the two headers
nixnax 142:54d1543e23e5 1055 if (v1) {
nixnax 142:54d1543e23e5 1056 char pbuf[50]; // local print buffer
nixnax 142:54d1543e23e5 1057 checkPc();
nixnax 142:54d1543e23e5 1058 sprintf(pbuf, "TCP %d ipHeader %d tcpHeader %d Data %d\n", ipPktLen, ipHeaderLen, headerSizeTCP, dataLen); // 1 for more verbose
nixnax 142:54d1543e23e5 1059 checkPc();
nixnax 142:54d1543e23e5 1060 putsWhileCheckingInput( pbuf );
nixnax 142:54d1543e23e5 1061 }
nixnax 142:54d1543e23e5 1062 if (dataLen > 0) {
nixnax 142:54d1543e23e5 1063 ppp.pkt.buf[4+ipHeaderLen+headerSizeTCP+dataLen]=0; // insert a null after the data so debug printf stops printing after the data
nixnax 142:54d1543e23e5 1064 putsWhileCheckingInput( ppp.pkt.buf+4+ipHeaderLen+headerSizeTCP ); // print the tcp payload data
nixnax 142:54d1543e23e5 1065 putsWhileCheckingInput("\n");
nixnax 142:54d1543e23e5 1066 }
nixnax 142:54d1543e23e5 1067 }
nixnax 142:54d1543e23e5 1068
nixnax 142:54d1543e23e5 1069 /// handle an incoming TCP packet
nixnax 142:54d1543e23e5 1070 void TCPpacket()
nixnax 142:54d1543e23e5 1071 {
nixnax 142:54d1543e23e5 1072 dumpHeaderIP(0); // dump incoming packet header
nixnax 142:54d1543e23e5 1073 dumpHeaderTCP(0); // dump incoming packet header
nixnax 142:54d1543e23e5 1074 if (v2) dumpDataTCP();
nixnax 142:54d1543e23e5 1075 tcpHandler();
nixnax 142:54d1543e23e5 1076 }
nixnax 142:54d1543e23e5 1077
nixnax 142:54d1543e23e5 1078 /// handle the remaining IP protocols by ignoring them
nixnax 142:54d1543e23e5 1079 void otherProtocol()
nixnax 142:54d1543e23e5 1080 {
nixnax 142:54d1543e23e5 1081 debugPrintf("Other IP protocol");
nixnax 142:54d1543e23e5 1082 }
nixnax 142:54d1543e23e5 1083
nixnax 142:54d1543e23e5 1084 /// process an incoming IP packet
nixnax 142:54d1543e23e5 1085 void IPframe()
nixnax 142:54d1543e23e5 1086 {
nixnax 142:54d1543e23e5 1087 int protocol = ppp.pkt.buf[13];
nixnax 142:54d1543e23e5 1088 switch (protocol) {
nixnax 142:54d1543e23e5 1089 case 1:
nixnax 142:54d1543e23e5 1090 ICMPpacket();
nixnax 142:54d1543e23e5 1091 break;
nixnax 142:54d1543e23e5 1092 case 2:
nixnax 142:54d1543e23e5 1093 IGMPpacket();
nixnax 142:54d1543e23e5 1094 break;
nixnax 142:54d1543e23e5 1095 case 17:
nixnax 142:54d1543e23e5 1096 UDPpacket();
nixnax 142:54d1543e23e5 1097 break;
nixnax 142:54d1543e23e5 1098 case 6:
nixnax 142:54d1543e23e5 1099 TCPpacket();
nixnax 142:54d1543e23e5 1100 break;
nixnax 142:54d1543e23e5 1101 default:
nixnax 142:54d1543e23e5 1102 otherProtocol();
nixnax 142:54d1543e23e5 1103 }
nixnax 142:54d1543e23e5 1104 }
nixnax 142:54d1543e23e5 1105
nixnax 142:54d1543e23e5 1106 /// respond to LCP (line configuration protocol) configuration request) by allowing no options
nixnax 142:54d1543e23e5 1107 void LCPconfReq()
nixnax 142:54d1543e23e5 1108 {
nixnax 142:54d1543e23e5 1109 debugPrintf("LCP Config ");
nixnax 142:54d1543e23e5 1110 if (ppp.pkt.buf[7] != 4) {
nixnax 142:54d1543e23e5 1111 ppp.pkt.buf[4]=4; // allow only "no options" which means Maximum Receive Unit (MRU) is default 1500 bytes
nixnax 142:54d1543e23e5 1112 debugPrintf("Reject\n");
nixnax 144:01d98cf7738e 1113 sendPppFrame();
nixnax 142:54d1543e23e5 1114 } else {
nixnax 142:54d1543e23e5 1115 ppp.pkt.buf[4]=2; // ack zero conf
nixnax 142:54d1543e23e5 1116 debugPrintf("Ack\n");
nixnax 144:01d98cf7738e 1117 sendPppFrame();
nixnax 142:54d1543e23e5 1118 debugPrintf("LCP Ask\n");
nixnax 142:54d1543e23e5 1119 ppp.pkt.buf[4]=1; // request no options
nixnax 144:01d98cf7738e 1120 sendPppFrame();
nixnax 142:54d1543e23e5 1121 }
nixnax 142:54d1543e23e5 1122 }
nixnax 142:54d1543e23e5 1123
nixnax 142:54d1543e23e5 1124 /// handle LCP acknowledge packets by ignoring them
nixnax 142:54d1543e23e5 1125 void LCPconfAck()
nixnax 142:54d1543e23e5 1126 {
nixnax 142:54d1543e23e5 1127 debugPrintf("LCP Ack\n");
nixnax 142:54d1543e23e5 1128 }
nixnax 142:54d1543e23e5 1129
nixnax 143:c5019f856a56 1130 /// handle LCP end (disconnect) packets by acknowledging them and by setting ppp.online to false
nixnax 142:54d1543e23e5 1131 void LCPend()
nixnax 142:54d1543e23e5 1132 {
nixnax 142:54d1543e23e5 1133 ppp.pkt.buf[4]=6;
nixnax 144:01d98cf7738e 1134 sendPppFrame(); // acknowledge
nixnax 142:54d1543e23e5 1135 ppp.online=0; // start hunting for connect string again
nixnax 142:54d1543e23e5 1136 pppInitStruct(); // flush the receive buffer
nixnax 143:c5019f856a56 1137 debugPrintf("LCP End (Disconnect from host)\n");
nixnax 142:54d1543e23e5 1138 }
nixnax 142:54d1543e23e5 1139
nixnax 142:54d1543e23e5 1140 /// respond to other LCP requests by ignoring them
nixnax 142:54d1543e23e5 1141 void LCPother()
nixnax 142:54d1543e23e5 1142 {
nixnax 142:54d1543e23e5 1143 debugPrintf("LCP Other\n");
nixnax 142:54d1543e23e5 1144 dumpPPPFrame();
nixnax 142:54d1543e23e5 1145 }
nixnax 142:54d1543e23e5 1146
nixnax 142:54d1543e23e5 1147 /// process incoming LCP packets
nixnax 142:54d1543e23e5 1148 void LCPframe()
nixnax 142:54d1543e23e5 1149 {
nixnax 142:54d1543e23e5 1150 int code = ppp.pkt.buf[4];
nixnax 142:54d1543e23e5 1151 switch (code) {
nixnax 142:54d1543e23e5 1152 case 1:
nixnax 142:54d1543e23e5 1153 LCPconfReq();
nixnax 142:54d1543e23e5 1154 break; // config request
nixnax 142:54d1543e23e5 1155 case 2:
nixnax 142:54d1543e23e5 1156 LCPconfAck();
nixnax 142:54d1543e23e5 1157 break; // config ack
nixnax 142:54d1543e23e5 1158 case 5:
nixnax 142:54d1543e23e5 1159 LCPend();
nixnax 142:54d1543e23e5 1160 break; // end connection
nixnax 142:54d1543e23e5 1161 default:
nixnax 142:54d1543e23e5 1162 LCPother();
nixnax 142:54d1543e23e5 1163 }
nixnax 142:54d1543e23e5 1164 }
nixnax 142:54d1543e23e5 1165
nixnax 142:54d1543e23e5 1166 /// discard packets that are not IP, IPCP, or LCP
nixnax 142:54d1543e23e5 1167 void discardedFrame()
nixnax 142:54d1543e23e5 1168 {
nixnax 142:54d1543e23e5 1169 if (v0) debugPrintf("Frame is not IP, IPCP or LCP: %02x %02x %02x %02x\n", ppp.pkt.buf[0],ppp.pkt.buf[1],ppp.pkt.buf[2],ppp.pkt.buf[3]);
nixnax 142:54d1543e23e5 1170 }
nixnax 142:54d1543e23e5 1171
nixnax 142:54d1543e23e5 1172 /// determine the packet type (IP, IPCP or LCP) of incoming packets
nixnax 142:54d1543e23e5 1173 void determinePacketType()
nixnax 142:54d1543e23e5 1174 {
nixnax 142:54d1543e23e5 1175 if ( ppp.pkt.buf[0] != 0xff ) {
nixnax 142:54d1543e23e5 1176 debugPrintf("byte0 != ff\n");
nixnax 142:54d1543e23e5 1177 return;
nixnax 142:54d1543e23e5 1178 }
nixnax 142:54d1543e23e5 1179 if ( ppp.pkt.buf[1] != 3 ) {
nixnax 142:54d1543e23e5 1180 debugPrintf("byte1 != 3\n");
nixnax 142:54d1543e23e5 1181 return;
nixnax 142:54d1543e23e5 1182 }
nixnax 142:54d1543e23e5 1183 if ( ppp.pkt.buf[3] != 0x21 ) {
nixnax 142:54d1543e23e5 1184 debugPrintf("byte2 != 21\n");
nixnax 142:54d1543e23e5 1185 return;
nixnax 142:54d1543e23e5 1186 }
nixnax 142:54d1543e23e5 1187 int packetType = ppp.pkt.buf[2];
nixnax 142:54d1543e23e5 1188 switch (packetType) {
nixnax 142:54d1543e23e5 1189 case 0xc0:
nixnax 142:54d1543e23e5 1190 LCPframe();
nixnax 142:54d1543e23e5 1191 break; // link control
nixnax 142:54d1543e23e5 1192 case 0x80:
nixnax 142:54d1543e23e5 1193 IPCPframe();
nixnax 142:54d1543e23e5 1194 break; // IP control
nixnax 142:54d1543e23e5 1195 case 0x00:
nixnax 142:54d1543e23e5 1196 IPframe();
nixnax 142:54d1543e23e5 1197 break; // IP itself
nixnax 142:54d1543e23e5 1198 default:
nixnax 142:54d1543e23e5 1199 discardedFrame();
nixnax 142:54d1543e23e5 1200 }
nixnax 142:54d1543e23e5 1201 }
nixnax 142:54d1543e23e5 1202
nixnax 142:54d1543e23e5 1203 /// scan the PPP serial input stream for frame start markers
nixnax 143:c5019f856a56 1204 void waitForPppFrame()
nixnax 142:54d1543e23e5 1205 {
nixnax 142:54d1543e23e5 1206 while(1) {
nixnax 142:54d1543e23e5 1207 checkPc(); // handle received characters
nixnax 142:54d1543e23e5 1208 if ( ppp.rx.head != ppp.rx.tail ) {
nixnax 142:54d1543e23e5 1209 int oldTail = ppp.rx.tail; // remember where the character is located in the buffer
nixnax 142:54d1543e23e5 1210 int rx = pc_getBuf(); // get the character
nixnax 142:54d1543e23e5 1211 if (rx==FRAME_7E) {
nixnax 142:54d1543e23e5 1212 if (ppp.firstFrame) { // is this the start of the first frame start
nixnax 142:54d1543e23e5 1213 ppp.firstFrame=0;
nixnax 142:54d1543e23e5 1214 ppp.rx.rtail = ppp.rx.tail; // update real-time tail with the virtual tail
nixnax 142:54d1543e23e5 1215 ppp.hdlc.frameStartIndex = ppp.rx.tail; // remember where first frame started
nixnax 142:54d1543e23e5 1216 } else {
nixnax 142:54d1543e23e5 1217 ppp.hdlc.frameEndIndex=oldTail; // mark the frame end character
nixnax 142:54d1543e23e5 1218 processPPPFrame(ppp.hdlc.frameStartIndex, ppp.hdlc.frameEndIndex); // process the frame
nixnax 142:54d1543e23e5 1219 ppp.rx.rtail = ppp.rx.tail; // update real-time tail with the virtual tail
nixnax 142:54d1543e23e5 1220 ppp.hdlc.frameStartIndex = ppp.rx.tail; // remember where next frame started
nixnax 142:54d1543e23e5 1221 break;
nixnax 142:54d1543e23e5 1222 }
nixnax 142:54d1543e23e5 1223 }
nixnax 142:54d1543e23e5 1224 }
nixnax 142:54d1543e23e5 1225 }
nixnax 142:54d1543e23e5 1226 }
nixnax 142:54d1543e23e5 1227
nixnax 142:54d1543e23e5 1228 /// scan for a connect string ("CLIENT") from the host PC, if found, we set ppp.oline to true, which will the IP packet scanner
nixnax 142:54d1543e23e5 1229 void scanForConnectString()
nixnax 142:54d1543e23e5 1230 {
nixnax 142:54d1543e23e5 1231 while(ppp.online == 0) {
nixnax 142:54d1543e23e5 1232 checkPc(); // gather received characters
nixnax 142:54d1543e23e5 1233 // search for Windows Dialup Networking "Direct Connection Between Two Computers" expected connect string
nixnax 142:54d1543e23e5 1234 char * found1 = strstr( (char *)ppp.rx.buf, "CLIENT" );
nixnax 142:54d1543e23e5 1235 if (found1 != NULL) {
nixnax 142:54d1543e23e5 1236 // respond with Windows Dialup networking expected "Direct Connection Between Two Computers" response string
nixnax 143:c5019f856a56 1237 if (v0) debugPrintf("Connected: Found connect string \"CLIENT\", sent \"CLIENTSERVER\"\n");
nixnax 142:54d1543e23e5 1238 pc.puts("CLIENTSERVER");
nixnax 142:54d1543e23e5 1239 ppp.online=1; // we are connected - set flag so we stop looking for the connect string
nixnax 142:54d1543e23e5 1240 checkPc();
nixnax 142:54d1543e23e5 1241 }
nixnax 142:54d1543e23e5 1242 }
nixnax 142:54d1543e23e5 1243 }
nixnax 142:54d1543e23e5 1244
nixnax 144:01d98cf7738e 1245 /// Initialize PPP data structure and set serial port(s) baud rate(s)
nixnax 144:01d98cf7738e 1246 void initializePpp()
nixnax 142:54d1543e23e5 1247 {
nixnax 142:54d1543e23e5 1248 pc.baud(115200); // USB serial port to pc
nixnax 144:01d98cf7738e 1249 debugBaudRate(115200); // baud rate for (optional) debug serial port
nixnax 142:54d1543e23e5 1250 debugPrintf("\x1b[2J\x1b[H\x1b[30mmbed PPP-Blinky HTTP & WebSocket server ready :)\n"); // VT100 codes for clear_screen, home, black_text - Tera Term is a handy VT100 terminal
nixnax 142:54d1543e23e5 1251 pppInitStruct(); // initialize all the PPP properties
nixnax 143:c5019f856a56 1252 }