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:
Mon Aug 28 15:36:09 2017 +0000
Revision:
141:4cc1518ee06f
Parent:
140:f526e9ecfebb
Child:
142:54d1543e23e5
Comments, removed Dial-up Error 777 reference.

Who changed what in which revision?

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