Home

Manual - MicroProcessor Engineering Ltd.

image

Contents

1. REBOOTING SELECTING lt DHCPOFFER ss Seinen Ar Collect f replies DHCPACK jo We q cipe Record lease set v Select offer timers T1 T2 send DHCPREQUEST Pa 222 gt DHCPNAK Lease expired REQUESTING Halt network DHCPOFFER Discard _ RoC W DHCPACK Record lease set REBINDING timers T1 T2 DHCPACK V Record lease set S dere ee en ee timers T1 T2 qossee gt lt BOUND lt DHCPOFFER DHCPACK T2 expires DHCPNAK DHCPNAK Discard _ Broadcast Halt network DHCPREQUEST DHCPACK T1 expires Record lease set Send DHCPREQUEST timers T1 T2 to leasing server Figure 5 State transition diagram for DHCP clients sm smState smDHidle smState smDHinit smState smDHselect smState smDHrequest idle do nothing pseudostate initialisation o p DHCPDISCOVER process DHCPOFFER s process ACK discard offers ACK decline gt o p DHCPDECLINE smDHinit ACK accept gt record lease smDHbound go ACK check gt DHCPdecline init or bound A A A A A A AW smState smDHarpcheck Chapter 20 DHCP and BOOTP 55 smState smDHbound discard messages time out gt smState smDHrenew wait ACK T2 expiry smState smDHrebind wait ACK NAK smStat
2. 0 84 Th EE 45 asmx neueren as 118 asp headers EE 123 E E KEE 123 EDERT Redon ta nd bacs ibant idus 118 aspfil reg uillo4leee wel eh Ete pei 127 aSspinterpret ap 127 ASPPLOCESS nen eek 123 E EE 123 aspx typ EE 118 atlinkdm 2ecemec ne ETE RU EET PE gue 83 A vices oxi wee eei ls EXER RM ER 83 B DAES pesto te ha X gaere Pater eg ERE eld 127 badippacket ree LP RP RUE 48 basehdrS un secs ER 124 129 BALYS yp 146 bind 9 bel ic erp periere Sle 88 DIO ON ici n na anne an EE Rep 147 bindtO i rai wise Er SPERA een 88 RTE nene be Geben PE en 147 SA ne TE IP RE EIE 147 bloCkEid ee prb er hate e mu ere ea e 93 bodyleft I as dae 125 bootp fid snd iila re ek RR re undas 55 bootpmagie nee 56 boundary ecsedi oemei setane e ises 124 Let EE 146 P ff ea ieh de ran 119 o AA TE A TS 119 buffenit u i see een 119 buffer 27 41 45 101 121 135 140 141 147 buffhdrsize i o een 11 33 bus iz pianista e 29 DUE Pci ri la ete ee 119 buffitypemask eeh SEELEN 29 bumppbuffdata ile Se m reete 30 C CUA oe Le erg ech Are de RP E 97 64 canrouteip ricino a 47 C hweroute ere ei ra Y EUR 45 COUT ROO EEE NER TECH dabo E editis qns 21 A u a ne nee ps pisei 41 Cigtemplate ungern as resa ERA E Y ins 140 cgiend slash te eR ORE DER Ed E deine 125 EE 125 E AAA ria penni iy aia DIEE Niais 125 A 125 check tcp cksum oie nen ann nee 91 158 ei e E EE 84 el EE 107 Checkftpdatay icic
3. Seesen NTP Packet Received 4 ACTIVE Timeout sm smState smSNinit initialisation wait for params from caller smState smSNconfigured X Send SNTP Request set up timeout smState smSNactive X SNTP answer received within timeout period sm smSNactions X number of states in this machine variable SNTPTimer addr Holds the TICKS time at which the next SNTP action will be performed 0 for no action variable smSNcount addr Down counter used to provide repetitions and timeouts variable smSNstate n Holds current SNTP state create smSNactions addr Execution table containing the xts of the action words This in CDATA space and is filled in later setSNstate xt state INTERPRETER word that sets the action of the given state SNTPidle er Performed periodically to do SNTP actions 22 4 State machine utilities SetSNTPtimer ms Set the SNTP timer to time out ms later SNstate N Debug tool to display the current state of the SNTP state machine toSNTPstate NX ms n state The given state will be executed after the given period in ms and n times if sensitive to the number of times Note that this specifies the interval until the state is executed not the repetition rate of the state 22 5 Outgoing message tools variable SNTPreply addr Set non zero when an SNTP reply has been received but the data has not yet been
4. Set the given QVAR to n which is held as a signed decimal string getQvar caddr len n Return the value held in the QVAR as a signed decimal number If the QVAR does not exist NO_VAR_SET is returned If the string cannot be converted zero is returned CEM specific numeric items are commented out QvarString caddr len type Return true if the variable is a string variable 35 6 ASP Support ASP stands for Active Server Pages In PowerNet these are HTML pages which are modified by PowerNet when served See Examples PowerNet TestPages thanks asp for an example The script language is Forth itself Inside an HTML document scripting commands Forth source are contained inside tags of the form lt Forth code gt It is important that the script delimiters lt and gt are surrounded by white space otherwise the very simple parser will fail Before any scripting can be performed the first command must be on one line 4 language forthscript gt After that Forth source code can be interpreted Note that any CGI variables QVARS above are available For example if a form was submitted with a GET request Chapter 35 HTTP Server 123 GET formi asp sname Robert amp send submit You can display the data using a script such as 4 s sname qstring gt Pages can be served from a linear memory image or from the FAT file system When scripts are served from memory each script section must b
5. TcpIdle sk cb Handles TCP idle time processing 23 13 Primitives for the BSD layer Tcp Open sk cb res res Allows an application to open the TCP connection N B This is a blocking function It will not return until connected or timed out Tcp Close sk cb res res Allows an application to close the T CP connection cleanly This is the TCP primitive for the BSD disconnect function 23 14 TCP initialisation TcpInit N Initialise the TCP layer 23 15 Checksum test code Chapter 24 SMC LAN91C92 4 6 Ethernet Driver Code 77 24 SMC LAN91C92 4 6 Ethernet Driver Code 24 1 Introduction The file Smc91C9z fth contains the hardware driver layer for the Standard MicroSystems LAN91C92 4 6 Ethernet controller chips as used on the MPE ARM Development Kit MPE Hiden SA1110 StrongBox and other MPE boards The data sheets for these devices may be found at www smsc com and the part number for the MPE board is LAN91C96I which can be used at 5v or 3 3v The controller has 64 8 bit registers organised as four banks of 16 The code is written for portability rather than speed and uses byte accesses only This permits the code to be used without change on big and little endian CPUs regardless of the bus interface width 8 or 16 bits 24 2 Hardware gotchas This code assumes a CPU with byte addressing A cell addressed machine e g most DSPs will require considerable changes to the source code for mem
6. ftp250 Return status 250 good file command ftp226 Return status 226 transfer successful ftp331 Return status 331 password needed ftp350 Return status 350 need more info ftp425 Return status 425 can t make data connection Chapter 33 FTP Server 109 ftp426 Return status 426 aborted ftp450 Return FTP error code 450 action not taken ftp451 No Return FTP error code 451 ftp502 Return FTP error code 502 command not implemented ftp504 Return FTP error code 504 ftp550 Return FTP error code 550 33 7 Data socket operations sm 0 Starts the definition of a state machine s states smState n n 1 Defines the next state as an EQU and increments the state number sm n Finishes the state machine and defines an equate of the number of states The FTP data transfer state machine sm smState ftpDtIdle No data transfer in progress smState ftpListening PASV mode wait connection smState ftpConnected wait transfer command smState ftpReadSendData XV RETRieve smState ftpRecvWriteData STORe smState ftpErrorState it s bad if we get here sm FTPsm n Select the the FTP data socket states goFTPidle As ftpDtIdle my_ftpDataState goFTPlistening N ftpListening my ftpDataState goFTPconnected KE ftpConnected my_ftpDataState goFTPReadSend ftpReadSendData my_ftpDataState goFTPRecv
7. io con NV R ipvec opvec Restore the I O devices from the return stack ConLine caddr len Display text with leading CR on Forth console debug_emit char As EMIT but always uses the CONSOLE device debug_cr NS As CR but always uses the CONSOLE device debug space As SPACE but always uses the CONSOLE device debug spaces n As SPACES but always uses the CONSOLE device debug pos Nn Position the console output to column n debug type N addr len As TYPE but always uses the CONSOLE device debug count amp type c addr As COUNT TYPE but always uses the CONSOLE device debug_ Nn As but always uses the CONSOLE device debug hex Nn As HEX but always uses the CONSOLE device debug decimal Nn As DECIMAL but always uses the CONSOLE device debug lword n 16 PowerNet TCP IP Stack As LWORD but always uses the CONSOLE device debug byte n As BYTE but always uses the CONSOLE device debug ASCII char As ASCII but always uses the CONSOLE device debug s Nos As S but always uses the CONSOLE device debug dump addr len As DUMP but always uses the CONSOLE device 4 3 Stack checking StackEmpty If the stack depth is non zero issue a console warning message and clear the stack This is often used at the end of a task loop DictTop here Used by some debug tools as the highest permi
8. ms timer for maximum segment lifetime mSecs default is 30 secs 7200000 equ TCPIDLETIME ms timer for idle disconnection mSecs default is 2 hours 12 equ TCPMAXRETRIES X n Maximum number of transmission retries before returning SOCKET ERROR default is 12 If a receiving socket fails to accept new data the total timeout will be TXRETRY TIME TCPMAXRETRIES the default being 60 seconds create MSSopt addr Maximum Segment Size option 23 2 Unknown socket requests variable NoTcpHandle addr Holds the handle of a socket used to handle unknown TCP requests Init NoTcp Socket X res SOCKET_ERROR Initialise a socket structure to handle unknown TCP requests SOCKET_ERROR is returned if the socket cannot be initialised 70 PowerNet TCP IP Stack 23 3 TCP structures and equates Most equates are not documented STRUCT tcp_hdr size of tcp header structure TCP header structure STRUCT tcpcb N size TCP control block structure is defined in structs fth TcpStateQ sk state Get socket state tcpstate Nn Display tcp socket state Only compiled if DIAGS is non zero ShowTcpState sk Display the state for the connection 23 4 TCP structure creation and deletion initTcpTxBuff buff cb Use buff to initialise or reset the T CP transmit buffer TcpTxBuff N cb FREE the T CP transmit buffer and reset the transmit pointers goCLOSED sk Place socket i
9. RNTO lt filespec gt Process RNTO the second part of the file rename operation DELE X DELE lt filespec gt Process the file delete command MKD MED lt pathspec gt 114 Process the make directory command RMD XV RMD lt pathspec gt Process the delete directory command previous definitions End of FTP command definitions 33 11 FTP service tasks FTPcommands PowerNet TCP IP Stack Empty the return stack store 0 in SOURCE ID and enter interpretation state FTPcommands repeatedly inputs an command line and FTPinterprets it FTPcommands must initialise TIB BASE IPVEC and OPVEC FTPservice Note that any task that uses The FTP service task launched for each established Telnet connection FTPconns X u Return the number of FTP connections This is the number FTP service tasks running Each one needs two sockets 33 12 FTP listening task FTPserverPass One iteration through the FTP server FTPserver stay here forever The FTP listening task O value FTPtask Oltask Returns 0 or the FTP server task if running startFTPserver N Start the FTP server task StopFTPserver Stop the FTP server 33 13 Diagnostics This code is only compiled if the EQUate DIAGS is set non zero ftp initfatfs powernet Start the file system and PowerNet FTPchain NS Display data about the FTP sockets Chapter 34 WWW Support 115
10. Zero the USER variables MY_HSOCKET and MY_SOCKET ShutErrSocket socket_error Close the current server socket and return SOCKET_ERROR All allocated socket and service memory is released by the close InitServerSocket service data port res Create a listening socket and the private data for a TCP service conversation On success the USER variables MY_HSOCKET and MY_SOCKET contain the socket number and socket address On failure these variables contain zero service service type number data size of the service private data area at least SVDATA port port number to listen on res socket number 1 n or SOCKET_ERROR SVinitiate xt taskl0 Allocates memory for a server task and INITIATEs it with the given xt returning the task s TCB address If memory cannot be allocated zero is returned SVterminate task Terminates a server or service task and frees off the task memory Does not PAUSE SVterminate task Terminates a server or service task and frees off the task memory 30 6 Service listening task SVmessage N caddr len Display a message to the current output usually the console in the form service lt given text gt on socket n The USER variables MY SOCKET and MY HSOCKET must contain valid data ServiceCreate service data port Create a new service listening socket StartService hs xt Initialise and launch a new service task on socket hs The a
11. from which the actual checksum is generated GenTcpCksum sk tcp len Generate the TCP checksum using a prepared header and socket data for the IP addresses Len is the length of the full TCP packet 23 7 TCP window size The words in this section are the defaults for transmitting the TCP receive window size to the remote end PowerNet queues input packets in the socket structure before passing them to the BSD layer Usually ACKs are delayed There are three ways to implement receive window handling selected by the equate genWinSize in the PowerNet configuration file e genWinSize 0 The receive window is always set to TCPWINDOWSIZE e genWinSize 1 By default we assume that if all the input packets have not been consumed by the time the ACK is sent the system is under heavy load and we do not want any more input for the moment This is indicated by setting the window size to zero Otherwise the receive window is set to TCPWINDOWSIZE Although this bang bang approach is very crude it works well unless many packets are being sent from PowerNet as can happen when web pages are served from memory e genWinSize 2 The word genWindowSize sk tcp is provided by you to suit your application See tcp fth for the examples genWindowSize sk tcp Given a socket sk and a TCP header at tcp calculate the TCP window size and place it in the TCP header This version is used when genWinSize 0 and implements the prev
12. my ftpDataSock 0 sockType FTPdataCr my_ftpDataSock sockCr create ConFTPdata X addr OUT managed by upper driver Function despatch table for FTP data channel I O OUT is managed by the upper level driver FTPdatalo R ipvec opvec Redirects console I O to the FTP data channel Use in the form FTPdatalo io Chapter 33 FTP Server 107 33 2 2 Command socket create ConsoleFTP X addr OUT managed by upper driver Function despatch table for FTP command channel I O OUT is managed by the upper level driver Init ConsoleFTP N Initialise the command channel Note that the F TP socket must have been set up and and the private service area initialised FTPio Select the FTP command channel as the console checkFTP ior Return non zero if there is an error in the FTP command channel 33 3 Sampling the command channel input ftpLine X Reset the FTP line input ftpLine X Mark that a complete line is available ftpBS en The backspace operation for input ftpCmdChar char Add the character to the command line being assembled FTPacceptable ore Process the next service input character on the command channel Input is terminated by LF and CR is ignored This satisfies the requirements of DOS Windows Unices and the TCP IP NVT Network Virtual Terminal 33 4 Diagnostic control 1 value FTPdiags n Set this non zero to get diagnostic informat
13. string gt hex caddr len n Converts an ASCII string as a hexadecimal number dec gt string n caddr len N is converted to a signed decimal string hex gt string n caddr len N is converted to an unsigned hexadecimal string with a leading character is c addri c addr2 u flag Compare two same length strings memory blocks returning TRUE if they are identical The comparison is case insensitive 34 2 Time and date These functions rely on the ANS Forth word TIME amp DATE s m h dd mm yyyy and the non standard DOW dow O Sun to get the day of the week create days addr String containing 3 character text for the days of the week create months addr String containing 3 character text for the months dow e Display day of week 2r n Display n as a two digit number with leading zeros Ar n Display n as a four digit number with leading zeros Time amp Date N Display the system time The format is hh mm ss dd Mmm yyyy AnsiDate N zone Display the day of week date and time If zone is 0 GMT is displayed The format is dow hh mm ss dd Mmm yyyy GMT IncludeMem caddr len INCLUDE a block of memory as if it were a file 34 3 Test code Chapter 35 HTTP Server 117 35 HTTP Server The Powernet HTTP server is a multi threaded server that can accept multiple connections limited only by available heap space For details of the server architecture see S
14. ETHER PKT blocks for ever because there is not enough space in the device for the transmission packet Theoretically this should not happen because 1536 bytes are reserved for transmission but 24 8 Attached EEPROM ee word offset Write a 16 bit word into the EEPROM at EEPROM address offset The EEPROM may not be present in all SMC91C9x implementations eeQ offset word Read a 16 bit word from the EEPROM at EEPROM address offset The EEPROM may not be present in all SMC91C9x implementations 82 PowerNet TCP IP Stack 24 9 Generic I O for PowerNet v3 and above The code in this section is only compiled if the equate fo GenericIP has been defined and is non zero The layout and usage of this structure is defined in the file COMMON ETHERCOM FTH create IPdevice gt Mylnit 0 initialisation MyTerm 1 shutdown gt MyRx 2 receive test gt MyRx 3 receive packet gt MyTx 4 transmit test gt MyTx 5 transmit packet gt MyGetAddr 6 Get device addresses gt MySetAddr 7 Set device addresses gt MySave 8 Save IP device state GetAddrs X ipaddr macaddr 0 For Generic I O IPDGetAddr function SetAddrs ipaddr O macaddr 0 mode Set up the Ethernet MAC and the IP addresses At present mode is always 0 but will be used in future releases to indicate data formats If ipaddr or macaddr are zero the stored data will not be cha
15. create SNTPServiceStruct addr Holds the UDP Service info to run the SNTP code on receipt of SNTP packets or idle on timeout Not that this must match the UDPService structure in UDP fth 22 8 Set up state machine gt doSNinit smSNinit setSNstate gt doSNconfigured smSNconfigured setSNstate gt doSNactive smSNactive setSNstate Chapter 23 TCP layer 69 23 TCP layer You will find the books TCP IP Illustrated Volume 1 Stevens and Volume 2 Wright amp Stevens useful when exploring the PowerNet TCP code especially for details of sequence and ack numbers 23 1 TCP configuration The configuration below can now be found in PNconfig fth O equ TCPDEBUG n Set this flag non zero to generate debug messages 1460 equ TCPDATASIZE n EGS009 Transmit buffer size of pbuf less tcp hdr ish 1460 2 equ TCPTXBUFFSIZE n Size of the retransmission buffer for a TCP socket One buffer of this size is allocated from the heap when a TCP socket is created 1460 equ TCPWINDOWSIZE NV n EGS002 TCP window size 100 equ TXDELAYTIME ms timer for delayed transmit mSecs default is 100 milliseconds 10 equ ACKDELAYTIME ms timer for delayed ack mSecs default is 10 milliseconds 5000 equ TXRETRYTIME ms timer for transmit retries mSecs default is 5 seconds 30000 equ TCPCONNECTTIME ms timer for incoming connections to complete mSecs default is 30 seconds 30000 equ TCPMSLTIME
16. see cleanFTP in SERVICES FTP fth MySVD X addr Returns the address of the task s service data Chapter 30 Support for TCP services 97 SVTib tib Returns the address of the TIB buffer for this task SVdone flag Return true if the socket can be closed SVbye Na Set the SVdone exit flag 30 3 Server assistance CheckSV flag Run by the service tasks to check whether the service task should be closed Flag is returned true if the service task should be closed 30 4 Service KEY EMIT and friends 0A equ AcceptChar char The character returned bySVkey below when an error has occurred This should be the character that SVaccept uses as a line terminator usually LF 30 4 1 Low RAM version In this version all buffering is performed in the socket layer This saves RAM at the cost of performance On a local area network the penalty may be significant it certainly is for Telnet SVkey flag Return true if a character is avilable from the service s client or an error has occurred SVkey char receive char Return a character from the service s client If the service s SVdone flag is set an LF is returned SVtype caddr len Send a string buffer to the service s client SVemit char Send a character to the service s client SVer Nez Send a CR LF pair to the services client SVflushOP N A compatibility NOOP in the low RAM version 30 4 2 High
17. 10 KEREN 11 35 MP caian reed dis e 11 30 Pira ted E ds S E OSEE 12 37 TOP configuration seen ee a a nee na 12 EE EE 13 3 9 DNS client ce fade a es 13 3 10 Servers and Services 6 ccc rn 14 3 11 End of configuration ae nee ee ea a Haan 14 4 Debugging Tools ee EN UP ud E PON 15 4 1 NMascellaneous ui Vereor d irte reto ei AE trei ads 15 4 2 Using the system console eee hem menn 15 4 3 Stack checking seere seaweed eg be be ae ee A EE ACE escis EOS 16 A A Celia coner EE Be a na EE EE 17 5 Network operations CPU specific 19 5 1 Network order big endian operations esee 19 5 2 Internet checkeum see hh re 19 6 Extra USER variable u kae an AY RR RAE NA 21 6 1 Common to all Gasks ccceieereterRRRR a SE STE ea da er pases 21 6 2 SLIP variables a a ERE ge FR Se 21 ii PowerNet TCP IP Stack T e Tr 25 GL GER OR te EE 25 8 QUEUE and buffer allocation 27 9 PBUF EE unseren 29 9 1 Introduction ae an Cages a ae 29 9 2 Data structure asien aa en ae 29 9 3 PBUPF handling eu ser a een ra ala 29 9 4 Queue buffer allocation and release 0 eee n 30 10 Queue diagnostic routines sss eee eee 33 11 System wide eouates 0066s 35 11 1 Application definitions ssssssssesssssssssss e 35 112 Standard TCP IP and Winsock values 42 09 sdessiizeresascs oi Rie SE ee 35 12 TCP IP data structures gie ach Ee ENEE EE E 37 12 1 Primary sUruct res i cp elle na pa Dan 37 12 2 SNMP s
18. 101 tOpidle arena 16 tepidletime eet ed wastage ate DE Pd Redes 13 69 tepidletimer a anne 76 tepinit EE 76 tcepmMaxretries wur Min 13 69 tcpmsltime ie euge hc 13 69 le TEE 13 TCPSOCKab i dics sce ne an wee gan 90 tcpstateQ viscosa isis 70 lee CET 12 69 telnet 0 089 aan e aa 10 telnetport oce eee enge 14 103 telnetserver o 4i illo lieb el ce gea 104 telnetserviCe c ose eR tate Pee EE s 104 telnettask unsinnig 104 term consolebuff u2222u 24 0umH2 e tinahi 119 termd t strean n ann samen 110 E DE EE 149 COTMUP nes an ae imus 147 149 E E EE 126 EE a sorit iaat hi 118 tevent b ginreceive icol sse deos 93 teventiirxdata cce dece cb merid e twist 93 LE WE RE 10 tetp_blocksize nn ee ln ee 93 tftp install oes ae 94 tftp packetsiZe Ive b eec obe ne reri 93 tftp Socket ee pecie ER ERR EE DESERER E 93 tftptasK eer eb Rh EE stance 94 En ANNOUNCE u ER RP RERO RES dr PR 103 itn A i d neta REP ina eae 104 EAU ura e 104 O 104 SE EE 104 todhcpstate icoscipbecesueteccaca sea 55 POSNEPStAate gh EE level bili ana 67 trans frame end 85 trans frame escape uoe erre EN nn 85 Vtransactlonf l l 2e coreeni anap mrpr randi ee 140 irha o oii ia ae EE 11 Lurnetbherpacketround eee 49 txdelaytime e re E ee See 12 69 LAMB ira iv ee Sraeeefrv e eds 56 UtxpD fiiziebtenj een heran 30 txretrytime iii re ich 12 69 EY PO EEE E E nein 113 udp hdr eicere een ot NEE 51 let EE
19. 34 WWW Support The source code for these string and time functions is in PNmisc fth 34 1 Strings leading N c addr u c addr u Modify a string address length pair to ignore leading spaces addchar char string Add the character to the end of the counted string append c addr u dest Add the string described by C ADDR U to the counted string at DEST is c addri c addr2 u flag Compare two same length strings memory blocks returning TRUE if they are identical The comparison is case insensitive str addri leni addr2 len2 flag Compare two addr len memory blocks returning TRUE if they are identical both in length and contents The comparison is case sensitive ISEARCH c addri ul c addr2 u2 c addr3 u3 f Search the string c addr1 u1 for the string ifc addr2 u2 If a match is found return c addr3 u3 the address of the start of the match and the number of characters remaining in c addr1 u1 plus flag f set to true If no match was found return c addr1 ul and f 0 Case insensitive for English left string caddr len char caddr len Given a string and a delimiter return the string to the left of the delimiter right string caddr len char caddr len Given a string and a delimiter return the string to the right of the delimiter extract string caddr len char caddr len Given a string return the substring between the delimiters ignoring leading delimiters jum
20. 59 dodlirenew i 2e iota ieee teria AE 59 dodhrequeSt ece li Ere v e ipe e 59 EE EEN 59 Godt connected circa eerie case ep ne ah 110 dodterror 2 o 9 A AA 110 dodtidle ocre da hs 110 dodtlistening anscur EIER aaa a 110 Godtreadsend 288 cra 110 dodtrecvwrit6 ss dae EE e Re E 110 Index doescapesequence nn nn 103 doftpacct lislaci stel iara Suter one ees 112 le WEE 110 le ee 112 e dee dukte ner 112 le 123 le EE 128 doincoming etc ER 47 domains zur Nail 137 le EE 149 len eh 148 le Oe EE 148 dorunechosocket ociosas oda ER Reds 101 dor nether e nee IRE VE ER RUE NES 84 doslipport i e ori ea NER 86 le EE 68 dosnconfigured venir na ann ene da neses 68 dosninit EE 68 dotcpacknowledge ccc cece eee eens 75 dotcpclosed 1221 aio 74 dotcpclosewait ataca deb neg 75 dotcpclosing 22 441 0 3 mia Poder i bes 75 dotcpconnecttimeout cc eee eee eee 75 dotcpdelagedack 0 e ee eee 75 dotcpdelageddata cc ccc cece cece eee eee 75 dotcpdiscondelay cies eR Reds 75 dotcpestablished e nece eerie 75 dotcpfinwaltli s nenne 75 lee E EEN 75 le 75 dotcplisten EE 74 lege ee ee RE erus 75 dotcpsynreceived iieloca dae seed EE 74 lege ET EE 75 doteptimevadt EE 75 dump Jine eee l e deere e 91 dumppairgs eceme RR Rer nennen 125 e EEN 141 EE 142 TI s eiseee gu REEL nn NODI EU H 101 BE nn ee een 79 80 lj 19 80 OCHO sci oss rese add a eae Re ants a eee 10
21. 61 21 DNS client The code in DNS fth implements a simple DNS client The focus of the design is on minimising overall RAM usage All data is transferred using UDP The code is compiled after the BSD layer because it makes heavy use of that layer The main documentation for DNS is contained in RFCs 1034 and 1035 The language is abstruse at best 21 1 Configuration These equates and data are only used if not already defined 1 equ DNSdebug N A Set this non zero to display DNS debug information during execution 53 equ DNSport porti The standard DNS port number on the server 3 equ DNS Kg Maximum number of DNS attempts if no response 5000 equ DNSms ms Maximum time in milliseconds allowed for a DNS transaction 512 equ DNS u Maximum size of the DNS payload variable DNSserver addr Holds DNS server or 0 if not configured yet 21 2 Queries and responses For the full details of DNS queries and responses see RFCs 1034 and 1035 What follows in this documentation is a small subset The header RFC 1035 4 1 1 contains the following fields 62 PowerNet TCP IP Stack if 1 1 1 1 1 1 012 34 5678 9012 34 5 o o o o 44 44 4444 ID dE o 44 44 4444 44 4 IQRI Opcode JAAITCIRDIRAIl Z RCODE o o than o tha o o tha tata QDCOUNT tha tha tha o o o tha o ooo ttt ANCOUNT tha tha tha than than than o tha tha ooo ttt NSCOUNT hott tha tha than tha than tha
22. Chapter 8 QUEUE and buffer allocation 27 8 QUEUE and buffer allocation Create the various IO queues needed O buffer FirstQ addr Address of first location in the queue RAM area Used by initialisation code queue buffer FreePBufQ addr Free PBuffers ready for RX amp TX queue buffer IPinQ NX addr Holds unprocessed incoming packets queue buffer TxEnetQ addr outgoing ethernet data buffers queue buffer TxSlipQ addr outgoing Slip data buffer O buffer LastQ addr Address of last location 1 in the queue RAM area Used by initialisation code QBarea buffer FirstQ MX addr Address of first location in the queue RAM area Used by initialisation code TRxBuffers buffer TRxBuffers addr The block of I O buffers Chapter 9 PBUF buffers 29 9 PBUF buffers 9 1 Introduction PBUFs are used to hold data which is received or transmitted as IP packets Rather than copy data repeatedly the system passes pointers to these structures In order to avoid heavy heap use these buffers are preallocated Collections of buffers are handled by the QUEUE data structures The function of PBUFs is to hold data that will be received or transmitted to a device Headers are added to application data The worst case occurs for Ethernet systems Ethernet header IP header TCP UDP or other protocol header s Application data Traditionally TCP IP stacks based on the BSD implementations use se
23. SMC NoER Initialise SMC chip init EtherTx Enable Ethernet TX module init EtherRx Enable Ethernet RX module etheradd gt CS addr Store 6 byte Ethernet address into SMC chip from memory buffer InitEther NES Perform a full initialisation of the chip enabling Rx and Tx and setting up the Ethernet MAC address from ETHERADDRESS EtherLink flag Return true if the Ethernet link is established AllocTxMem n mask Allocate n bytes of memory to hold a packet for transmission Return the contents of the ARR register or 1 for a fatal error GetTxMem n ior Allocate n bytes of memory to hold a packet for transmission WritePacket addr len Write an Ethernet frame to chip for transmission IsRx tlf Check if incoming data is present returning true if a packet is available for get_ether_pkt below DiscardRX N Throw away pending input packet due to lack of memory get ether pkt dest maxlen len Get pending receive packet to a buffer Note that data is valid only when ISRX returns true so that you must poll with ISRX before using GET ETHER PKT IsTx n flag Return true if a packet of length n can be sent send ether pkt addr len Send packet from supplied buffer The word will block until sufficient packet memory is available Note that you should read incoming packets regularly otherwise it is possible to get into a situation in which SEND
24. Servers True if any servers are required e g HTTP or Telnet 1 equ Clients True if client code is required e g HTTP or Telnet 1 equ http NV n nz to include HTTP True to include the HTTP server Note that TCP and server support are required 1 equ MemPages n Set this non zero to compile code for HTTP pages to be served from memory e g Flash O equ FilePages n Set this non zero to compile code for HTTP pages to be served from a FATfiler file system 1 equ telnet NV n nz to include Telnet True to include the Telnet server Note that TCP and server support are required O equ ftp NV n nz to include Telnet True to include the FTP server Note that TCP and server support are required O equ echo X n nz to include Echo True to include the Echo server T CP and server support are required O equ snmp NV n nz to include SNMP True to include SNMP O equ smtp NV n nz to include SMTP True to include SMTP 3 2 Diagnostics The next group of equates controls the generation of debugging information 1 equ diags n Set true to include diagnostic code recommended 1 equ XC X n True if compiled by cross compiler False if compiled by a hosted system such as VFX Forth for DOS 0 equ tcpdebug n True for lots of TCP debug info O equ ICMPmon X n True to monitor ICMP packets 3 3 Queues and Buffers 1520 equ PSIZE Keen Data size in each PBuf including all tra
25. a list of connections This equate defines the number of outstand ing connection attempts that can be queued The default is 5 which is common for Unices such as Solaris where it is referred to as the backlog value Many browsers request up to four connections for each page and queueing connections reduces peak RAM load in the heap Do not reduce this value to zero O equ SVlowRAM x Set this non zero to use the low RAM configuration for servers Setting this non zero increases the CPU load and may cause a significant increase in the number of small packets transmitted O equ SVsingle x When non zero the HTTP and Telnet servers accept only a single connection at at a time This connection is run from the listening task so reducing RAM usage and page serve performance For applications on single chip systems with limited RAM and in which the HTTP and Telnet servers are used only for configuration and maintenance by humans this is a useful setting especially where the application s RAM needs are high 80 equ HTTPPort X n standard is 80 Define the port used for the HTTP server The standard port is 80 15 1000 equ HTTP KEEPALIVE TIME ms The keep alive time in milliseconds used by HTTP 7 equ EchoPort n Port on which Echo server listens 5023 equ TelnetPort NX n standard is 23 Define the port used for the Telnet server The standard port is 23 but 5023 is the default set for PowerNet as most appl
26. and execute the first receive action for the port If no association is found try to route the packet RxUDPPacket pb udp hs q bf Process a received UDP packet Chapter 20 DHCP and BOOTP 53 20 DHCP and BOOTP The code in lt PNet gt DHCP fth implements a DHCP client according to RFC2131 See also RFC2132 and RFC1542 Do not attempt to modify this code until you have absorbed these RFCs If you do not have a DHCP server on you network there are many available For Windows PCs several users have recommended the haneWin DHCP Server from www hanewin net O equ DHCPdebug NX Set this non zero to display DHCP debug information during execution 20 1 DHCP BOOTP state machine The DHCP system is controlled by a state machine which is run whenever the timer fo DHCPtimer times out The action performed is responsible setting the next state and updating the timer The state machine actions are performed by DHCPidle which is called in the service task States of the DHCP state machine See RFC2131 Figure 5 below for the transition diagram 54 PowerNet TCP IP Stack gt lt INIT gt INIT REBOOT DHCPNAK 4 _ Restart lo Ames EE DHCPNAK Discard offer Send DHCPDISCOVER Send DHCPREQUEST DHCPACK V not accept Send DHCPDECLINE
27. and facilities for routing input and output through the normal Forth KEY and EMIT wordset variable SVchain addr Holds the tail of the service chain 64 equ SVOB n Size of a service output buffer A value of 64 or 128 bytes is sufficient to provide satisfactory output for Telnet 64 equ SVIB KEE Size of a service input buffer 256 equ SVtib N n Size of the service s TIB area struct SVdata len Defines the common data in a service specific data area int SVlink link to previous service X N B MUST BE FIRST int SVtask task that runs this service int SVskit socket used by this service int SVsendflags TCP override flags for lower layers int SVdone set nz to close service int SVappClean sv sv application specific clean up xt dup equ CSVdata size of core service data end of core structure SVtib field SVtibBuff service TIB e g for Telnet dup equ MSVdata size of core TIB service data end of core plus input buffer SVlowRAM O if int SVOB number of characters in SVOB SFP002 SVOB field SVopBuff service output buffer SFP002 int SVIB number of characters in SVIB int SVIB offset of next character in SVIB SVIB field SVipBuff service raw input buffer then end struct The field SVappClean contains the xt of a word cleanFTP sv sv that frees any aqdditional resources that are not released by free the service data area For an example
28. are ER 10 131 EE ner 113 MOS anna eek menden 113 TEE 108 116 MSSOP EE 69 my D SE he EE einen 105 my GE 106 Or RE 106 my ftpdataip EE 105 Or E E tiens oi 105 my er EE 105 my ftpdatastate EE 105 my EE 106 MYA tpi dida 106 my e HEEN 106 My ftppassive nn ei 105 my tt pqui t rt 105 Hy LCPSECD e Aas coisas Eeer 106 My E EE 105 MYSV sense erste era ee Seek 96 N A chen 16 E GEET EE 142 nestle ine 91 Degdatasocket cece eee 110 NEXCDOUNGATY ENEE eee e e bh eer 146 nextbyte c ern ea oa 147 o e A tians in peneira Eia ni Sa Ra 124 E TEE 84 DEXTSOck nennen anne 41 EE Al E e EE 30 DEXTWINSIZE cu era ead er ERR QUE HE A gan eL E 113 EE 117 no Var Set 121 NOCANTOUTE venis A 47 NodhepserVer u0 na nennen ee hemmen 56 162 e i hie in ae de alada 112 noO0thef 2 21 p 4 ee 47 DOPAE O iii ende 131 ROSOCket EE 99 DOLL Ad 146 notboundary viii ee 147 notcphandle u n 2 nee 69 e unsere 126 mumtreepbut EE 11 D nsockets u senken EIERE EE UR EREEPEER 42 H merxb uffers 2 11 O OCE E EE 148 ee A ee ee 74 P packettask uses ana 47 G EE 12 Pagedirt une ae 133 EE EE 125 PalrvallS ee pete RTT RR RD e RARE 125 P ranreg est list ce 58 parse name i i 1e aaa erg 111 G E E OR 111 E dE EE 128 parsetelnetbuffer cece eee eee 103 PAP ERTS nee ee 148 paS Sherer aoee ta naher Ae Ae 112 TEE EEN 113 le TEE EE 47 pPbdatalen EE 30 pbdatastartil le e Es 30 Pbhdrlen ino i
29. been processed During this time any following SNTP packets will be discarded 68 PowerNet TCP IP Stack SNTPPSend 4 pb ipaddr Send SNTP data as a UDP packet The parameters are pb a pointer to a PBuff containing the UDP data and ipaddr the IP address to send to SendSNTP pb sntp Send an SNTP message 22 6 SNTP state selection Each state is controlled by three values defined here e Entry delay delay before state is executed for the first time e Period period between repetitions of the same state e Count number of repetitions before smSNcount reaches zero goSNTPInit KE Go to the smSNnit state stop SNTP activity and wait for parameters from the calling app goSNTPConfigured Kn Go to the smSNconfigured state start the SNTP process goSNTPActive Go to the smSNactive state SNTP data has been received doSNinit Ne SNTPauto nz Do nothing until SNTP server has been set either manually or by DHCP and then start SNTP doSNconfigured N Configured state has timed out send SNTP request and wait for response or timeout doSNactive active state has timed out revert to configured runSNTP N Start the SNTP process and wait until a valid time has been returned 22 7 Receive SNTP packet RxSNTP N pb Process received SNTP packets When we get here we know this is from port 123 and that the Ethernet packet was either addressed to us or was broadcast
30. been no timeout echoResponse hs Read the input and respond echoClose hs Close the echo connection EchoService hs Service an Echo connection DoRunEchoSocket The Echo task task TcpEchoTask addr The task running the Echo socket RunEchoSockTask Start the Echo task Chapter 32 Telnet Server 103 32 Telnet Server The Powernet Telnet server is a multithreaded server that can accept multiple Telnet connec tions Local echo is not required on the client The model used is described in SERVERS FTH For testing please be aware that the standard Windows Telnet client is very slow A nuch faster alternative is HyperTerminal Personal Edition from http www hilgraeve com 32 1 Telnet specific data These data definitions are required by each Telnet server task The data is allocated at the start of the task and released when the task is TERMINATEd The chain SVCHAIN links all the service tasks 5023 equ TelnetPort NX n standard is 23 Define the port used for the Telnet server The standard port is 23 but 5023 is the default set for PowerNet as most application Telnet servers are private Moved to PNconfig fth 32 2 IAC handling Not yet implemented DoEscapeSequence addr n Process a character sequence with the TNET_IAC escape character at addr returning n decoded length At present these sequences are ignored ParseTelnetBuffer numchars Process incom
31. cued El bed a enge dd 64 22 SNTP client EE 65 22 1 SNTP equates and structure 65 22 2 SNTP Confipuration zb ua ge Da ea 66 22 3 SNTP state machine 66 22 4 State machine utilities u un NEEN ENER aer ren RR RR A re eee EE RA 67 22 5 Outgoing message tools 67 22 6 SNTP state selection nennen 68 22 7 Receive SNTP packe 68 22 8 Set up state machine une san ee 68 23 TOP nee ee a EXP ER re 69 23 1 TCP configuration ee es E 69 23 2 Unknown socket reouests nennen 69 23 3 TCP structures and equates 0 00 cece cnet e teen nee ennnes 70 23 4 TCP structure creation and deletion 0 6 c cece eee eee eee eens 70 23 5 TOP header EE 70 23 6 TGP checksum handling sessar inciri hake ead Rem in neh EE 71 23 7 Kee ii 23 8 TCP transmission primitiven l 23 9 TCP state GEIER A en ee ae a 73 23 10 LISTEN connection queues ssssssssee eee 74 23 11 TCP state handlers iss desea aan 74 23 12 TCP timer handling en d Rea element 75 23 13 Primitives for the BSD layer 2 00 cece tenet teenies 76 23 14 TCP mtpalsation ene e 76 23 15 Checksum test Code ann en Eech dl en aan SERIES bee 76 iv PowerNet TCP IP Stack 24 SMC LAN91C92 4 6 Ethernet Driver Code TT 24 1 Introduction essgaoedon da a qued BRI iud add qucacpeRr tru fada TT 242 Hardware golcha8s8 2 4 2 socks bu ee D as padded eden are Ha adu idee E dapes TT 24 3 CONSUL RE IR 24 4 Constants 3520 einen kei a NP RUMP REP Rer eee 7
32. debug DNS ici ee tod 16 debug decimal et tr 15 debug AO cir ran 15 PowerNet TCP IP Stack debu g S N sn samen en ae 16 debug gt pos NEE EIERE Ae 15 debug_count amp type 6 ccc eee nen 15 debug CP 22 sige deka ea gu stages 15 debug d mp c e e E EE ERE EREE E 16 TEE 15 deb g Space usa eee ee een 15 debug spaces iia b uev Re Er eh 15 TA A reres vere erani aie eei a aA 15 TEE 116 A nire a i EE 121 TR EE 114 geg ee SIE EE As 12 defro te d EE dE era AN ASV Cia aria a EFE a Ee REESEN Maa ube E 113 della ca aa d 39 dequele ie iocuinasis cari is AR 25 dev MAS une nen 11 AAC EE 140 Gli A wine veaceok bomen reas nae 55 dhep EE 55 AAA A ne Peek 53 dhepf EE 56 Ihcpidlie u ace pe ohare aceon aes 55 dhcplease spice rra 55 dhcpleasetimer e222 ccc es ck one rare 55 dhceppacket EE 59 dhcpport EE 59 dhepserver EEN 56 ele Ee GE 60 fe EE 55 EE 10 CH 16 discallsockets nr a eac inot tiek 88 discardrx success 81 EE EEN 42 discardtftp EE 94 EE GE 110 disconnect un peite sce snug Pa neuere handen Panes 88 ABS ia 140 ANS AUCO u anne nee 9 A A sieck ki EtES NEKE EEES 13 61 Inside ersehen 64 dnsSpOEFti EE 13 61 va ee 64 uk VI EE 64 dnsservef u ne een 13 61 d clength sans near 124 a ehe 124 dodharpcheck eder ea 59 dodhboutnd AAA obe Dan Panes 59 dodhCpopt siie e rere rr e namen 59 ee KE KEE 58 EDU eege nee 58 dodhrebind a i e ce ee 59 dodhrebooting wie bei een nat
33. derive er do e als 128 TUMAINCOMING eene 4T 48 r nservicesS 220 2 59 inneren T ale EE i runsliptask 2biw ieew t ont deans dee idee 86 r nsntp iencibene hie eb R eb hb RES 68 runtelnetsocktask esee esses 104 IxdhCp iiiiec e de e n EE 59 rxetherpacket c ua e kinau me E REFER 83 rxetherpkt ee r ana ee asian Pas 83 rxicmppacket c su n n e her e ndhi ends 43 rxippacket i a e e ennast nenn rae e eph 48 EE 68 ER DEER a di 75 rxu dppacketo inel l BPPIeRRIHEMR ER en 51 S SacCept o x eng a aad ee abenpi a d Eee EAS 89 Savesktrem i eese sei a e bee Race 8T scandhcpopts 2 s e ud a tr e E eR 59 Script code a eg e ree EPLERERERE RS 123 Index SCLIPtengine 205 sess c dedos s snis an u KEN 123 searchpage iieccnilic4ev SE AE A 133 SeIQua EEN 89 send demo emall EE EE 137 sendsether cece enses 83 EK TEEN 47 sends I pushen eese R een ee ee ane 85 send ether pkt ss dees dee ine a ne 81 send frame end char cece cece eee ee 86 send_frame_eSc_Char cc cece eee cece eee 86 SQndack gt t EE 72 sendarprequest 9 Zeche SE SES metered eats 49 sendbody mclaren SPI 137 sendb ff gt t p iore prirent dd ENER SEA ine 12 SEnddatagram zucseasne mans siria Ren eg 51 ee TEE 58 Senden occas ne an tee nad ra 58 senddiscove iaa A ag nenne 58 sender dein en 137 Send ratuitousarp 6 cece eee eee eee 49 sendnoSOCk t c iskaa een nn 73 SONOPLOV A ee 127 E UE EE 58 Sends li E 2c
34. echoclos8 cerkemk GR DESEE RETIRER REESE 101 echoest debe ke deb EE HER eh RR eua 101 echoportf EE 14 101 echo Te questa dad RR ER 43 e TEE 101 ECH SEL VICE ne ann 101 SCH WALL ina ne Peer mare 101 BE ee near 81 EE 81 de 78 EE 139 eiSrQ cover SE Sege E EE marken 80 SMM ae ne 80 enpty route r Ree ai 46 le E EE 85 ST A rir ieni enDi E TEET EOE 80 EE 6 45 140 E TEEN 25 159 Une nee 12 14 66 69 103 120 OSOS isis 80 SECT u en nen ne 80 ether A EA ANa EIE iDN EAEE 37 ether mask 0 ccc cece eee n du ether port 11 49 TE KEE 81 etheraddress ceu nern 6 78 140 etherarppacket See dree dere re vx 49 A een een E etbherbcastaddreses 0 c cee eee eee eee 49 etherippacket un Ree e nee 83 etherlink i u 81 ethernet a Deh sanken 9 o e sseecenenx sherewered side ias 142 ethertask cinri eben bn ae p o wade pons 84 etherunk ddress eee aee rte repete 49 WI ceste tea epis ee AER e qot guae Pup EE enses 80 OUO Lco dem eso cts d be decime ha Saris deme 80 execchain ie Santee A Bae teens 39 expire rOutes ervxoieersc9 x a e spacer nei 46 EE EE Weser d vb Ve OR SAMT 45 extract StrlHg il ocil een o 115 extractvalue o inue ue kb RES E DEEE 124 F fastCpu ene ev area bai ER RE EE 149 filename EE 147 EI lepage ae na 131 RE 10 131 Pilequery anne nee ann 127 Filesceript unsern 127 eege A dee greng EE 127 find hsocket port 41 find hsocket tepport eee 41 find route erde
35. enough heap space make this at least twice TCPDATASIZE 1460 equ TCPWINDOWSIZE n TCP window size O equ genWinSize X u Selects the strategy used to generate the TCP window size advertised by PowerNet PowerNet queues input packets in the socket structure before passing them to the BSD layer Usually ACKs are delayed There are three ways to implement receive window handling selected by the equate genWinSize e genWinSize 0 The receive window is always set to TCPWINDOWSIZE e genWinSize 1 By default we assume that if all the input packets have not been consumed by the time the ACK is sent the system is under heavy load and we do not want any more input for the moment This is indicated by setting the window size to zero Otherwise the receive window is set to TCPWINDOWSIZE Although this bang bang approach is very crude it works well unless many packets are being sent from PowerNet as can happen when web pages are served from memory e genWinSize 2 The word genWindowSize sk tcp is provided by you to suit your application See tcp fth for the examples 1460 equ defMSS len Define the maximum segment size packet size less transport IP and TCP headers On a LAN 1460 is the default For WAN and broadband access lower values may be appropriate e g 1420 The values sent in the SYN and SYN ACK packets may be modified by intermediate routers 5 tick ms max equ TcpIdleMs ms Interval in miliseconds
36. for data assembly CGIend flag Return true if the body content is exhausted CGIkey char Read the next character If the content is exhausted or there has been a socket error LF is returned ReadKey ior Read the key portion of a key value pair returning zero for success ReadValue ior Read the value portion of a key value pair returning zero for success 35 8 2 Application words These words will mostly be used inside ASP scripts Note that the key and value strings are not URL decoded You can use decodeURL to perform the decode and copy in one operation It is assumed that you control both the RAM usage of the PowerNet server and that you control the scripts it serves We are not trying to reimplement the Apache server To read the pairs call ReadNextPair and inspect the return result If it is good examine and process the PairName and PairValue strings Because you control the scripts it is sensible to use key names that do not require URL decoding Especially for user input some key values may need decoding e g email addresses This decision is left up to you ReadNextPair ior Read the next key value pair and return 0 on success 1 is returned for an unexpected end of input or socket error and 2 is returned if input was truncated before the key terminator PairName caddr len Return the last key value pair s key text PairValue caddr len Return the last key value p
37. for up to SMTPWAIT milliseconds SMTP Error hsock flag Read a response back from the SMTP server via the supplied socket and return a TRUE flag if the server s response indicates an error SMTP Connect ipaddr port hsocket O Attempt to create a socket and connect to an SMTP Server IPADDR is an ipaddress and PORT is the requested port SMTP Servers are almost always found on port 25 decimal SMTP Disconnect hsock Disconnect from a SMTP discussion by closing our socket SMTPWrite hsock c addr u Write a buffer out via a socket SMTP Write X hsock c addr u Write a buffer out via a socket Used to send text strings to the SMTP Server create crlf addr A counted string holding a CR LF pair SMTP WriteLn hsock c addr len mode As SMTP Write but followed by a CR LF pair Mode is a TCP flag which is normally 0 but is set to TCP_PSH by SMTP WRITEFIELD below SMTP WriteLn hsock c addr u As SMTP Write but followed by a CR LF pair SMTP WriteField hsock field addr field len val addr val len flag Write a field to the SMTP server In this case a field consists of a field name and a text value followed by an EOL Any field written prompts the server to make a response which is checked for an error condition to form the return flag Chapter 38 SMTP Demonstration 137 38 SMTP Demonstration 38 1 Configuration These definitions should be cha
38. if primary headers have been read WebPageDef N struct Return the address of the file page definition structure This word is forward referenced TestWebFlag mask n O Test the mask bits in the service s status flag cell SetWebFlag N mask Set the mask bits in the service s status flag cell ClrWebFlag N mask Chapter 35 HTTP Server 119 Clear the mask bits in the service s status flag cell SetHttpTimeout time Set the timeout target for HTTP A value of 0 indicates no timing GetHttpTimeout time Get the timeout target for HTTP A value of 0 indicates no timing 35 2 HTTP vectored I O 35 2 1 Stream socket The HTTP server establishes its own generic I O based on that in SERVERS FTH in order to handle special character processing in the future create ConsoleHTTP X addr OUT managed by upper driver Function despatch table for HTTP I O OUT is managed by the upper level driver HTTPio Select HTTP as the console Init ConsoleHTTP N Initialise for console I O by HTTP Note that the HTTP must have been set up and and the private service area initialised 35 2 2 Output to a memory buffer For correct handling of error responses some browsers require the HTTP Content Length field to be defined This means that the output length must be known before sending Consequently error messages are buffered before transmission N B All output to the buffer is unchecked for overfl
39. matches the last boundary condition return true otherwise return false ReadBinFile flag The separator line between the part headers and the binary file has been read Read the binary up to the concluding part boundary If the boundary string is the last one return true otherwise return false 40 4 3 Part scanning In this example the only form part we need to process is the one containing a binary file We detect this by parsing the headers for the pair Content Disposition form data name appfile filename foo Content Type application octet stream We assume that a valid file is present when e the form data marker is present e the filename is non null e and the application octet stream marker is present variable OctetStream addr Set true when Content Type application octet stream has been received variable FormData addr Set true when the form data marker has been received formData caddr len Check for the form data marker appfile caddr len Check for name appfile doPdisp caddr len Check the given content disposition line doPtype caddr len Check the given content type line create PartHdrs addr Table holding the headers to be processed by part header handlers CheckPartHdrs x Check the data received in the part headers and return z indicating what to do with the part If x is zero just skip the part Chapter 40 POS
40. page from its name caddr len returning the data structure address struct and a type code type If the page cannot be found both return values are zero The action is to look up the name in the HTTPpages voc vocabulary and extract the page type from the PAGEDEF structure 132 PowerNet TCP IP Stack 36 3 Executable pages xtPage xt lt name gt struct type Creates a page which later executes the given action e g doNewApp xtPage NewApp asp The specified action must have the stack effect qaddr qlen where the input is the rest of the line after GET or POST 36 4 Memory pages MemPage lt Forthname gt lt filename gt struct type An INTERPRETER definition that creates lt Forthname gt in the HTTPPAGES VOC vocabulary and a PAGEDEF structure and then loads file filename into the dictionary as data At run time the address of the PAGEDEF structure is returned When the HTTP server is running it will serve the data in response to a GET request for Forthname INenPage home htm IPSTACK powernet htm 36 4 1 Example memory pages These files are compiled by default unless the equate TestPages exists and is set to zero MemPage home htm IPSTACKY TestPages home htm Creates embedded memory page HOME HTM from the data in IPSTACK home htm The leading is required as it is not removed by the command parser MemPage bgimage jpg IPSTACK TestPages bgimage jpg The backgr
41. performance version SVIBuffer N addr Returns the address of the input buffer for this task SVOBuffer addr Returns the address of the output buffer for this task isSVInput Read any available characters from the incoming TCP stream into the service input buffer SVkey flag check receive char Return true if a character has been received by the server or the service must be closed SVflushOP SFP002 98 PowerNet TCP IP Stack Send current buffer if not empty by passing it to the socket SVflushOP is used by SVkey and SVkey so that pending output is transmitted If your code does not call either of these e g through the Generic I O you should add SVflushOP to your code where appropriate SVemit char SFPOO2 Send a character to a client of this service Service vectored I O SVkey flag check receive char Return true if a character has been received by the server Any pending output characters are sent SVkey N char receive char Return a character from the service s client Any pending output characters are sent first If the service s SVdone flag is set or a socket error has occurred an LF character is returned SVemit char emit char Send a character to a service s client SVtype caddr len display string Send a string to a service s client SVcr X display new line Send a new line sequence to a service s client 30 4 3 Generic I O devi
42. releases so we suggest that you keep changes in a separate file 36 1 Configuration The following two equates are only used if they are not already defined 1 equ MemPages n Set this non zero to compile the memory pages code 1 equ FilePages n Set this non zero to compile the file pages code 36 2 Data structures Since Web pages may be stored in a file system other mass storage or memory a common data structure is used based on the needs of pages stored in CPU memory Pages stored in CPU memory are identified by name in the HTTPPAGES VOC vocabulary Executing the word returns the address of the data structure and its type struct PageDef n The structure used for a page definition The following equates define the types of pages that are available They are stored in the PG TYPE field of a PageDef structure O equ NoPage 0 Page not found or unusable 1 equ FilePage n The page is in a file 2 equ SMemPage n The page is in memory e g Flash and need not be released 3 equ xtPage Avec 1 The page is created by executing a Forth word whose xt is in the PG addr field 4 equ HMemPage n The page has been loaded into the heap vocabulary HTTPpages voc Kaes The default vocabulary used to hold page data voc gt wid xt voc wid Return the WID of a vocabulary whose XT is supplied This definition is implementation dependent FindVocPage caddr len struct O typelO Find a
43. that are not so forgiving a few extra commands are supported The FTP server has been tested with e Ipswitch WS_FTP Pro 2007 This has been our Windows FTP client of choice for many years Windows only e WinSCP A functional free tool Windows only e FileZilla A functional free tool Windows Linux and Mac OS X The use of the FATfiler file system code is assumed Because this is not a fully thread safe file system and only has a single working directory for all threads this FTP server is not suitable for use with FTP clients that assume a Unix style operating system Such clients include the FTP client built into Finder on Mac OS X FileZilla works well on the Mac as well as on Linux and Windows 33 1 FTP data struct FTPdata n The standard service data structure is extended for FTP cleanFTP N sv sv Clean up an FTP service block before it is released my ftpState addr Holds the state of the FTP system my_ftpPassive NV addr Holds the passive flag my_ftpBinary addr Holds the binary flag my_ftpQuit NX addr Holds the QUIT flag my ftpDataIP addr Holds the IP adddress of the data channel my_ftpDataPort NV addr Holds the port number of the data channel my_ftpDataSock addr Holds the socket handle of the data channel my_ftpDataState addr Holds the state number of the data channel 106 PowerNet TCP IP Stack my_ftpDataFile NV addr
44. up operations 39 4 1 Displaying and Entering IP addresses GetIPaddress ipaddr INADDR NONE O Get an IPv4 address from the user INADDR NONE 1 is is returned if the entry is bad and zero is returned for a zero length entry Use IPv4 ipaddr to display an IP address GetIPaddress caddr ior Get an IP address from the console in the form 192 168 0 55 base is decimal A good result is saved at caddr and ior is returned 0 for success or a null entry or other for a bad entry Note that caddr will always be modified GetIP caddr ior O success Get an IP address from the console in the form 192 168 0 55 base is decimal A good result is saved at caddr 39 4 2 Displaying and Entering MAC addresses MACaddress caddr Display the MAC address at caddr getByte addr char addr Collect an integer delimited by char and store it at addr returning addr 1 getData N addr char n 142 PowerNet TCP IP Stack Collect n integers delimited by char and store the bytes sequentially at addr GetMACaddress caddr ior O success Get an Ethernet MAC address from the console in the form aa bb cc dd ee ff base is hex The result is saved at caddr and ior is returned 0 for success or a null entry or other for a bad entry Note that caddr will always be modified GetMac caddr input new MAC address Get a new MAC address from the user console 39 4 3 Setup proper y n f
45. used fl the flag bits to use opt ol are the option pointer length if non zero dat dl are the data pointer length if non zero res SOCKET_ERROR on failure or no of bytes sent on success SendTcpOpts sk fl opt ol SFP005 Send a packet that consists of the flags and options without data SendTcpFlags sk fl SFPOO5 Send a packet that just consists of the flags without options or data ForceTCPReset sk SFPO12 Force a socket reset and then close the socket sent lt txbuff Sch len Bump the transmit buffer after len bytes sent from txbuffer SendBuff gt TCP cb sk nb Send any buffered data out No action is taken if there is nothing to send Use this only in the TCP state machine SendAck gt TCP 4 cb sk nb Send any buffered data out with an ACK skValid sk flag Returns true if the socket structure is a valid TCP socket skCanSend sk flag Returns true if the socket structure is valid the socket is in TCPS_ESTABLISHED state and has not exceeded the maximum number of retry attempts sendtoTCP hsocket bf len flags bufflen sk cb nb res Move user data into the socket s transmit buffer waiting in the word until all data has been transferred to the buffer This may involve packet transmission while waiting for the buffer Chapter 23 TCP layer 73 to empty Because the socket may be closed during transmission the socket must be check
46. 1 A p RTEA E EEE RE 51 Tappfile estkse enron pep E E RP IE DUS 148 Index Tbadsocket i EE 42 KEREN 124 AS ue ee inne inkl 127 PAUMP EE 15 Tformd ta en ne ee hae dames 148 WET EE 39 Tftpacceptable cei eee em es 107 multipart 000 deve desde ana ee Seth 124 KEE 87 KEE E E 87 KEE 87 KE 87 TSELVICEC LOSE ernennen 100 Termica lara ad 100 TetackempPtriuianriniania ciar dn Et De PERPE PESE 16 PSVRILT 2 0 een an 100 A nenne ti ER BEE 19 Oia a aa 33 PP RECTE 15 ftp a nee ne naar 107 ftpdatalO ee gp REIR E PERPATA REL ORT 106 hd D nee 120 IER AE ER i EE 133 EE 40 109 EE 93 94 1 HEEN 121 4 EE 93 ADOS ia de een 80 lolon aE engen 113 aborttftp li E E SE eee es 94 EERSTEN 97 ACCEPtdhcpin ivi nic cia eee 57 acceptglvenii eisneixizsca e ninimi in im sisne 57 TEE 112 Ekel erte erbei inte 12 69 acktxDYtOS rita e hnn E E 75 add besocket 0 ccc ccc cc cece eee ence eee 41 ie RE 46 addchar EE 115 E EE 147 adddhcpopts i eie n dg eL ph DERE genes 58 addendlink a ua sn aa nee 39 addeth rroute eve p pe eR d RR REC EE 49 addfileupd lie en e Rene thv 149 157 TN nes ee neither 39 add pd scis cete bobo e e pL Md 146 149 aligned coccion ia deb Irene eR SG 33 ERR e ee ERO at e vens 30 ALLOCEMMCM 55 43 ccc evento nigh eed DA ET ds 81 OPPCNG ebe SC wate vane EE REEL 115 Kee 37 arp Pda daria a AE 37 ee TEE 11 Aarpforme 22x 20a a era 49 askforetherroute
47. 2 SKIPAUSG EE 64 A een ede died Mak dened SERRA 64 Skm reip EE ral SECO N Keren et ae Sh seta aaa media ee 42 SkValid ia en o a 12 BIP nee nee euren 9 SET Mas naar 11 slip rx timeout ee ee 85 a e 86 CR eet EE 86 a EE 86 Sn aloe ee ee near en ea 40 109 EEN OC HEET 94 Scl6 rien IM EE 77 SMEVECHOF een ee 82 SMAGHACELONS nai EEN ai de EEN 55 ENEE 55 smdhst te miii seniii e Aeg 55 EE 131 te o A ironi tere e re anae 94 SMi RR EE 94 EE 94 smrxdata csi m ee et Re Rr RR EX d E 94 smnsnactionS cie ka eb EE REEF ERE E REPE 67 SMOC iii E RES 67 Smsnstate u nenne ne 67 SMSLALELX cua een 94 SUstarttx nu ee sivas en 94 SMS een 40 109 SMEPFECONNEeCEt nn nee een 135 smtp disconnect liseeieiveveen ee 135 Ss rtie re ES ER ECESE 135 Stp WAIT ge Eeer 135 uho oaea EE 135 smtp writelleld nui acera teases 135 EMP MO ea o e 135 SINED PET 10 Smtpdiags ue Ree deans tate bandon E EE 135 SMEPPOTT ee EE nen fob domos 137 SnbpServer c ca esa pie re 137 SMEPWAIL ee uve dise IE Dd dE 135 ee Eh EE 94 E EEN 94 EE 82 STIER a ee en ee ee 78 EE 10 hee GEET 65 EDERT Ee ENEE aes 9 SntpdebugT sil asked EE 65 sntpidle lw Re RR het EELER 67 EE 65 EE 67 164 sntpservicestr ct cecovcoioionnnicra eniai 68 SNCPCIMEH nennen een 67 Sockaddr niic es ew AER Da SA EE 106 SOCkeNit4 2 e oss e eol a 106 SOCKET i sooo er EE AT Medias 42 88 Socket errOr vu ac yu Sows See nd RE qu 35 socket list l st 21 4 9 E
48. 224 User Agent Mozilla 5 0 Windows U Windows NT 5 1 en US rv 1 8 1 14 Gecko 20080404 Fir Accept text xml application xml application xhtml xml text html q 0 9 text plain q 0 8 ime Content Type multipart form data boundary 805274458224 The Content Type and Content Length headers are essential The first tells us that this is a form response in the style we need and the second tells us the overal size of the response If you need security you can use the Referer field to indentify which host and file contained the form In particular the Content Type field contains a boundary string This is the only data that identifies where one part of the form starts and ends Chapter 40 POST handlers and HTTP updates 145 40 2 Form boundaries The boundary string is defined by the browser The PowerNet server has no control over it However it is mandatory that the string is not contained in the data The example below shows three versions of the boundary string 805274455224 805274455224 805274455224 The first is the separator defined by the boundary portion of the Content Type header Under some circumstances this may be delimited by characters which are not part of the boundary string The second is applied to all part separators except the last one The second form is the same as the first but with two leading cha
49. 41 3 Recommended reading TCP IP Illustrated volume 1 W Richard Stevens ADDISON WESLEY TCP IP Illustrated volume 2 Gary R Wight amp W Richard Stevens ADDISON WESLEY InterNetworking with TCP IP vol 2 Douglas E Comer amp David L Stevens PRENTICE HALL Net BSD Sources Net BSD Man Pages The Linux sources will do fine http www Linus org Chapter 42 Licence terms 153 42 Licence terms 42 1 Distribution of application programs Providing that the end user has no access to the source code compiled applications contain ing the PowerNet IP Code may be distributed without royalty An acknowledgement will be gratefully appreciated No part of the target source code may be further distributed without permission from MicroProcessor Engineering If you need access to an open Forth interpreter for engineering and maintenance access only this is permitted after a free of charge letter of permission from MPE to ensure maintenance of our copyright Use of the Forth interpreter for server side scripting is permitted with the purchase of the PowerNet code If you need to ship open source or wish to check what constitutes engineering and maintenance access please contact MPE 42 2 Warranties and support We try to make our products as reliable and bug free as we possibly can We support our products If you find a bug in this product and its associated programs we will do our best to fix it Please check first by fax or email to s
50. 45 Eindfilepage iscsi SEN nennen ER EE 133 EE 121 Eindv cp age EES nn nad deans PUR SEN nade 131 Fionre d nee nee e 88 firstportnunber ira net 13 42 Firstgate ae 21 EE 139 flushdebug eceesnervene aa 6 E oa ae arra ass 42 E e 12 TOMA ii daa 148 OH DEER EE REENEN 124 forth Scri nennen nenne 117 frame end Zu aussen teo bi qe are 85 e EE 85 e e een 121 Freeconnd EE 42 e LEE 30 EE 121 E ET EE 42 a EE 10 o E E EE E TETT 107 ftpabort426 nue ne asian 111 age 111 pe o o CN O aneiie a dann eE ARa Ea a E a 107 ftpendp rti unse net dran 14 ere Keen qug e RR 114 160 a E TEE 110 a DE RE KEE 110 ftpdataport nennen 14 age KEE 107 ERC rer 112 a EE 107 A uses einen 114 a E TEE 114 Ftpservice iaa Bee rec 114 PEP CASE ann sen EE 114 FED V O C sie rd 112 at OR e EE 147 G gendnsnane merida 64 gendnsghead nannten a D nd 64 gendnsquestion EE 64 BEHEFICIPT ana een Ee 9 78 genlabel EE 64 gentcpcksum iii elessenia ol nenn naia Rd 71 EE HEEN 71 EE 12 got ether pkt iesese it e 81 get socket addi cesses eese 41 get socket inq i e E pe err 41 get socket outq isuuesdadu dae iieri hus 41 get tcpstate io lecce pei RR IA RP IIS 88 EE 82 getbootpserveraddT cece eee eee eee 58 ROUTE EE 141 EEN 142 E ior doe scis we du wen deer ET 141 getdestparam ic e lle rae eer rte dudes 111 getfreeportn ins an 42 gethttptimeout 2 EN niii tortini en 119 EE 141 getipaddress oc cai er
51. 8 24 5 Hardware Interface TLaver e hen 79 24 0 Diagnostics oce tk BB ae ei 80 QA Driver Bayer os ee ee ee ee a tee ee 80 24 8 Attached BEPROM 405 Eee een ann a bad Fan due 81 24 9 Generic I O Tor PowerNet v3 and above 0 0 50 96 VIS br xe RR EEN Ee d 82 24 10 System Dedica SR etos rer i aera a RA bcnc 82 25 Ethernet processing toask nn 83 25 1 Ethernet packet handlers nenn 83 25 2 Link failure detection 6 een nnn nent eee rnrn 83 25 3 Ethernet EE 84 20 4 ROU Ey een nee Richie 84 26 SLIP ee Ae ee ne daa eed EE tees 85 26 1 SLIP equateS eher i eoe ibd gege SEET e 85 26 2 Slip input functions een ee ee aan 85 20 3 Slip output functions 2 sensensa ee ea a etek ENEE 85 264 SLIP support task sten a aaa a Ic ac 86 27 BSD API EE 87 27 1 SOCKET ERROR returns AEN 87 26 2 BSD TEE 87 27 3 BSD Style APT cnn essan ehh ER EEN na 88 254 EXTENSIONS E RR a ee 90 28 PowerNet diagnostic tools 91 29 KR Let NEE 93 29 1 Ident Block 0000 e ken AE A a a 93 292 Global data wacked aaa I ke ei oss ea ra 93 29 3 TFTP State Machine equates sssssssseesse e enn e nes 93 29 4 Event action place holders and defaultz 00 c ccc ccc een eee tenes 93 20 5 Utility e ENEE 94 29 6 TETP State Handlers engen ao ka aaa le 94 29 7 Event Action Handlers anaa a nananana aaneen 94 30 Support for TCP services 95 30 1 Service numbers 0 eee haee 95 30 2 Service specific datas cis esce beo ee an
52. 80 URL buffer PollURL addr Buffer for the poll server s domain name URL buffer PollPage addr Buffer for the page to be accessed by polling operations O value Unit u Unit serial number O value CustID u Unit customer ID number O value Transaction N u Transaction number used by the client code Chapter 39 Ethernet and Internet configuration 141 39 3 Flash and EEPROM routines Select one set of these routines as required 39 3 1 Flash SecTab dup cells FlashBase constant CfgFlash addr For configurations in Flash we default to using the last sector of the flash for configuration storage Systems that use fixed size pages e g Atmel SAM7X CPUs should predefine CfgFlash Elast buffer CfgBuff addr Buffer used during configuration read and write SetDefaults Flash Write the default configuration to Flash Usually run during production configuration before NetSetup below DataFlash gt RAM N Flash Read the TCP IP stack and unit settings from the Flash configuration area Data is copied to RAM if the magic number is correct otherwise the default configuration is pro grammed and used RAM gt DataFlash N Flash Write the TCP IP stack settings to the configuration Flash 39 3 2 Serial EEPROM DataFlash gt RAM N EEPROM Read the configuration from EEPROM RAM gt DataFlash N EEPROM Write the configuration settings to the EEPROM 39 4 Set
53. 9 initioqueueS i da e e peade ss 30 EIER ee aa Maes T INV EE 25 Int TEE 45 initserversocket esoerseer ca 99 inijtsockets d Re geb ee ea 41 eg EE 70 EE WEE 146 149 KE TE ne ea 127 TEE 127 invalid socket 2 ossis e en 33 H WEE 133 RT RTE 88 eh EE 16 Ip _hdr 44 e i Rt are 37 IPAddr EE 6 78 140 DEE reet ge Sg 6 45 140 iphdrlen iii diia ii ran 48 A A lee 47 iprout EEN 37 45 IPS dr E E EE EE E EES 47 he if SE EE EE 115 116 S a sed 115 EE e A trideni titrda enan eE G EE 47 USMY SOCKET EE 99 S EE 81 TE EE Sie SE EE 73 istcp fin ren emp Sine 73 istcp psh ceed t erp P ERI senses 73 istcp rst nn ae een ERR EAE ES Ta IStEB SM e Eed Ee de Ee 73 lstep syn ack A eio enra ENE NETEDE E NYES 73 EE 73 o 81 J Jpeg Picasa xen re quete aa ded 118 jump string iiiesiisciomeedbe De E EG eter 115 161 L lastportnumber eee 13 42 lastportused iicicrcee rci e RO PSIRE S n VES 42 DASH ei eI UR e heresi ep Per ee 27 left StriDg jede raten ae PES 115 DAG coeds e eheS REIR RR CROSS naeh PEE 39 linkdhchlainh ice per hr Er Rhet pr ER ERE 83 linked envi bae erster in 83 RE e EE 83 HE RE 113 listen sense een 89 RT ame 83 RE ee 83 M mnake tcpcb ener RH Rp er 42 maketcphdr e essere nani re RUPEE sates 72 EE D EE EE 12 75 EE rera T1 45 lnaxr xsize esgseeskie pace Guy edad sight saree ee 135 MAXSOCKCTS une a ER bee te 13 EE 132 mempages u ia aan a ia shaded
54. 90 dpproCcesSSTrX v vic ico eb e Rega pP e Ie RR 51 udpsend iii pP uer ROS EVE a np NES 51 udpservicechain ene e er bep EEN 51 Index HE een 56 109 Unbumppbutf E EE 30 ek EE EE 140 E MT EE 142 unnask ints naar 6 usebroadcast s voca zoe nen 58 USC O OP iii a ee 9 USC rr a A Peter ERE 9 US rre pe 112 usesntp non o eage teen ees 9 V ECH 93 101 124 KE EE 45 VOCDWIA ini a E 131 W CR DEE 19 WEICH esta se as echte 19 WOCHE Sara en ea sen ee E E 19 valt socket empty 66 c cece cece 99 WALtCODNG AA E E 89 vgaitdataconnected cece eens 110 vgaitdataestablisbed 0 cece eee eee 110 waitforipaddre ss ld wear an 41 CEET 89 Ee d EEN 89 wakxtsockets nt icc caw ern 99 web fil name lale lude era 126 gebautbhenticate eee esee 129 weberreode 22 Saas inh eH ias 118 weberr r unsern 126 165 RTE 129 webopflags siii 118 WEDPAagedeL oir rr spinn ta SERERE RAES 118 WEbQUErYVATS ENEE 122 WEDLESPONSE ii esseci rishini cece eee nn 126 Websteed dia 118 webs closa iee ion TE nase 117 webs_keep_alive nennen 118 Webs SCLIPtEY ea 117 WEDSCEIPti AA iiot E pIE EEAS A KRE 118 WEDSONG WEE 120 websetvars suneee eet E pe e en 122 Webstatus siciscicricesg users 118 MODULOS ene ee per AN RE nennt 118 writepacket eeere ns 81 X EE 10 ROW is aan ee 113 xml CY rinda e a a 118 Kan 113 DEE Seege did 131 EE 132 Y Do a 142 Z EE 92 ZCOUN a een EE e E p 94
55. Compute the partial internet checksum of a memory area This is a high level implementation that can be used by any CPU The word CKSUM is useful when calculating header checksums and avoids the need to create the pseudoheaders described in the TCP IP literature cksum addr len cksum computed as 16 bit ints Compute the internet checksum of a memory area This a high level implementation that can be used by any CPU STRUCT pseudohdr size The pseudoheader structure for checksum calculation This word is for illustration and is not compiled PHcksum hdr len ipsrc ipdest ipproto cksum A generic TCP UDP checksum function The parameters supplied are used to form a pseudo header from which the acual checksum is generated or checked Chapter 6 Extra USER variables 6 Extra USER variables 6 1 Common to all tasks cell User SocketErrorCode addr Last socket error cell User my_hsocket NV addr Socket owned by this task cell User my_socket addr Socket address owned by this task cell user emitBuff addr Start of the current emit buffer cell user emitNext addr Pointer for next buffer location cell user emitQueue addr Pointer to interface emit queue cell user emitmode addr 0 char 1 block 2 udp socket cell user keyBuff addr Contains current key buffer address cell user keyNext addr Pointer to next byte in buffer cell u
56. DP layer 51 19 UDP layer equ gt UdpDataPos offset The UDP data offset in an outgoing UDP packet UDPcksum hdr len ipsrc ipdest cksum A generic UDP checksum function The parameters supplied are used to form a pseudoheader from which the acual checksum is generated UDPSend hs pb ip sk lenlerr Send data on a connected UDP socket HS is a handle to a UDP socket handle PB is the address of a PBuff pointer already filled with the data to send as UDP data Returns the number of bytes sent if OK else SOCKET_ERROR SendDatagram pb ipaddr ip udp Send data as a UDP packet without using a socket The parameters are pb a pointer to a PBuff containing the UDP data and ipaddr the IP address to send to GetUDPAddress pbuf udp Extract start of UDP data from IP packet GetUDPLen udp len Extract length of UDP packet gt UDPData udp udpdata Extract pointer to UDP packet data variable UDPServiceChain addr This variable anchors the chain that will be walked to find out what to do with a UDP packet that has arrived struct UDPService len Describes the UDP service and how to run the service int us next Link to next service in chain int us port UDP Port that this service handles int us xtReceive Word that will process this packet int us xtIdle Word that will run idle action end struct UDPprocessRx pb udp Walk the UDP service chain
57. DSENDDATA state doDTRecvWrite The action in FTPRECVWRITEDATA state doDTerror The action in FTPERRORSTATE state create FTPdataActions addr A table of xts corresponding to the FTP data channel state doFTPdata We have a data socket Execute the action for the state waitDataConnected X ior Wait for a passive mode data connection to be made Return non zero on failure waitDataEstablished ior Wait for a passive mode data connection to get to TCP state TCPS ESTABLISHED Return non zero on failure Chapter 33 FTP Server 111 33 8 Command processing An FTP command exists on a single line The first token identifies the command Each command identifier is a Forth word which parses any more data needed by the command parse name text caddr len Return the next space delimited string from the input stream parse path lt pathname gt caddr len Return the next space delimited path name from the input stream Clip it to MAX_PATH 1 bytes getSrcParam Read the parameter and store it as the source name getDestParam Read the parameter and store it as the destination name getSrcDir Nee Read the parameter and store it as the source name If the name ends in a character remove it Some FTP clients terminate directory names with a which can confuse the FAT file system SrcParam N addr len Return the string saved as the source paramete
58. ER EEE e Hr 33 TEE 122 UE 111 KEE 121 SE 80 le GE 91 let GE 91 EE 16 a A A O i eh 95 SUStAtC POR EH 67 SOCKAddr IN 6 cabral 91 SOCKEL een aaa 91 A A nee 91 iSVmeSSage lies ead a a send a 99 PowerNet TCP IP Stack pj 91 E e EE 91 teptlage nannte darted tend 91 SUCpStabtO is theca wise ehe 70 dbelnetchain 2 406 2 i eite E E 104 itime amp date lscireiet n ee rb eS Ire teni 116 LEE 104 EE 91 uploasddone i Ee a DERE ee er 149 LETS speech 132 ONATYDIOCK u anne an 147 Edad neue et Pa eds 139 Feonniten nme ee IESE a p ad 74 cortact A Ee A 132 RER eh Ke datos stew heed EE 56 LEE 13 61 LEE 13 61 disgqtemplate cian inet 64 SCHOMS E 101 Le d EE 132 A EE epe EA 127 flashblock genge l ma geg eege 146 Lori DM o edem ern 132 form2 htm 2 de pr edere i vere sees 132 eem Ree ann 132 tpdata sisi pe ehe gege h ass 105 home htm i 2 dle Se 132 httpdata eer cy YO RP EDU DIATVUS 117 ene uenee ierra Ae ex IE Eege Sec 14 nareply EE 149 TEE 131 AA A m aka 20 EISES e en ees Rr REPRE USES 117 120 NEE 117 120 d EE 117 120 121 Sreflash timer nenn eet 149 BER each EE brad 65 Entpparams ana ee eat 66 A in ah E a Ee ROEA 96 lan Prem 96 SVOD n rm 96 SCD aan an 96 AA A nei 132 thanks ER ciar arca 132 tchanks3 Ponciano EES 132 art LE EE 51 A E E TE E E 139 gt inet ALON EEN 39 KT EEN 39 Ke 6 PUCPCOMNG A sirian A E E A eA SEE pE EES 74 S cpd t EE EEN 70 alte E EE 5
59. Holds the handle of the file being read written my_ftpLine X addr Holds true if a complete line can be processed my_ftpLineLen NV addr Holds the current length of the line excluding terminators my_ftpSrc addr Buffer that holds a source file path as a counted string my_ftpDest NV addr Buffer that holds a destination file path as a counted string my_ftpBuff X addr Buffer that holds FTP data for transfer 33 2 FTP vectored I O The FTP server establishes its own generic I O for the data and command channels The data channel operations are written for minimum RAM usage and use the sockets for buffering 33 2 1 Data socket checkSocket hs ior The zor is returned non zero if the socket is invalid or not in TCPS_ESTABLISHED state sockKey hs chars Return the number of available characters from the socket If an error has occurred 1 is returned sockKey hs char Return a character from a socket On a socket error an LF is returned sockType caddr len hs Send a string buffer to the socket sockEmit char hs Send a character to the socket sockCr hs Send a CR LF pair to the socket The following five words are used to provide generic I O on the FTP data channel FTPdataKey char my ftpDataSock sockKey FTPdataKey flag my ftpDataSock 0 sockKey FTPdataEmit char my ftpDataSock sockEmit FTPdataType caddr len
60. IN WAIT1 state DoTcpFinWait2 pb sk ip tcp cb Handle incoming packet while in FIN WAIT2 state DoTcpClosing pb sk tcp cb Handle incoming packet while in closing state DoTcpCloseWait pb sk Handle incoming packet while in CLOSE_WAIT state DoTcpTimeWait pb sk tcp cb Handle incoming packet while in timed wait state IncTcpPacket pb hs sk cb Process an incoming packet destined for hs RxTCPPacket 1 pb ip tcp hs q bf Process an incoming TCP packet 23 12 TCP timer handling DoTcpRetry cb sk SFPO21 Send data if tx retry timer expiration DoTcpDelayedData cb sk SFPO21 Send data if the transmit delay timer has expired DoTcpDelayedAck cb sk SFPO21 Send ack data if ack delay timer expiration DoTcpDisconDelay cb sk SFPO21 Handle disconnect delay timer expiration DoTcpConnectTimeout cb sk SFPO21 Handles timeout for failed connections 5 tick ms max equ TcpIdleMs ms SFPO30 Interval in miliseconds between TCP idle checks Using this timer mechanism reduces the CPU load at the expense of transmission performance on local networks Setting the value of TcpIdleMs to zero turns the mechanism off The value set here in tcp fth is only used if TcpIdleMs has not been defined in your PNconfig fth file 76 PowerNet TCP IP Stack O value TcpIdleTimer time SFPO30 Time for next TCPIDLE check
61. LOSING state from FIN_WAITI goFIN_WAIT_1 sk Move socket into FIN_WAIT_1 state from SYN_RECVD or ESTABLISHED goFIN_WAIT_2 sk 74 PowerNet TCP IP Stack Move the socket into FIN_WAIT_2 state goCLOSE WAIT sk Move the socket into CLOSE_WAIT state after receiving a FIN in ESTABLISHED goSYN_SENT sk Move the socket into SYN_SENT state from CLOSED 23 10 LISTEN connection queues From PowerNet v4 8 onwards listening sockets save connection attempts receipt of SYN on a linked list of connection items When the application e g a Telnet client wants to use a connection it inspects the queue and transfers the next item on the list to a new socket in SYN_RECEIVED state The new socket waits until the socket gets to ESTABLISHED state at which point the new connection can be used to transfer data Compared to the previous design listening sockets use less RAM and because connection at tempts are stored the design is kinder to single threaded servers struct ConnItem len Holds unprocessed connection information after a SYN packet has been received by a listening socket All entries are in native order Eowed ci Display the connection queue item cq hs Display the socket s connection queue TCPConnQ sk flag Return true if there is a connection on the queue TCPConnQ sk n Return the number of connections on the queue ciSame cil ci2 flag
62. OCKADDR IN skaddr is filled in with the IP address and port of the remote end After a successful operation the new socket is used for the connection just made and the old socket remains listening If SOCKET ERROR is returned no new socket is available and previous socket hs should be checked to see if it should be closed and remade 90 PowerNet TCP IP Stack 27 4 Extensions These extensions make life a bit simpler when connecting to servers TCPsocket hslo0 Create a TCP socket Return the socket handle on success or INVALID_SOCKET 0 on error connectTo caddr u port socket socket ior Attempt to connect to a server The socket has already been created in the appropriate mode The value of socket must be a positive non zero number Caddr u describes the server address either as a name or an IPaddress string and port is the requested port If u is zero caddr is treated as a 32 bit number representing an IPv4 address In this implementation u must be zero On success the socket and zero are returned otherwise SOCKET_ERROR and an error code are returned TCPConnect c addr u port socket ior Attempt to create a TCP socket and connect to a server Caddr u describes the server address either as a name or an IPaddress string and port is the requested port If u is zero caddr is treated as a 32 bit number representing an IPv4 address In this implementation u must be zero On success the socket and zero are ret
63. PowerNet TCP IP Stack Stephen Pelc Graham Stevenson vo 0 Copyright 1999 2008 2009 2010 2011 2012 2013 2014 Microprocessor Engineering Limited Published by Microprocessor Engineering PowerNet TCP IP Stack User manual Manual revision 5 0 18 July 2014 Software Software version 5 0 For technical support please contact your supplier For further information MicroProcessor Engineering Limited 133 Hill Lane Southampton SO15 5AF UK Tel 44 0 23 8063 1441 Fax 44 0 23 8033 9691 e mail mpe mpeforth com tech support mpeforth com web www mpeforth com Table of Contents 1 Introduction td ee 1 1 1 What Do You Get 1 1 2 Documentation 1 x9 nn er A EEEE 1 1 3 Source EE 2 2 PowerNet bld primary build le 5 Qed Heaps use nie aaa small 5 2 2 Multit sker neger a N PRESE Seth dea ie 5 2 9 Other Forth equates sas ans ee ee a d NEEN her pes 5 2 4 Configuring the stack 5 25 Default console I O for tasks excita dada ine 6 2 6 Default Ethernet and IP addresses 0 00 cece eee nr 6 2 7 Compiler extensions REENEN EELER cde semen ended eb dba eee es 6 2 8 Compiling Dowerhet 0 0 c ccc ne nent hh e mme 7 2 9 Compile the required services 7 2 10 Tree deeg Se rn ee eier 7 2 11 Sanity checks u ns ah 7 3 PowerNet confbeuration 0 00 00 erases anren eee 9 3 1 Features and Services oclo deb Rp dee eer NEEN NEES EE EE ER 9 3 2 Diagnostic riada A da ee eee EE EA 10 3 9 Queues and EA
64. RSE PECES E ges 133 36 6 Page look EE 133 37 SMTP Eat oer owes Nasen ga C So bap ion o e 135 38 SMTP Demonstration eee 137 38 l Configuration msi da rene ENEE ea HERE RERO Y ae per EN 137 38 2 Sending mail ie ecke tern Bar ti 137 39 Ethernet and Internet configuration 139 39 1 HEPROM Flash area definition e AANEREN is 139 39 2 EE 140 39 3 Flash and EEPROM routines sssssssseeeeee emen 141 SUMMOPERE rU 141 39 3 2 Serial EEPROM See rs ea a da 141 39 4 Set up operations sssseesseseees EDENE sehen 141 39 4 1 Displaying and Entering IP addresses 0 000 nunne eee eens 141 39 4 2 Displaying and Entering MAC addresses 0 cece eee eee e eens 141 39 443 Setup Prop ANNERES NEEN naeh 142 40 POST handlers and HTTP updates 143 AQ DISCUSSION cce e er eR ERE ERE cR ee 143 ADAL bom ge rer RR E ERI 143 SN Headers veces eee Deer Rete retirees Saud aly bx ed bor s 144 40 2 Form boundaries esee hm m eee 145 40 2 1 Form data 4e arten ini ee ERA 145 40 2 2 After theform uu ener ee ee a ida dis 146 GR We EE 146 40 3 Parsing multipart boundaries 0 cece eee een eee tenn ee eee 146 40 4 Flash update application 146 40 4 1 System interface nee ran nn ehren NEE 146 40 4 2 Receiving ane 147 40 4 3 Part Scanning nee ne nel 148 40 5 File update h ndler 2 ee ne ak lerne te 149 40 5 1 Example for pages stored in les 149 41 Internet REP sauna 151 ati What
65. Return true if the two connection items are for the same connection i e a retry has has occurred onConnQ ci sk flag Return true if the connection is already on the socket s connection queue gt TCPConnQ N tcp sk Add an entry to a listening socket s connection queue On failure no action is taken and we assume that the connecting socket will retry TCPConnQ gt skl ska Take a connection from the listening socket skl and transfer it to the accepting socket which enters TCPS_SYN_RECEIVED state ska 23 11 TCP state handlers DoTcpClosed 1 pb sek ip tcp cb Handle incoming packet while in CLOSED state DoTcpListen 1 pb sk tcp cb Handle incoming packet while in listening state server DoTcpSynReceived pb sk tcp cb Chapter 23 TCP layer 75 Handle incoming packet while in SYN received state server DoTcpSynSent pb sek tcp cb Handle incoming packet while in SYN sent state client acktxbytes cb nb nb SBDO11 Removes n bytes from the transmit buffer DoTcpAcknowledge tcp cb sk nb Handles incoming ACK See Wright amp Stevens about ack numbers DoTcpEstablished pb sk ip tcp cb tdlen Handle incoming packet while in established state DoTcpLastAck pb sk tcp cb Handle incoming packet while in last ACK state DoTcpFinWaiti pb sk ip tcp cb Handle incoming packet while in F
66. RxBuffers Do not change these unless you are really sure you know what you are doing FO equ DEV_MASK mask Router device mask 8 bits The device type is contained in the upper four bits and the device number within a type is contained in the lower four bits EO equ ETHER_MASK mask Ethernet ports are in the range E1 EF 00 equ SLIP_MASK mask SLIP ports are in the range 01 0F E1 equ ETHER_PORT n Port identifiers for Ethernet devices are in the range E1 EF 3 4 Routing 32 equ MAX_IPADDRS n No of entries in the routing table not dynamic yet 7200000 equ ROUTE_LIFE ms Two hours in milliseconds 1000 equ ROUTE_SAMPLE_MS ms How often routes are tested im milliseconds 2000 equ ROUTE_SEARCH_TIME ms Maximum time allowed for route searches 3 5 ICMP 3 equ ARP_REQ_TRIES N n Number of ARP request tries before failure 12 PowerNet TCP IP Stack 3 6 IP O equ PacketTask n Set this non zero to use a separate task to handle incoming IP packets This uses more code and RAM but may give better performance on some systems The default is 0 3 7 TCP configuration 1460 equ TCPDATASIZE N n Iransmit buffer size of a PBUF less the standard IP and TCP headers The largest value for Ethernet is 1460 1460 2 equ TCPTXBUFFSIZE N n Size of the retransmission buffer for a TCP socket One buffer of this size is allocated from the heap when a TCP socket is created If you have
67. T QUIT Process the QUIT command ABOR N ABOR Process the ABORt command PORT N PORT al a2 a3 a4 ph pl Process the PORT command The IP address and port are saved in my ftpDataIP and my ftpDataPort PASV N PASV Process the PASV command RFC 0959 does not document PASV well See http cr yp to ftp retr html for more details A successful response is of the form 227 Entering Passive Mode al a2 a3 a4 ph pl RETR RETR lt filepathname gt Process the RETRieve command Starts transmission of a server file to the FTP client CWD NV CWD dirpath Process the CWD command XCWD CWD XCWD dirpath Process the XCWD command PWD X CWD dirpath Process the PWD command XPWD PWD XCWD dirpath Process the XPWD command LIST LIST lt filespec dirspec gt Process the LIST command The parameter is optional If there is no parameter the current directory is listed If the parameter is a file the details of that file are listed If the parameter is a directory the files and directories are listed in sort of the Unix s format NLST LIST lt filespec dirspec gt Process the LIST command The parameter is optional If there is no parameter the current directory is listed If the parameter is a directory only the files are listed by returning one name per line RNFR RNFR lt filespec gt Process the RNFR command checking that the file exists RNTO
68. T handlers and HTTP updates 149 ProcessPart flag After receiving a boundary process a part up to and including the next boundary returning true if it is the last one ProcessParts Read the parts up to the last boundary 40 5 File update handler doNewApp caddr len This is the handler for the update request doNewApp xtPage NewApp asp Defines the page which performs the upload UploadDone Used in the body of an ASP page to indicate the response to the upload MemPage Reflash htm IPSTACKY TestPages Reflash htm A form used to request a new application MemPage nareply asp IPSTACKY TestPages nareply asp The response delivered after an upload 40 5 1 Example for pages stored in files This example can be used to upload binary files e g a new application image to the file system In order to compile this code the FAT file system must be present and the equate FilePages used in Pages fth must be set non zero Defer InitUpd caddr len Initialise the app s binary update system The input string is the file name to be received This is passed for validation purposes and in case the file is saved in a local file system Defer AddUpd caddr len Add the given memory block to the update All blocks except the last contain FlashBlock bytes of data Defer TermUpd Terminate the app s binary update system create FileDir addr The base directory for files This will b
69. TE_ create defRoute IPROUTE structure for the default route SetRouteLife ms route Set the route s life to end ms from now SetInfLife route Set the route to have an infinite life ExtendLife ms route Extend the life of the given route by ms if the life is not infinite InitRoutes N Initialise routing table find route ip addrlO Get routing table entry address if available AskForRoute ip addrlO See if we can make a route ViaGateway ip iptmp rt addrlO Returns gateway route or none CanWeRoute ip addr O returns route or 0 gt Handles routing via the subnet mask or gateway if one exists find route ip addrlO Get table entry address if available 46 PowerNet TCP IP Stack empty route NX addr O Get table entry address if available add_route ip addr O Get table entry address if available expire_routes N Decrement the route entry timers and expire any routes that have timed out Chapter 17 Basic IP layer 47 17 Basic IP layer 17 1 Tools isIPforme pbuf flag Flag true if this packet is for me variable ipid addr for outgoing packets IP packet identifier incremented by one for each outgoing IP packet SetIPhdr len ipsrc ipdest ipproto iphdr Initialise and fill in an IP header with no options pb gt IPH ip pb Step the PBuf data pointers back to the IP header from th
70. TML for an example form Following sections indicate the response in our case using Firefox 144 PowerNet TCP IP Stack lt html gt lt head gt lt title gt Select new application lt title gt lt head gt lt body gt lt h4 gt Select application lt h4 gt lt p gt Select the application using the Browse button lt br gt then press the Submit button to send it to me lt br gt Once you have pressed Submit you are committed lt br gt To avoid sending a file return to the previous page lt p gt lt form enctype multipart form data method POST action newapp asp gt lt table gt lt tr gt lt td gt New application file lt td gt lt td colspan 4 gt lt input type file name appfile gt lt td gt lt tr gt lt tr gt lt td gt Upload to remote lt td gt lt td colspan 2 gt lt input type submit name send value Submit gt lt td gt lt tr gt lt table gt lt form gt lt body gt lt html gt 40 1 2 Headers The following is a response by Firefox to the form above Note that whenever you press a button of the submit type you get the complete response including any selected file 7 POST newapp asp HTTP 1 1 Host 192 168 0 227 Accept Language en us en q 0 5 Accept Encoding gzip deflate Accept Charset IS0 8859 1 utf 8 q 0 7 q 0 7 Keep Alive 300 Connection keep alive Referer http 192 168 0 227 Reflash htm Content Length 9386 805274455
71. TP Server 121 32 equ QVARS MX n Number of QVARs in each connection and the common area QVARS QVarRec equ QVARS n Size of a QVAR buffer QVARS buffer commonQvars addr The buffer area for the common QVARs 80000000 equ NO_VAR_SET N n Indicator returned when a QVAR has not been set QvarName 1 chars equ QV name X n Maximum length of a QVAR s name QvarData 1 chars equ QV data X n Maximum length of a QVAR s string data Qvars addr Display the variables in the given table Qvars Display the common and connection variables freeqvar table addrl0 Find a free QVAR in the given table and return its address or zero if no free space is available freeQvar addr O Find a free QVAR for the current connection and return its address or zero if no free space is available freeCommonQvar addr 0 Find a free QVAR in the common QVARs and return its address or zero if no free space is available findQvar caddr len table addr 0 Try to find a QVAR in the given table Case insensitive findQvar caddr len addr O Try to find the given QVAR name returning the address if found or zero if not found Case insensitive Yxx gt char caddr len caddr len char Convert the three character sequence xy as a hexadecimal two digit number Step over the string decodeURL caddr len dest dlen Converts the source string caddr len from a URL encode
72. Web Services the input data is not in the headers but is contained in the body of the message The size of this body is defined by the Content Length header When handling POST messages the whole of the incoming message must be read the body extracted and passed to the message handler In addition some handlers may need to process the message header For example Web Services need to use the SOAPaction header before SOAP version 1 2 Scripting for output messages introduces the problem that the size of the message body is not in general known until the script output has been generated This means that the Content Length header sent before the body cannot be formed until the body has been generated Chapter 35 HTTP Server 129 To avoid the memory overhead of buffering script output for ASP file requests no Content Length header is generated and the connection is closed after the response has been sent to indicate that the message is complete For web services ASPX pages are served and are buffered and a Content Length header is generated Error messages such as 404 Not found are always buffered to produce a valid Content Length header because some browsers require this header for error messages The Content Length header is not always required for HTTP version 1 1 and above However if HTTP 1 0 clients have to be supported the Content Length header must be provided In this case all scripted operations must be buffered See RFC2616 fo
73. Write Noes ftpRecvWriteData my_ftpDataState umin ul u2 ullu2 Minimum of two unsigned values closeDataFile 110 PowerNet TCP IP Stack Perform an emergency close of the data file if it is open hasConn hs ior true 0 Return true and an ior if the socket has an error or a completed connection For a good connection tor is non zero newDataSocket hs 0 Create a new FTP data socket and set it to listen The socket handle is also stored in the FTP service structure discDataSocket If open flush the socket transmit data and disconnect the FTP data socket This is a graceful close unless the socket has failed closeDataSocket If open close the FTP data socket This is not a graceful close termDataStream Gracefully shut down a STREAM mode data transfer and return to FTPDTIDLE state closeDataStream Hurriedly shut down a STREAM mode data transfer and return to FTPDTIDLE state CheckFTPdata ior Return non zero if the FTP data socket is in error FTPdataFailed ior Return non zero if the FTP data socket is not in established state If not established the data socket is closed and we return to FTPDTIDLE state doDTidle The action in FTPDTIDLE state Check the data socket If it fails close it doDTlistening The action in FTPLISTENING state doDTconnected The action in FTPCONNECTED state doDTReadSend The action in FTPREA
74. a 95 KINNEN 97 30 4 Service KEY EMIT and friends 97 30 4 1 Low RAM veraion 0 ccc ccc enn eee nee es 97 30 4 2 High performance veraon 0 000 cece ence cence ee nent m 97 30 4 3 Generic EE 98 30 4 4 Service console support 98 30 5 Service creation and deletion ssssssssssssssssseese en 99 30 6 Service listening ask 99 30 7 Service support tools 99 IN 100 30 9 Diagnosties srece has est an en Rn ee 100 31 TCP Echo SDORBE as ede dead Ud oco een 101 32 Telnet Server Zaire era 103 32 1 Telnet specific data nenn ee LA Steg ee ba Eabb 103 32 2 TAC handing ti Ae ere a rear Backen 103 32 3 Telnet vectored ER en usa 103 32 4 Telnet service tasks 22ceeeeeeeeeseeeeeenesennneeeeeeeeeeeesssnnneneenn 103 32 5 Telnet listening task een ENEE na a ee ish REM 104 32 6 Diagnostics adc eet b e E a cec a ae nen 104 33 Ce NEE 105 33 1 PUP data een ei a ar ee 105 33 2 FEP vaobored DO EE 106 33 2 1 Data socket na a a an ki a da 106 33 2 2 Command ET EE 107 33 3 Sampling the command channel input 0 e eee 107 33 4 Diagnostic control 6 0 6 nen nee eben s en 107 33 5 Directory listing for HDD 107 SET 108 33 7 Data socket operationsg 00 cece nen m en 109 33 8 Command processing cc cece eect rrur mee 111 39 9 Login and Security en eee esee e RR EN A En er EE de eda 111 33 10 Implemented FTP commande 112 33 11 FTP service tasks lodi Rer an ea a 114 39 12 FTP hstenin
75. ack Process a GET command The input string is the complete input line containing the GET command semaphore PostSem addr Controls access to the single POST handler POST requests are serialised because they may change the state of the system http post caddr len Process a POST command The input string is the complete input line containing the POST command ParseHTTP caddr len Process received HTTP command line At present we only deal with GET and POST commands doHTTPinput Process any pending input cleanHTTP N sv sv Cleans up the HTTP system when a task is shut down from the kill chain HTTPService The HTTP service action or task launched for each established HTTP connection 35 12 HTTP listening task Listening tasks or actions are spawned when the HTTP server gets a connection HTTPServer NV stay here forever The HTTP listening task O value HTTPtask NV Oltask Returns 0 or the HTTP server task if running RunHTTPtask Start the HTTP server task StopHTTPtask Stop the HTTP server 35 13 Notes on memory usage The majority of page requests are made using a GET request For these only the first line of the header needs to be scanned and the request is contained in a single packet whose maximum size is defined in lower layers of the Powernet system Consequently a fixed size packet buffer is used for HTTP input When handling POST requests e g for
76. actor out error handling in the BSD layer By default they are implemented as COMPILER macros If implemented as discrete words remove the comments around the R gt DROP phrases seOX flag flag SOCKET_ERROR exits caller If flag is true returns SOCKET_ERROR and exits the CALLING WORD otherwise does nothing This is provided as a factor for parameter testing se1X X n flag n SOCKET ERROR exits caller If flag is true drops 1 item returns SOCKET_ERROR and exits the CALLING WORD oth erwise does nothing This is provided as a factor for parameter testing se2X ni n2 flag n1 n2 SOCKET ERROR exits caller If flag is true drops 2 items returns SOCKET_ERROR and exits the CALLING WORD otherwise does nothing This is provided as a factor for parameter testing se3X X ni n2 n3 flag n1 n2 n3 SOCKET ERROR exits caller If flag is true drops 3 items returns SOCKET ERROR and exits the CALLING WORD otherwise does nothing This is provided as a factor for parameter testing 27 2 BSD factors These words are not part of the official BSD interface They are either factors or useful in low level code pollSocket sk pblO SOCKET ERROR Non BSD function to poll a socket and return the next input packet buffer if available ioctlRead V arg sk O SOCKET ERROR Return the amount of data that can be read from a socket storing it at address arg ioctlState arg sk res SOCKET_ERROR Re
77. air s value text DumpPairs KE A diagnostic tool for use in scripts Read and dump all the key value pairs without preserving them 126 PowerNet TCP IP Stack 35 9 HTTP headers and responses This section deals with extracting the HTTP command data and with pages served from memory web file name caddr len caddr len Return the string up to the next character Then if the file name starts HTTP step over HTTP This situation can occur with proxy servers test web type caddr len type Return the type code associated with the file extension e g htm or asp HTTP n Output the HTTP string and code line HTTPserver Output the HTTP server name line HTTPdate Ame Output an HTTP date line HTTPar none Output the accept ranges none line HTTPcontent type Output the text string for the curent type Unknown types generate text plain close keep NX Output the default connection type WebResponse datalen type code Output a suitable HTTP header for this type of data create Null addr A null string which may be used as a counted string or a zero terminated string ErrHead len err Output the error header If len is non zero it is used for a Content Length field ErrBody caddri leni caddr2 len2 err Output a web error body using the given strings and error number The string caddr2 len2 contains the error descript
78. an be set to 1 FTPuser N The default action performed for the USER command All users are accepted FTPpass ADS The default action performed for the PASS command All passwords are accepted FTPacct N The default action performed for the ACCT command All accounts are accepted 33 10 Implemented FTP commands FTP commands all start with a command name verb in FTP parlance Each is implemented as a Forth word in the FTPvoc vocabulary vocabulary FTPvoc NE Vocabulary holding FTP commands for execution gt FTPvoc gt body constant FTPwid N x Wordlist holding FTP commands for execution FTPinterpret Interpret the current line containing an FTP command also FTPvoc definitions Start of FTP command definitions USER N USER lt name gt Handle the USER command PASS PASS password Handle the PASS command ACCT ACCT password Handle the ACCT command SYST N SYST Handle the SYST command STAT N STAT Process the STAT command Commands with parameters are rejected HELP HELP lt param The HELP command just describes the system NOOP 5 NOOP The NOOP command just returns good STRU NV STRU F Chapter 33 FTP Server 113 Obsolete command we just accept F MODE N MODE S Obsolete command we just accept S TYPE N TYPE lt params gt Process the TYPE command Valid parameters are A AN I L 8 QUI
79. an entire domain name or a list of labels at the end of a domain name is replaced with a pointer to a prior occurance of the same name The pointer takes the form of a two octet sequence 1 1l OFFSET The first two bits are ones This allows a pointer to be distinguished from a label since the 64 PowerNet TCP IP Stack label must begin with two zero bits because labels are restricted to 63 octets or less The 10 and 01 combinations are reserved for future use The OFFSET field specifies an offset from the start of the message i e the first octet of the ID field in the domain header A zero offset specifies the first byte of the ID field etc 21 3 Tools 4 buffer DNSid addr Holds the DNS transaction number The number is incremented before use so that a good response should have the same number create DNSQtemplate X addr Template for a DNS query 12 equ DNSQtemplate NX len Length of the DNS query template genDNSQhead addr addr Generate a DNS query header at addr and return the address just after the header gt che addr b addr 1 Saves b at addr and increments addr genLabel caddr len addr addr Add a label n n bytes to the text at addr returning the next label address genDNSname caddr len addr addr Generate a name as a sequence of labels genDNSquestio
80. ata n pbuf Moves the data pointer count along the buffer incrementing the address decrementing the count unbumpPBuffData n pbuf Moves the data pointer count back up the buffer decrementing the address incrementing the count 9 4 Queue buffer allocation and release PBinit pb Initialise a PBUF AllocPbuf pblO ALLOCATE and initialise a PBUF from the heap and return the PBUF address If the buffer cannot be allocated O is returned without waiting O value TxPbuf addr Points to the dedicated transmit PBUF O value NextTxPbuf addr Holds TxPbuf when the transmit PBUF is available or zero when not available InitIOQueues Initialise the predefined queues and their I O buffers and PBUFs GetPbuf pblO Get a PBUF from the free PBUF queue and return the PBUF address If there are no free buffers 0 is returned without waiting GetTxPbuf X pblO Get a PBUF from the free PBUF queue and return the PBUF address If there are no free buffers try the dedicated transmit PBUF O equ QBdiags n When this equate is set non zero additional test code is compiled and included in FREEQB below variable qbug addr When set to non zero FREEQB will display diagnostics if the buffer is bad PBUFFER PSIZE or equ PBcheck x Check value for a PBUF FreeQB pb bf Place a PBUF or I O buffer on the relevant free queue N B FreeQB cleans up the buffers before requeuei
81. ations From v4 8 onwards you can use the equates SVlowRAM andSVsingle in the PowerNet configuration file to reduce RAM consumption in listen state by up to 2kb per listening socket above the reductions already achieved in the TCP layer 30 1 Service numbers These are MPE defined for use in the socket structure O equ service none NV n Defines a null service 1 equ service Telnet n Defines a Telnet service 2 equ service_HTTP n Defines an HTTP service 3 equ service_FTP n Defines an FTP service 8 equ service_Echo n Defines an Echo service 9 equ service_MultiChat n Defines a MultiChat service Windows version only 10 equ service_ModBus Defines a ModBus TCP service 20 equ service_App Service number for an application specific service service n Display the service type corresponding to n 30 2 Service specific data These data definitions are required by each server task The data is allocated at the start of the task and released when the task is TERMINATEd The chain SVchain links all the service tasks 96 PowerNet TCP IP Stack Each task has USER variables MY_SOCKET and MY_HSOCKET which hold the socket address and socket number From these the service specific data can be found The first part of a service data area is common to all services and additional fields can be added as required See TELNET FTH and HTTP FTH for examples The common data area includes service managment data
82. between TCP socket polls Using this timer mechanism reduces the CPU load at the possible expense of transmission performance by 10 2096 on local area networks Setting the value of TcpIdleMs to zero turns the load reduction mechanism off Note that on some systems setting TcpIdleMs non zero may improve performance because of the reduction in polling time For tuning we recommend an initial value of 5 with the ticker rate usually defined by TICK MS in the main control file set to 1 millisecond 100 equ TXDELAYTIME ms timer for delayed transmit mSecs default is 100 milliseconds 10 equ ACKDELAYTIME ms timer for delayed ack mSecs default is 10 milliseconds 5000 equ TXRETRYTIME ms timer for transmit retries mSecs default is 5 seconds Chapter 3 PowerNet configuration 13 12 equ TCPMAXRETRIES n Maximum number of transmission retries before returning SOCKET_ERROR the default value is 12 If a receiving socket fails to accept new data the total timeout will be TXRETRYTIME TCPMAXRETRIES the default being 60 seconds 30000 equ TCPCONNECTTIME ms Timer for incoming connections to complete mSecs the default is 30 seconds 30000 equ TCPMSLTIME ms Timer for maximum segment lifetime mSecs the default is 30 seconds 7200000 equ TCPIDLETIME ms timer for idle disconnection mSecs default is 2 hours 80 equ TcpRstTime ms Delay before closing socket after a reset 3 8 Socket
83. byte Chapter 24 SMC LAN91C92 4 6 Ethernet Driver Code Bank2 Registers MMU Memory management unit cmd reg PNR Packet number register ARR Allocation result register Pointerl Memory pointer register Pointerh Memory pointer register Datal Reg to send packets too Datah Reg to send packets too IntStatus IntMask Misc Constants RelRx MMU Command to release memory from an rx RxRd SMC Command to read received packet TxWr SMC Command to write to tx area of ram AllocIntMask Memory allocated mask MaxMsgSize Max 802 3 Ether frame size in bytes AllocTx bitO Bitmask biti Bitmask bit2 Bitmask bit3 Bitmask bit4 Bitmask bit5 Bitmask bit6 Bitmask bit7 Bitmask EvenTx Control byte for tx of even bytes OddTx Control byte for tx of odd bytes RxTask Multi Task ID 24 5 Hardware Interface Layer The default code is for a memory mapped device at base address EtherBase ec b offset Set an 8 bit register contents to b in the selected bank ec offset val Read an 8 bit register in the selected bank 79 80 PowerNet TCP IP Stack ew w offset For LITTLE ENDIAN CPUs only Set a 16 bit register contents to w in the selected bank ew offset val For LITTLE ENDIAN CPUs only Read a 16 bit register in the selected bank ec val offset VFX optimising compilers will probably produce shorter and faster code by using a compiler macro for EC ec offset val VFX optimising compil
84. ce create ConsoleSV addr OUT managed by upper driver Function despatch table for service I O OUT is managed by the upper level driver Console SV Select the service I O as the console Init ConsoleSV Initialise for console I O by the service Note that the service s socket must have been set up and and the private service area initialised 30 4 4 Service console support SV_responsive N Set the socket to use the TCP PSH flag when sending to improve interactivity DN responsive N Set the socket not to use the T CP PSH flag when sending SV responsive X res Return non zero if the socket s TCP PSH flag override is set SVaccept c addr n1 n2 read up to LEN chars into ADDR Read a string of maximum size n1 characters to the buffer at c addr returning n2 the number of characters actually read Input is terminated by LF and CR is ignored This satisfies the requiresments of DOS Windows Unices and the TCP IP NVT Network Virtual Terminal If ECHOING is non zero characters are echoed If XON XOFF is non zero an XON character is sent at the start and an XOFF character is sent at the the end SVquery X fetch line into TIB Reset the input source specification to the console and accept a line of text into the input buffer Chapter 30 Support for TCP services 99 30 5 Service creation and deletion isMySocket hs Set up USER variables for this socket NoSocket
85. ction of the new task is given by zt given by xt 30 7 Service support tools waitSocketSent hs Wait until all transmit data for a socket has been sent and acked wait socket empty X Wait until all output has been sent from the socket SVdisconnect Disconnect the current service socket and run SVbye 100 PowerNet TCP IP Stack SVstartup X Performs the default actions when a service starts I O is set to the console BASE to decimal and a console message is issued SVshutdown Performs actions required when a service finishes SRVRstartup NX caddr len The first action a server task should perform The string is displayed on the console with a startup message 30 8 Service output In order to avoid race conditions a separate task handles testing whether a service should be closed variable SVkillChain addr Holds the tail of service tasks to be destroyed SVkill SVdata If the service has a task i e is a service rather than a server move it to the kill chain otherwise just free the memory ServiceClose Close any service tasks with a non zero SVDONE field in the private service area ServiceKill MX Kill any service tasks that are on the kill chain and free the task and service memory The kill chain is extended by CloseSocket The service task clean up action the xt in the SVappClean field is run before memory is freed The field SVappClean contains th
86. d after changing the pointer register 0 equ smcDiags flag 78 PowerNet TCP IP Stack Set this equate true to compile diagnostic code for register dumping and so on False by default O equ eeprom flag Set this equate true if the LAN91C9x has an attached EEPROM for configuration data storage False by default O equ GenericIP flag Set this equate true if the Generic IP device structure defined in ETHERCOM FTH is required This is only required for systems using multiple IP devices in future releases of PowerNet 1 equ sniff N flag Set this equate true to compile the packet sniffer code which can be used to test Ethernet reception create EtherAddress addr Holds the Ethernet MAC address six bytes Note that you must obtain these from the IEEE www ieee org or from other sources create IpAddress NV addr Holds the Ethernet IP address four bytes 24 4 Constants BankSelect Offset of bank select register Bank0 Registers TCRL Transmit Control Register lo byte TCRH Transmit Control Register hi byte TXSTATUS Transmit Status Register RCR Receive Control Register MIR Memory Information Register MCR Memory Control Register Bank1 Registers Configl Configuration Register lo byte Configh Configuration Register hi byte TAO Hardware Address Ethernet MSB IA1 Hardware addr IA2 Hardware addr IA3 Hardware addr TA4 Hardware addr TA5 Hardware addr Ctrh Control Register hi
87. d string to a decoded counted string in the buffer dest dlen No error checking is performed Decoding converts characters to a space and ab follwed by two hex digits sequences to their character codes setQvarData caddr len qvar Use the given URL encoded string i caddr len to set the data area of the given qvar set string N name nlen string slen Set the connection QVAR name nlen to contain string slen If the name already exists in the connection or common QVARs it is overwritten If the QVAR does not exist it is created in the connection s QVAR set If there is no space for it the request is ignored setCommonQstring name nlen string slen 122 PowerNet TCP IP Stack Set the common QVAR name nlen to contain string slen If the QVAR does not exist it is created If there is no space for it the request is ignored GetQstring name nlen caddr len Return the text for a string If the variable cannot be found is returned Qstring name nlen Output the text for a QVAR using GetQstring above websetvars caddr len Process a query string A query string has the form name value amp name value WEBSETVARS can be used with any query string WebQueryVars caddr len This is used by GET with query packets init CommonQvars Initialise the common QVARs init WebVars Initialise the connection QVARs 35 5 1 Numeric QVARS setQvar caddr len n
88. d the actions performed by default for timestamps 0 Dummy action 1 Set clock user defined action 22 1 SNTP equates and structure 123 equ SNTPport porti The standard SNTP port number The client us and the server use the same port number STRUCT sntp len SNTP payload structure after the IP and UDP headers The Timestamp fields contain a 32 32 bit fractional time in network big endian format The first cell contains seconds measured since 1st Jan 1900 as per RFC1361 The second cell contains a fractional second If you are using the SNTP code with the Unix calendar code in Examples UnixTime fth NTP timestamps are based from 1 Jan 1900 which has an LSECONDS value of 1291876096 86400 1291962496 so add 1291962496 to the NTP seconds value to produce a Unix time value If you are using this code with NTP timestamps these are based from 1 Jan 1900 which has an LSECONDS value of 1291876096 86400 1291962496 so add 1291962496 to the NTP seconds value to produce a Unix time value Note that the Unix LSECONDS counter rolls over in 2036 Suitable code to convert LSECONDS to time and date can be found in your cross compiler Exam ples UnixTime fth If you are planning a product which needs to cope with dates beyond 2035 note the following from RFC4330 As the NTP timestamp format has been in use for over 20 years it is possible that it will be in use 32 years from now when the seconds field overflows As it is probab
89. d the length of the IP header IPhdr ip addr Step from the IP header to the next item e g TCP header RxIpPacket pb Process a received IP packet PowerNet TCP IP Stack Chapter 18 ARP handler 49 18 ARP handler ARP fth handles ARP packets for Ethernet and DHCP SEI equ ETHER PORT X eeu Port identifiers for Ethernet devices are in the range E1 EF create EtherBCastAddress addr Holds the Ethernet broadcast address FF FF FF FF FF FF create EtherUnkAddress Holds the Ethernet unknown address all zeros TurnEtherPacketRound eth_hdr Return the packet to the sender HandleArpRequest pb ad eth arp Returns reply to an incoming ARP request AddEtherRoute etheraddr ipaddr Add an Ethernet route given a pointer to a 6 byte Ethernet address and an IP address HandleArpReply pb arp Handle an incoming ARP reply so extract info ArpForMe arp flag nz for me Given the address of an incoming ARP payload return true if the packet should be handled EtherArpPacket pb ad In eth arp Process an incoming ARP packet The pbuf holds the received Ethernet packet We use the incoming packet buffer for the reply create ProtoArpHdr X addr Prototype ARP request header SendArpRequest ipaddr Formats and sends out an ARP request packet This is always a broadcast SendGratuitousArp N Send a Gratuitous ARP Request Chapter 19 U
90. e TCP or UDP header 17 2 Sending IP packets defer send gt other pb rt len This allows other routes to be patched in to the stack without changing the stack source NoOther pb rt len The default action of SEND gt OTHER IPSend pb len 1 Send the data in the supplied PBuf chain PB is the first pbuf in the chain only 1 allowed Returns the number of bytes sent if OK else SOCKET_ERROR IPSend sk pb len SOCKET_ERROR Send the data in the supplied PBuf chain Returns number of bytes sent if OK else SOCKET_ERROR 17 3 Receiving IP packets defer RouteIP pb This IP packet is not for me Vectored routing allows later application dependent patching up The default action is to discard the packet with FreeQB defer CanRouteIP pb TIF Returns true if we can route this packet Vectored routing allows later application dependent patching up NoCanRoute pb False The default action of CANROUTEIP ProcessPacket pb Process an incoming packet Task PacketTask addr The task that handles incoming packets DoIncoming X The action of the incoming packet task RunIncoming Start the incoming packet task GoodIPPacket 41 pb Process a good packet 48 GoodIPPacket pb Process a good packet RunIncoming Start the incoming packet task BadIpPacket pbuf A header check failed so discard the packet IPHdrLen ip len Fin
91. e diagnostic code 2 2 Multitasker The multitasker is required 1 equ tasking true if multitasker needed 6 cells equ tcb size for internal consistency check O equ event handler true to include event handler O equ message handler true to include message handler 1 equ semaphores true to include semaphores 2 3 Other Forth equates The equate RP SIZE should be set to 0200 bytes Powernet is particularly heavy in its use of locals and hence of the return stack 2 4 Configuring the stack First of all you must add a text macro to your main control file to tell it where the stack is located The code below was used during development c C buildkit dev software AddOns PowerNet Dev setmacro IpStack where the PowerNet stack lives The macro IPSTACK tells the cross compiler where the file POWERNET BLD is located By default PowerNet bld compiles configuration data from the file PNconfig fth which is always provided with PowerNet If you need a different configuration create a different file based on PNconfig fth The EQUate PNconfigured must be present and non zero in your configuration file It permits you to compile your configuration file before compiling PowerNet bld and prevents compilation of the default configuration file 6 PowerNet TCP IP Stack create PNETver addr PowerNet version string PNET A e Display PowerNet version string 2 5 Default console I O for tasks All PowerN
92. e on a single line When serving scripts from files the script section can extend over several lines Script code N caddr len Returns the command to select Forth as the scripting language asp header N caddr len ASP command header string asp tail caddr len ASP command tail string ScriptEngine caddr len Processes the string as Forth source The data stack is checked on return to ensure system integrity AspProcess caddr len If Forth has been selected as the script language pass the string to SCRIPTENGINE otherwise try to find the Forth script command In practice this means that the language selection command must be on its own as the first script section AspRequest caddr len Extract script section and try to process it All output is done using TYPE and WebSend 35 7 Header scanning HTTP headers are processed by building a list of actions and strings The action is an xt and the string is theheader text that we are interested in Each action has the stack effect caddr len where caddr len is the string after the header and the trailing colon create UploadHdrs addr doCLength Content Length align doCTypel Content Type align 0 0 CheckName src slen name nlen flag Return true if the start of the string src slen contains the entire name name nlen CheckHeader src slen name nlen flag Return true if the start of the string src slen con
93. e prepended to the page name given to InitUpd The string is held as a counted string in the buffer Make sure that your application sets FileDir to point to its own pages The directory name must not end in a separator The directory must exist before use 1 value hPostFile handle Handle of the file used to save the download data InitFileUpd MX caddr len Initialise the file reception AddFileUpd caddr len Add the given memory block to the update All blocks except the last contain FlashBlock bytes of data TermFileUpd Terminate the app s binary file update system Chapter 41 Internet RFCs 151 41 Internet RFCs 41 1 What is an RFC Internet standards are generally proposed and honed by various commitees in public documents across the World Wide Web These documents are called RFCs Request for Comments For any standard protocol you will find a number of these documents on the Web Some relevant ones are in the M directory 41 2 Where are the latest versions The web site http www rfc editor org is currently the best source for finding RFCs Another starting place for a search engine you can find them simply by entering the phrase lt protocol gt RFC into the search engine When looking up a protocol be aware of two things 1 Sometimes an RFC describing a protocol is made obsolescent by a later document 2 Most protocols have extension documents posted after their initial release
94. e smDHrebooting warm restart DHCPREQUEST wait ACK NAK sm smDHactions number of states in this machine variable DHCPTimer addr Holds the TICKS time at which the next DHCP action will be performed 0 for no action variable smDHcount X addr Down counter used to provide repetitions and timeouts variable smDHstate n Holds current DHCP state create smDHactions addr Execution table containing the xts of the action words setDHstate xt state INTERPRETER word that sets the action of the given state DHCPidle Ns Performed periodically to do DHCP actions and lease checks 20 2 State machine utilitiles SetDHCPtimer ms Set the DHCP timer to time out ms later DHstate N Debug tool to display the current state of the DHCP state machine toDHCPstate ms n state The given state will be executed after the given period in ms and n times if sensitive to the number of times Note that this specifies the interval until the state is executed not the repetition rate of the state 20 3 DHCP Data definitions 20 3 1 DHCP control data These variables contain the working data used to access the DHCP server variable BOOTP XID addr Transaction ID number variable DHCPLease addr Length of DHCP lease in ms variable DHCPLeaseTimer addr TICKS at which lease times out variable DHCP T1 addr Time to RENEW in ms variable DHCP_T2 addr time to REBIND in ms 56 P
95. e xt of a word cleanFTP sv sv that frees any aqdditional resources that are not released by free the service data area For an example see cleanFTP in SERVICES FTP fth Servicel Handle any queued output called in the service task 30 9 Diagnostics Diagnostic code is only compiled if the EQUate DIAGS is set non zero Chapter 31 TCP Echo socket 101 31 TCP Echo socket The Echo server just returns anything it receives to the sender It is a simple test of TCP transmission and reception Only one connection at a time is supported To save code space the Echo server uses the server system in SERVICES Servers fth and Saccept from the BSD layer As discussed in the Telnet chapter HyperTerminal PE is a reasonable test client TCP_PSH value EchoFlags n For fast response for use with an interactive terminal set this to TCP_PUSH For fast bulk response set this to zero 7 equ EchoPort n Port on which Echo server listens Moved to PNconfig fth 100 equ EBLen V n Size of the Echo receive buffer EBLen buffer EchoBuffer addr The Echo receive buffer 60000 equ EchoMs ms Max delay after a connection before the socket is closed if there is no transmission echoEst hs flag Return true if the socket is in ESTABLISHED state echoWait hs flag Wait for something to be received up to the timeout period Flag is returned true if the socket is still ESTABLISHED and there has
96. ec opvec Save the current I O devices on the return stack io NV R ipvec opvec Restore the I O devices from the return stack FindFilePage caddr len struct O typelO The action of SearchPage for pages in files Find a page into memory from its name caddr len returning the structure address and length 36 6 Page look up SearchPage caddr len struct O typelO Find a page from its name caddr len returning the data structure address struct and a type code type If the page cannot be found both return values are zero The action is to look up the name in the HTTPpages voc vocabulary and extract the page type from the PAGEDEF structure If file pages are required the page directory is searched Chapter 37 SMTP Primitives 135 37 SMTP Primitives This code can send any arbitary text via standard eMail systems using the Simple Mail Transfer protocol SMTP Recommended reading includes RFC_821 Simple Mail Transfer Protocol RFC_822 ARPA Internet Text Messages 1 value smtpdiags n Set this non zero to get diagnostic information 200 equ SMTPwait ms Number of milliseconds to wait for an SMTP response from the server If you are using a slow connection you may have to increase this value 256 equ MAXRXSIZE Xo sec Size of the response buffer for messages from the SMTP server MAXRXSIZE buffer SMTPin addr The SMTP receive buffer SMTP Wait hsock Wait for a response from the server
97. ed before each buffer fill operation Note that parts of this code must not be pre empted by the scheduler 23 9 TCP state primitives isTCP_Fin tcp TIF Set if FIN flag bit is set isTCP_Syn tcp TIF set if flag bit is set Set if SYN flag bit is set isTCP_Rst tcp TIF set if flag bit is set Set if RST flag bit is set isTCP_Psh tcp TIF set if flag bit is set Set if PSH flag bit is set isTCP_Ack tcp TIF set if flag bit is set Set if ACK flag bit is set isTCP_Urg tcp TIF set if flag bit is set Set if URG flag bit is set isTCP_SYN ACK tcp flag SFPOO5 Set if SYN and ACK flags are both set SendNoSocket pb tcp ip sk cb Handles sending the necessary RST replies when a connection request is made for a TCP socket we don t know about Go send an RST message The packet buffer is freed set2MSL N cb Start the 2xMSL timer for disconnection setIdle N cb Start the disconnect timer with the IDLE period setConn N cb Start the connect timer with the TCPCONNECTTIME period goSYN REC sk Put the given socket into TCPS_SYN_RECEIVED state This transition is performed by a server goESTABLISHED sk Move the socket into ESTABLISHED state goLAST_ACK sk Move the socket into LAST_ACK state from CLOSE_WAIT goTIME_WAIT sk Move the socket into TIME_WAIT state goCLOSING sk Move the socket into C
98. ee if the problem has already been fixed Please send us enough information including source code on disc or by email to us so that we can replicate the problem and then fix it Please also let us know the serial number of your system and its version number We will then send you an update when we have fixed the problem The level of technical support that we can offer may depend on the Support Policy bought with the product Technical support will only be available on the current version of the product Make as many copies as you need for backup and security The issue softwareis not copy protected The code is copyrighted material and only ONE copy of it should be use at any one time Contact MPE or your vendor for details of multiple copy terms and site licensing As this copy is sold both direct and through dealers and purchasing departments we cannot keep track of all our users If you send us your contact details we will put you on our mailing list This way we will be able to keep you informed of updates and new extensions as they become available If you need technical support from us we will need these details in order to respond to you You will find the serial number of the system on the original issue discs Index Index LH eu er area 19 DE ci a ia 58 E AA teens 30 IPD SIAS Leo oper aio 29 pbdatal nnd as ea 30 HOPPST LOs As 147 pu M EET 13 61 HfilesiZ8 x eb en 147 Wftpconns x inldnie Xx bid dei teens 114 Wf
99. en nr een 89 SV_FESPONSIVE 2s c 9 en 98 tcptxbuff ia se eee reca nennen na 70 SNE ee diately ht 11 PET 116 ER REINE dE ac ER EE 116 EE E EE 116 G T EE 142 A EE T EEEE 80 e EE 74 Close keep iere EES Re DER ia 126 COMMA EE 111 A E E EE ETAT 142 CONLING nenn nen 15 GG E E E E 74 decbyte dedanean Enee gas e D RE EEEE Nga dU xS TEE de cimal censpenrtee adore 15 dhcptype nee e eee ehrer adu namen 58 dhState csi crei croacia 55 GOW u 116 156 EE 92 o REED 126 AL AAA spi nn n inanin 126 Stheragd EE nun iste iai nerais 91 PAVING EE 107 EE 108 EE 108 EE 108 I 212 1 esses csse e eene anrea 108 EE EE RT 108 PE OA TEMERE 108 EE 108 EE MP 108 EE 108 EE 108 EE 109 EE 109 EE 109 E i SNNT RM PME 109 EE 109 El ecneeeeeeneneneeennennennsn nn ennnene nenn 109 A S 114 Ttpdate neueste teet ee Delian deo 108 dE ge iria TE 108 ee 108 D ee AA eenn pnei ARTE ESSEER EEES 108 AAA 108 SS A man nase ee 108 RE cie be 120 E RE RO ana 15 DEPP nic 126 shttpar NOne ee a al 126 Jhttpcontent m ecd e eR erg ie 126 A A ee 126 a e tlle bed epos e Pe iners 126 IpaddresS idilio aio bai 39 O 91 POC id R 39 A near aha Ban 39 i 9 9 EE Ol o adv susanne en obs a nen 39 aan ae ra a 91 IK a ne a ee 92 macaddresS sss cbe be en ae ae 141 TEE D dpowernet EE if Jprotocol i2om ee eier Sand saad ea 91 Pwdresp an este ie a DT rs id dns 33 o en se RB 91 ojo ea 33 M BESSER BE
100. er ta 41 LEE 106 EE 106 olei arn aol beer ee ule der 106 jac C ER 115 Spill pud Peg erg ae 115 ke EE 115 STCPAFAN vila ade serien 111 Srvrstart p s ceie emo e o b b RR SE 100 Startftpserver o ese dh aaa 114 startofpacket e ss p orar no 85 Startrxapp esexeecadiese rinik ESEE E nenne 147 e a GEET 99 BEE Abee EE tree egene Sege 112 Stopftpserver sin senken 114 Stophttptask ee Set Ee 128 SLOPLZAPPp nn tie ai ee ee 147 SPOPteIMet EE 104 EE 115 et DEE 116 string hex ee een ne ee noeh 116 As A E E T 116 StL RE 112 sub hsocke t i b ei AE a bs 41 Sv responsive uns ra nie 98 HEEN an ne DD D rade 98 EE 97 E EE 96 SUCH een weds 97 98 eh EE 99 EE entnehmen 97 usn 50 ee aer 97 98 SvflushOp el ete nenne agent Sie SVIbULfer unse ria nn Paes nad 97 Sviitit nn ana EE Rue p ea ante 99 SVEOy A A en dune deh Md 97 98 EE 97 98 svkillchain u een a 100 SALON acia ate NEAR 14 SVODU ica reia dees 9T SYQUET A sa piree i ranpa era pra rei AiE 98 svshutdown u seres ee re ei 100 E EE 14 SVSTALLUP ee een 100 a GE E a aa 99 a as ee ee dia 97 SVCY Pe ale eier 97 98 EE a ae eeng 112 RTE an ee ege 37 Le EE 10 UCP CLOSE ea ee e EE ADE 76 CCP EE 70 DEE ol o ee 76 PowerNet TCP IP Stack TOPCKsum n Sun Bean Ga euere Tal EE 90 le ee o TEE 13 69 A ti nud T aE E aT eer 74 Le s100 nba KEE 74 le E EE EEN 12 69 e TEE 69 tepdeb g nissen ideas 10 lCcpechotask 29 50 4 ll a des
101. ers will probably produce shorter and faster code by using a compiler macro for EC ew val offset VFX optimising compilers will probably produce shorter and faster code by using a compiler macro for EW ew offset val VFX optimising compilers will probably produce shorter and faster code by using a compiler macro for EW 400ns NS For fast CPUs use this hardware dependent word to ensure at least 400ns between back to back Ethernet chip accesses This is required for correct operation of the pointer register The default version here assumes 4 instructions per iteration at 5ns per instruction and the call return and set up overheads are ignored See FASTCPU above 400ns ES Use this version if your CPU takes at least 400 ns between back to back Ethernet chip accesses See FASTCPU above SetBank bank bank 0 to 3 Select the active register bank 24 6 Diagnostics bank Na Display register contents for currently selected SMC bank reg Lon Display contents of all SMC Ethernet Controller s registers 24 7 Driver Layer eISR bmask Read the bank 2 interrupt status register IST eMMU cmd Send a command to the bank 2 MMU register eTCR1 bmask Read the bank 0 TCRI register EnEtherTx Enable Ethernet transmission Selects bank 0 eSoftRst NA Initiate software reset needed to clear Tx lock up Chapter 24 SMC LAN91C92 4 6 Ethernet Driver Code 81 init
102. ervers fth Web pages may be served from memory or from the FAT file system If you are using the FAT file system you can configure the root directory for web pages and the name of the home page If you do not specify them they will default to PAGES and home htm create pagedir HTTP caddr X G The base directory for pages as a counted string The directory name must not end in a separator create HomePage home asp caddr X G Holds the counted string for the home page 35 1 HTTP specific data These data definitions are required by each HTTP task The data is allocated at the start of the task and released when the task is TERMINATEd The chain SVCHAIN links all the service tasks For details of QVARs see the CGI section below 80 equ HTTPPort X n standard is 80 Define the port used for the HTTP server The standard port is 80 Moved to PNconfig fth 8 equ HQVARS NX n Number of QVARs in each connection and the common area 20 equ QvarName n Length including count byte of a QVAR s name 20 equ QvarData n Length including count byte of a QVAR s data area struct QVarRec n Structure of a single QVAR QVARS QVarRec equ QVARS n Size of a QVAR buffer struct HTTPdata n The standard service data structure is extended for HTTP O equ NO SCRIPT 0 No selected script language identifier 1 equ FORTH_SCRIPT e St Selected script language identi
103. es two ports and must operate before the unit s IP address has been set doDHCPopt option option Process the given option if we know about it and step over it Unknown options are ignored Values for known options are saved in the Givenxxx variables scanDHCPopts bootp len Given the DHCP data area parse the DHCP options RxDHCP pb udp bootp len Process received DHCP and BOOTP packets When we get here we know this is from port 67 to port 68 and that the Ethernet packet was either addressed to us or was broadcast DHCPpacket udp flag Given a UDP header return non zero if the packet is a DHCP packet Used in the UDP layer to route DHCP packets 20 9 State machine initialisation and startup doDHidle smDHidle setDHstate doDHinit smDHinit setDHstate gt doDHselect smDHselect setDHstate gt doDHrequest smDHrequest setDHstate doDHarpcheck smDHarpcheck setDHstate gt doDHbound smDHbound setDHstate doDHrenew smDHrenew setDHstate doDHrebind smDHrebind setDHstate doDHrebooting smDHrebooting setDHstate 68 equ DHCPport port DHCP standard port 60 PowerNet TCP IP Stack create DHCPServiceStruct addr Holds the UDP Service info to run the DHCP code on receipt of DHCP packets or idle on timeout Note that this must match the UDPservice structure in UDP fth runDHCP N Start the DHCP process and wait until a valid IP address has been set Chapter 21 DNS client
104. et tasks should define an input output device used for debugging By default this is CONSOLE as set up for the interactive Forth If you need to change this modify the word ConsoleIO below or provide a version before PowerNet is compiled ConsoleIO N Define the default debug device for PowerNet tasks gt pos n Move to position n in the output stream for EMIT and friends Later versions of the MPE kernel code use a simpler timing mechanism by default 2 6 Default Ethernet and IP addresses These are compiled if they have not been previously defined create EtherAddress addr Holds the Ethernet MAC address six bytes Note that you must obtain these from the IEEE www ieee org or from other sources This definition is usually provided by the Ethernet driver which must be compiled first create IpAddress NV addr Holds the Ethernet IP address four bytes The range 192 168 xxx yyy is commonly used for private networks This definition is usually provided by the Ethernet driver which must be compiled first The data is in network order create EnetIPMask X addr IP mask for addresses on Ethernet port The data is in network order create IPGateway addr Gateway attached to Ethernet port The data is in network order Set to 0 0 0 0 if there is no gateway 2 7 Compiler extensions These words will probably be removed in a future release mask ints Disable interrupts Needed with pre emptive schedule
105. f INVALID SOCKET zero for failure Chapter 15 ICMP handling 43 15 ICMP handling The ICMP implementation is fairly minimal Only the implemented functions are documented Many diagnostics can be enabled by setting the equate ICMPMON to non zero See ICMP FTH ICMPcksum pb flag 0 for a pass Generate the ICMP checksum When used to check an ICMP header it will return 0 for a good checksum EchoRequest pbuf icmp got a ping Handle a PING request RxICMPPacket pbuf OK so we got an IP packet Handle an incoming ICMP packet Chapter 16 Routing packets 45 16 Routing packets The routing table is statically allocated Configuration data is in PNconfig fth 32 constant MAX_IPADDRS n No of entries in the routing table not dynamic yet iproute_struct MAX_IPADDRS equ RT LEN n Size of the routing table RT_LEN Buffer IpRoutes addr This is the main routing table 7200000 constant ROUTE_LIFE ms Two hours in milliseconds 1000 constant ROUTE_SAMPLE_MS ms How often routes are tested im milliseconds variable RouteTicker addr Holds the time to sample route expiry next create EnetIPMask addr IP mask for addresses on Ethernet port The data is in network order create IPGateway addr Gateway attached to Ethernet port The data is in network order STRUCT iproute_struct X size of structure Routing table entry The fields have the prefix IPROU
106. f two unsigned values TxMs secs ms Return the number of seconds required for expiry of the T1 T2 timer NoDHCPserver Chapter 20 DHCP and BOOTP 57 Set up for no known DHCP server AcceptDHCPin Accept incoming DHCP packets by clearing GivenReply RejectDHCPin Reject incoming DHCP packets by setting GivenReply to an non valid value AcceptGiven Transfer the data given by DHCP transactions to the working data 20 5 DHCP state selection Each state is controlled by three values defined here e Entry delay delay before state is executed for the first time e Period period between repetitions of the same state e Count number of repetitions before smDHcount reaches zero goldle A Go to the smDHidle state golnit es Go to the smDHnit state so starting the DHCP process goSelect N Go to the smDHselect state goRequest N Go to the smDHrequest state goARPcheck EL Go to the smDHselect state goBound NES Go to the smDHbound state goRenew A Go to the smDHrenew state goRebind KE Go to the smDHrebind state goRebooting Go to the smDHreboot state 20 6 UDP transmission BOOTPSend 1 pb ipaddr Send BOOTP data as a UDP packet The parameters are pb a pointer to a PBuff containing the UDP data and ipaddr the IP address to send to 20 7 Outgoing message tools Some data is carried as DHCP options in the DHCP packet Options that ma
107. fier for Forth 80000000 equ WEBS_CLOSE mask Status bit to close the connection 40000000 equ WEBS_SCRIPTERR mask Status bit for a script error 118 PowerNet TCP IP Stack 00000100 equ WEBS_ASP mask Status bit for ASP processing 00000002 equ WEBS_KEEP_ALIVE Status bit for keep alive handling O equ PLAIN TYPE 0 The data type indicator for PLAIN data 1 equ GIF_TYPE 1 The data type indicator for GIF data 2 equ HTML_TYPE 2 The data type indicator for HTML data 3 equ ASP_TYPE 3 The data type indicator for ASP data HTML data with server side scripting Output is not buffered 4 equ JPEG_TYPE 4 The data type indicator for JPEG data 5 equ XML_TYPE 5 The data type indicator for XML data 6 equ ASMX_TYPE 6 The data type indicator for ASMX data in web services XML data with server side scripting 7 equ ASPX_TYPE 7 The data type indicator for ASP data XML data with server side scripting Output is buffered 8 equ CSS_TYPE KE The data type indicator for CSS data WebErrCode addr Return the address of the service s error code WebStatus addr Return the address of the service s status flags WebVars addr Return the address of the service s connection variables WebScriptId addr Return the address of the service s script identifier WebOpFlags addr Return the address of the service s operation flags bitO set
108. ft N remaining length of data buffer cell User taddr N temp data pointer cell User trapgen Nc addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr addr PowerNet TCP IP Stack Chapter 6 Extra USER variables generic trap identifier cell User trapspec addr specific trap identifier 23 Chapter 7 Queues 25 7 Queues The PowerNet QUEUE data structure is the head of a linked list of queue buffer data structures usually a PBUF or an I O buffer The first cell of anything that is added to a QUEUE must have a link field at offset 0 the first cell 7 1 QUEUE structure QLock lock out interrupts If QUEUEs are used in interrupts or if the scheduler is interrupt driven place your locking code here Do not forget to change the COMPILER TARGET macros too QUnLock NX reenable interrupts If QUEUEs are used in interrupts or if the scheduler is interrupt driven place your locking code here Do not forget to change the COMPILER TARGET macros too PeekQ queue head Return the first item in the queue without removing it Useful for testing and handling partially full empty buffers Dequeue queue headl0 O indicates nothing to remove Remove the next item from the queue Enqueue buffer queue Add buffer to queue InitQ queue Initialise reset the queue
109. g EPollServer 4 byte Poll server IP address 4 cfg EPollPort 4 byte Poll server port URL cfg EPollURL server domain name URL cfg EPollPage server page name 4 cfg ETransaction Transaction number O cfg Elast defines size used cfg create CfgTemplate addr Default configuration which must match the configuration structure above 39 2 Runtime data 6 buffer EtherAddress addr Holds the Ethernet MAC address six bytes Note that you must obtain these from the IEEE www ieee org or from other sources 1 buffer DNS addr If non zero the first byte indicates that DNS should be used to obtain the poll server s IP address 1 buffer DHCP addr If non zero the first byte indicates that DHCP should be used to obtain the unit s IP address from a local DHCP server 4 buffer IpAddress NV addr Holds the Ethernet IP address four bytes The range 192 168 xxx yyy is commonly used for private networks The data is in network order 4 buffer EnetIPMask addr IP mask for addresses on the Ethernet port The data is in network order 4 buffer IPGateway addr Gateway attached to Ethernet port The data is in network order Set to 0 0 0 0 if there is no gateway 4 buffer PollServer addr Polling server IP address in network order This is the server that the reader unit will connect to The data is in network order 4 buffer PollPort X addr Polling server port address defaults to
110. g task au aa ne 114 33 13 Ee EE 114 34 WWW Support 115 24 1 SUTIN GS sea a ae en a a Da een fnew sashes 115 34 2 Time and EEN 116 343 EE TEE 116 vi PowerNet TCP IP Stack 35 HTTP Server ser tan 117 35 1 HTTP specific dala tree tek bep ht ak ia aca 117 35 2 HTTP E 0o 18010 EE 119 35 2 1 Stream socket isse ebbe eta ds based be REESE ei ee 119 35 2 2 Output to a memory butter 119 35 8 Diagnostic control u ne d CIERRE RAE ENEE EN 120 35 4 Transmit Utilities usse EES HL ra et 120 39 5 CGI erg tt ae innen he 120 35 5 1 Numeric OVARS essen enee eens 122 35 0 ASP SUppOFt Eeer ae ea eed baad eigen a beaded 122 39 1 Header Scanning su e ER ann ees 123 35 8 Form body processing 0c cece eee een eee eee eben hen 124 A 124 35 8 2 Application words A Eed ere A a EN REENEN A E 125 35 9 HTTP headers and responses rr 126 35 10 Serving ls wenns na aa ade 127 33 11 HTTP servicet sk u a ea ae a 127 39 12 HTTP listening task denkt tee see a Eech 128 35 13 Notes on memory usage 128 35 14 Authentication opel eee eth ee Selon a aan 129 36 Web page handling 0 ee 131 36 1 Configuratio esie ex teer REPE E eden eyes RERO quB end 131 36 2 Data struct re an ae ee ee Dad PC Que T Venda 131 30 3 Executable pages esset He ee Reed aera ana er RENE 132 36 4 Memory pages n ccc sep t ee en Uia RUPEE KUBA 132 36 4 1 Example memory page 132 30 5 File Pavesi sivas et en A E Newer OR PE
111. group hs 0 Create a new socket of the given characteristics returning the new socket number 1 n on success or zero for failure DO NOT CHANGE the return of INVALID_SOCKET zero for failure sendto hsocket buffer bufflen flags name namelen len err Chapter 27 BSD API layer 89 A factor used to send the buffer bufflenlen block of memory by TCP If name is a valid SOCKADDR_IN structure then save the current remote address for the socket and override with supplied settings using CONNECT send hsocket buffer bufflen flags sent socket_error The more common form of sendto when no address override is required recvfrom hsocket buffer bufflen flags name namelen res Receive data from a socket The parameters are as for SENDTO except that namelen is a pointer to the length If name namelen is a valid SOCKADDR_IN structure on return it will contain the sender s address and port Note that only one packet is read and if you do not read all of it the remaining data is not discarded recv hsocket buffer bufflen flags lenlerr Receive up to bufflen bytes of memory from the current packet returning the length read Note that only one packet is read and if you do not read all of it the remaining data is not discarded Listen hs O SOCKET ERROR Starts a bound socket listening on the port specified by the previous BIND or BINDTO operation LISTEN just changes the mode of the socket it does not wai
112. he following format Chapter 21 DNS client 63 C SN i it de d od 012345678390 12345 do o o o 44 44 4444 NAME TYPE do tha tha o than o tha ooo tat CLASS 4 4 4 4 44 444 444 TTL E 4444444444 RDLENGTH do o 4 4 444444444 RDATA y 4 4 4 4 44 4 44 4444444 P where NAME a domain name to which this resource record pertains TYPE two octets containing one of the RR type codes This field specifies the meaning of the data in the RDATA field CLASS two octets which specify the class of the data in the RDATA field TTL a 32 bit unsigned integer that specifies the time interval in seconds that the re source record may be cached before it should be discarded Zero values are inter preted to mean that the RR can only be used for the transaction in progress and should not be cached RDLENGTH an unsigned 16 bit integer that specifies the length in octets of the RDATA field RDATA a variable length string of octets that describes the resource The format of this information varies according to the TYPE and CLASS of the resource record For example the if the TYPE is A and the CLASS is IN the RDATA field is a 4 octet ARPA Internet address In order to reduce the size of messages the domain system utilizes a compression scheme which eliminates the repetition of domain names in a message In this scheme
113. her machine 6000 equ FirstPortNumber n First ephemeral port number Moved to PNconfig fth 9000 equ LastPortNumber n Last 1 ephemeral port number Moved to PNconfig fth variable LastPortUsed X addr Holds the last ephemeral port number used GetFreePort port Get a free port number the free port numbers count up GetFreePort socket porti Get an ephemeral port for a socket 14 2 TCP control block creation and deletion FlushQ queue Flush the contents of a queue return them to the free queue and FREE the queue itself If queue 0 no action is taken freeConnQ cb Free up any outstanding items on the connection queue DiscardTcpTcb cb Free up all resources in the TCP control block and then free the control block itself MakeTcpCb addrlO Create a new TCP control block from the heap On error zero is returned skTCP sk flag Returns true if the socket protocol is TCP FreeupSocket sk Frees up all allocated memory for a socket sk is assumed to be valid BadSocket sk x flag sk x O and exit caller A factor used by SOCKET for error recovery If flag is non zero x is discarded the socket is freed and exit is from the calling word Socket address family socket type proto group hs 0 Create a new socket of the given characteristics returning the new socket number 1 n on success or zero for failure DO NOT CHANGE the return o
114. hsock bytes SOCKET_ERROR Non BSD function to poll a socket and return the number of bytes available to be read Can be used with both UDP and TCP sockets bind hs name namelen res Associate a socket with a family protocol and port The parameters name and namelen addr len describe a SOCKADDR_IN structure The family must be AF_INET The port is the port number that will be listened to The IP address is usually 0 in which case the system s IP address will be used This allows use with systems which obtain an IP address dynamically e g through DHCP bindTo hs af port ipaddr res A non BSD function that binds a socket to the given set of address family af port port and IP address ipaddr The returned result res is 0 for success otherwise SOCKET_ERROR N B subject to change See BIND closesocket hs O SOCKET ERROR Close the socket This is the close of last resort as it simply reclaims socket memory without performing any notification to the other end Use DISCONNECT in preference connect hs name namelen res Open a connection to a destination defined by the SOCKADDR structure described by name namelen The adress family in the structure must be AF_INET On success res 0 the socket is ready to send and receive data disconnect hs res Disconnect the socket Returns 0 on success DiscAllSockets Disconnect all socket connections socket X address family socket type proto
115. i eco REENEN aes 110 checkheader areas cada 123 checkh mep ge e 8 REENEN ERR AER Ee 126 CHOC KEE 83 al e nee Nee pde 123 Geboter na nee a en 148 CHECK X WANs eis aan 72 ChecksoCketiiis csp tda ed tae dees ees 106 CHECKS ass hid oe ase theaters OP ERU I p Rae 97 checktine eh EE Ee dm Rd de 84 checktzunsent Sab EE EE 72 chktcptxbuff EE 70 eh BEE 74 CKSUN sai era 20 cleandnSQ eis s tm r9 ee 64 ee A DEDE E EEE ENE ESE 105 ek EE 128 cluentst 2c Usb Pp Vp pp eap qum 10 closedatafile o cole rre ee EYE eas 109 closedatasocket ccc cece eens 110 closedatastream cece cece ene 110 CIOSESOCKE LA ia a a 88 clrsocketerror 22 2 9a atu aint tes 41 Clrwebtlag eeng Nester aan 118 COM A RER EHEN RER TAN 15 conftpdata u 0u rb ere sted een 106 COMME GE 88 CONECTO ee ta a 90 ee NEE 98 consolestelnet o4 d 3 a 103 console bu ff i lzswade e ewe ex dvds 119 CONSOLE Divorcio 107 ee RE 119 ee EEN 6 15 ee REN 98 GOEN ek x AL RLEGGG EA A Es 103 CONSU su pea auti Nn poet RR SR KR antes IRR ane ard CONS TIM EE 82 COPyethadd EE REES EE EES EES 40 e amd a an 20 Cpus68l ag toi dad ea an o e dat 20 CPU EE a eg 20 e dE 20 epush8 3006 EES EENS APR 20 ER EE PE 66 CEP S As 135 e d A A EE T E EE ER ENS id 147 E EE EE 115 CES EE 118 CUSCTIOR ara a a a ae sea ee debts a ea 140 e EEN 113 D dat buffer u a 29 datatlashzram ccc cee cee renes re dieiis 141 days EE 116 TEE 15 e TE EE 16
116. ication Telnet servers are private 21 equ FTPcmdPort X u standard is 21 Define the command port used for the FTP server The standard port is 21 20 equ FTPdataPort X u standard is 20 Define the default data port used by the FTP server The standard data port is 20 20 1000 equ FTP_DATA_ESTAB_MS ms Time in milliseconds that an FTP transfer command such as RETR will wait for a passive mode connection 2 equ FTPmaxConns X u If you select multiple files to transfer in an FTP client the client may well open one connection per file Since each connection requires a task service area and two sockets the system can easily run out out of heap space and or sockets See sizeofheap in the control file and MAXSOCKETS in this file 3 11 End of configuration This must be the last section of the configuration file 1 equ PNconfigured n Must be defined non zero after all configuration information has been defined Chapter 4 Debugging tools 15 4 Debugging tools 4 1 Miscellaneous dump addr len Now redundant but does nothing for addr 0 DUMP decimal n display a value in decimal hex Nn display a value in hexadecimal 4 2 Using the system console consoleIO NS Select debug console for output By default this is the CONSOLE device con NV R ipvec opvec Save the current I O devices on the return stack and set I O to the console Restore the previous state with io con
117. ich is processed RxEtherPkt SFPOO1 Get waiting packet from the Ethernet driver layer 25 2 Link failure detection O value Linked Returns true if PowerNet is linked to the world by an active connection create LinkUpChain addr Anchors the chain of words executed when the link is established This chain must be defined at compile time create LinkDnChain X addr Anchors the chain of words executed when the link fails This chain must be defined at compile time AtLinkUp xt Add the word whose zt is given to link up chain INTERPRETER word AtLinkDn Kb Add the word whose xt is given to link up chain INTERPRETER word useDHCP if runDHCP AtLinkUp then Start DHCP when the link comes up useSNTP if runSNTP AtLinkUp then Start SNTP when the link comes up checkLink N flag Check PowerNet s connection and set Linked Returns true if PowerNet is linked to the world by an active connection 84 PowerNet TCP IP Stack variable CheckTime addr Holds the time at which the Ethernet link should next be checked nextCheck NES Set the next link check time This is normally every 200 ms CheckEther N The Ethernet link is checked every so often for an established link If the link fails the Ethernet task halts until the link is re established When it is re established a user extensible chain of actions takes place This permits the system to restart actions such as DHCP a
118. ig fth Application Configuration T WebPost fth POST and binary update Ho MBusClnt fth Modbus framework SOCKETS BSD FTH BSD Sockets API 4 SOCKPRIM FTH Low Level Socket struct manip QUEUES Ho PBUFFERS FTH Queue Buffer handlers T QPRIMS FTH En DeQueue code T QUEUES FTH Describe initialise queues 4 RAM FTH Describe TxRx RAM Useage SERVICES HTTP FTH MultiThreaded Web Server MbusSrvr ModBus Server framework Ho Pages fth Example web page handlers T Servers fth Server core code T TcpEcho TCP Echo Server Ho TELNET FTH Multi threaded Telnet Server T TFTP FTH Simple TFTP Server 4 TestPages Example web pages Chapter 2 PowerNet bld primary build file 5 2 PowerNet bld primary build file When all else fails read the source code PowerNet contains a large number of confiration options These are contained in PNconfig fth You should make copy in your application folder or use an existing configuration file 2 1 Heap PowerNet needs a heap The bigger the heap the more traffic PowerNet can handle 32kb is good for initial testing if the number of free PBUFFS in PNconfig fth see below is kept low If you have too low a heap size or request too many resources PowerNet will complain at start up 0000 8000 equ sizeofheap O no heap nz size of heap 1 equ heap diags true to includ
119. ill need a second form pointing to a different page 40 2 2 After the form After the last item of form data will come the residue which is usually null Note that more than one form may be contained in a web page 40 2 3 Restrictions The following assumptions and restrictions should be noted e Only the last boundary string defined in the message headers is used Thus nested boundary strings are not supported e It is assumed that a boundary string is followed by CR LF or CR LF e Very little checking of the message is performed e For simplicity compatibility with previous versions of PowerNet and to save RAM global variables are used 40 3 Parsing multipart boundaries There are two conditions we have to deal with parsing text lines and detecting the marker at the end of a binary file The second situation is coded within the binary file handler Not caddr flag true for not Return true if the two characters at caddr are not Bdry caddr len 0 1 Returns true if the string matches the boundary string plus two leading dashes Boundary caddr len 1l0 1 Returns 1 if the string is a normal boundary marker 0 if it is not a boundary marker and 1 if it is the last boundary marker NextBoundary flag Read text up to the next boundary marker Flag is returned true if the boundary was the last one 40 4 Flash update application 40 4 1 System interface The flash interface
120. ing Telnet data 32 3 Telnet vectored I O The Telnet server establishes its own generic I O based on that in SERVERS FTH in order to handle IAC processing in the future create ConsoleTN X addr OUT managed by upper driver Function despatch table for Telnet I O OUT is managed by the upper level driver Init ConsoleTN Initialise for console I O by Telnet Note that the Telnet socket must have been set up and and the private service area initialised SVdata equ TNdata len Required size of console service area Console Telnet Select Telnet as the console 32 4 Telnet service tasks tn_announce Issues Telnet signon message tn_login ior 104 PowerNet TCP IP Stack Perform the default login procedure and return non zero if successful so that the return code can be used as a user identifier by higher level code if required defer tn_login ior Perform the assigned login procedure and return non zero if successful so that the return code can be used as a user identifier by higher level code if required When zero is returned for unsuccessful login the Telnet session is terminated See TelnetService tn_quit N Empty the return stack store 0 in SOURCE ID and enter interpretation state TN_QUIT repeat edly SVaccepts a line of input and INTERPRETs it with a prompt if interpreting and ECHOING is on Note that any task that uses TN_QUIT must initialise TIB BASE IPVEC and OPVEC Note tha
121. ion ftp FTPdiags if io consoleio decimal A COMPILER macro used to surround debug code and terminated by FTP FTP debug message FTP ftp io endif A COMPILER macro that terminates an FTP FTP structure fdLine caddr len Display FTP text with leading CR on Forth console If FTPdiags is set to zero no action is taken 33 5 Directory listing for FTP Each line of the display is sort of in Unix ls format 108 PowerNet TCP IP Stack a 1 owner group 1803128 Jul 10 10 18 1s 1R Z d 2 2 Z22 1 owner group O May 9 19 45 Softlib create months addr String containing 3 character text for the months ftpDate NSS Display the current directory entry s date in the form Mmm dd yyyy e g Apr 30 2012 ftpDirLine NX Display a directory entry in FTP format FTP clients get the size information from this format ftpFile Ns List the file data for the last file found ftpdir A ee Display a list of files in FTP format ftpDirNlst Display a list of file names in FTP NLST format 33 6 Status returns ftpResp N caddr len Send the string plus a CR LF pair to the command socket and optionally to the console ftp150 Y Return status 150 about to transfer data ftp200 Return status 200 good command ftp202 Return status 202 not needed ftp211 Return status 211 not available ftp230 Return status 230 user logged in
122. ion e g Page not found If len2 is zero no error text body is sent and caddrl lenl is discarded The string caddrl lenl is displayed if lenl is non zero and is usually the resource name that caused the problem weberror caddr1 leni caddr2 len2 err Display a web error message using the given strings and error number The string caddr2 len2 contains the error description e g Page not found If len2 is zero no error text body is sent and caddrl lenl is discarded The string caddrl lenl is displayed if lenl is non zero and is usually the resource name that caused the problem create HomePage home htm If not already defined HomePage is set to contain the counted string home htm CheckHomePage caddr len caddr len Check for a home page string of the forms or and if found replace with home htm ServeSMem N caddr len type Serve a page from memory according to its page type extracted from the page name Chapter 35 HTTP Server 127 35 10 Serving files 256 equ FileUnit len The size of a part of a file processed at once FileQuery fetch line into TIB Reset the input source specification to the console and accept a line of text into the input buffer AspInterpret Process the current input line as if it is text entered at the keyboard InterpScript Interpret a section of ForthScript which may extend over several lines sendPrev addr Send the source line bef
123. ious constant window size skMorelp sk flag Return true if the socket has an input packet waiting NextWinSize sk size Return the TCP Window size to be used for the packet send genWindowSize sk tcp Given a socket sk and a TCP header at tcp calculate the TCP window size and place it in the TCP header This version is used when genWinSize 1 and implements the bang bang control mechanism 23 8 TCP transmission primitives unsent cb n Number of bytes waiting to be sent If no transmit buffer has been allocated this returns 0 unacked cb n SBDO11 72 PowerNet TCP IP Stack Returns the number of sent bytes awaiting acknowledgement If no transmit buffer has been allocated this returns 0 setAckDelay cb Set the ACK delay timer checkRxWin sk If the receive window is set to 0 and the delayed ACK timer is not running start the delayed ACK timer checkTxUnsent cb The TCP transmit primitive fo SendTcpPkt always clears the delayed ACK timer If there is no more data to send clear the delayed transmit flag and set the delayed ACK timer if if the receive window is zero MakeTCPhdr fl ol sk tcp Take data from the socket sk and create a TCP header at tcp The TCP header checksum is set to 0 SendTcpPkt sk fl opt ol dat dl pb tcp pl res Transmit a TCP packet directly through the IP layer sk points to the socket struct to be
124. is am REC Lose eg ds 151 41 2 Where are the latest version 151 41 3 Recommended reading 151 42 Licence EE 153 42 1 Distribution of application program 153 42 2 Warranties and support 0 cece eect een eee tenn eeenes 153 Chapter 1 Introduction 1 1 Introduction 1 1 What Do You Get PowerNet is a TCP IP networking stack code written in Forth with support for 1 Ethernet Layer Reference driver for SMSC LAN91C9x series of Ethernet chips Includes a packet sniffer to test reception and Ping to test transmit and receive Additional Ethernet drivers can be found in the CPU specific drivers directories supplied with your Forth cross compiler 2 SLIP Layer Uses a serial Interface and multiple connections are supported 3 Routing Table IP Hardware routing table with life timers on routes 4 IP Layers 7 p ES e f ICMP handler ECHO Request coded for PING other codes have stubs UDP handler Unconnected data packets DHCP client Permits almost automatic configuration DNS client Converts URLs to IP addresses SNTP client Used to synchronise the local clock TCP handler Connected data streams 5 Socket Layer The sockets interface being used is based on BSD Winsock 6 Services Layer a Primitive TFTP client Trivial File Transfer Protocol b Multi threaded Telnet server for Forth Interpreter over TCP IP c Multi threaded HTTP server with ASP and CGI d Modbus server template e Echo se
125. kenne 141 EE 142 getmacaddress een ii ai tee senso 142 GEMS ii Ed een rannte nade nea 70 EE 70 getmsssyn ack eese ene 71 BOTPDU n i creser ai eed iiia Eege 30 E TEE 122 gotqvar za ned uua ra legte 122 getslipchars susanne ass 85 getsocketerror serge EE States dE 41 Setsocketinfo cece eee eee 88 TO KEE 111 BESA anei n a er aae iaa 111 Pett cpdatal 6m ic ic rege de res iir isaks 70 gettephdr EE 70 getteppktlen nn een et 70 EE 81 gettxpDuf EE 30 E EE 142 get dp ddress un ce mare pets 51 getudpllen isep use ee meee EPE 51 Elf EE 118 PIVENINS EE 56 givengateWay eee tet 56 EE lien E EENS ANE KE RED EPIS 56 REN 56 PowerNet TCP IP Stack LEET 56 E KEE 56 EE 56 ElVensntp oiiiacedsesRh RERO RA dede beri dune 56 ElVenbl c20s2s 0h d ene ese ade 56 REES ua ep ae ditus op getan ird dis 56 a a AAA ad ra ao ee areis 57 g bound ees EE ond mg s 57 gBoclose EE TA e 70 TEE 73 Soestablisbed 6 cece eee eee eee 73 gofin Walt DEE 13 gofin wait EE 13 POL RRE 57 BOINIL an a ae Lade ia 57 E ONE 13 ROUDE ere ra aien 47 48 gorebind eis eres ae ae 57 SOTEDOOCING 6 eee 57 BOTENEW east 57 Eorequest EE 57 EE EK 57 EE 68 gosntpconfigured 6 cece ce eee eee 68 EE EE 68 BOSyH EE 13 EE 74 e ei ele ege Eelere eg rer eege 85 ee 85 gotime WALL een ie 13 g tslipchar EE 85 gottransframeend 0 cece eee eee 85 gottransframeeSc 6 ccc eens 85 H A assiensak sarnana iiei ri tis 58 ha
126. lag Wait for a key and return true if the key is Y EtherSetup Ke Set up the unit s Ethernet address getC N caddr Get a counted string of up to URL characters from the keyboard and save it at caddr This version is compiled if a heap is present getC N caddr Get a counted string of up to 62 characters from the keyboard and save it at caddr This version is compiled if a heap is not present getU N caddr ior Get an unsigned number and place it at caddr Return 0 for success or a null entry getU N caddr Get an unsigned number and place it at caddr BadE NES Warning for unconfigured string E caddr Display the counted string unless the count is 00 or FF in which case display a warning NetSetup iz Configure the unit for the network and server Config Krees Display the Flash configuration area UnitSetup NX Used during production test to set up the unit serial number and customer number UnitSetup Nee Used during production test to set up the unit serial number and customer number Config X Display the EEPROM configuration area Chapter 40 POST handlers and HTTP updates 143 40 POST handlers and HTTP updates The file lt Pnet gt Examples WebPost fth provides example handlers for HTTP POST requests According to the RFCs GET requests are made when the server is left unchanged by the request POST requests are made when the state of the server is or may be changed by the reques
127. ly inappropriate to archive NTP timestamps before bit 0 was set in 1968 a convenient way to extend the useful life of NTP timestamps is the following convention If bit 0 is set the UTC time is in the range 1968 2036 and UTC time is reckoned from Oh Om Os UTC on 1 January 1900 If bit 0 is not set the time is in the range 2036 2104 and UTC time is reckoned from 6h 28m 16s UTC on 7 66 PowerNet TCP IP Stack February 2036 Note that when calculating the correspondence 2000 is a leap year and leap seconds are not included in the reckoning 22 2 SNTP Configuration struct SNTPparams len A set of parameters to configure the SNTP service This structure is the simplest way to interact with the SNTP module The elements have the following meaings sp SNTPserver the IPv4 address of the SNTP server to use sp PollInterval log2 of the interval between polls in seconds e g 5 for a 32 second interval This value is set to 5 by default and you should probably increase it when you are satisfied with your SNTP handling fo sp xtSetTime the xt of a callback to your application to process the received SNTP packet This is called whenever an SNTP packet is received The word receives the address and length of the UDP data i e a SNTP structure described below and should return nothing caddr len Note that the data is in a pbuff that is owned by the SNTP engine and will be discarded Copy required data out of the SNTP struct
128. n caddr len addr addr Generate the question section of a query skipDNSQ caddr len caddr len Skip the query portion of a DNS reponse skipRRname caddr len caddr len Step over the name field in a resource record RR cleanDNSq hs buffer Clean up the query by releasing the buffer and closing the socket 21 4 User words After acquisition of the DNS server s IP address either by specification or by DHCP the only function provided is to convert a domain name string e g www google com into an IPv4 address DNSquery caddr len iplO Send a UDP DNS query message requesting the IP address of the given domain name Returns the IP address for success or zero on failure Chapter 22 SNTP client 65 22 SNTP client As of PowerNet v4 30 8 May 2008 the user interface to the SNTP data has changed and is not compatible with the previous one The code in lt PNet gt SNTP implements most of an SNTP client according to RFC1361 and RFC4330 See also RFC1305 Do not attempt to modify this code until you have absorbed these RFCs If you do not have an NTP server on your network there are public ones available See www ntp org for details Note when testing that advertised public servers are not always avail able Your ISP probably maintains a functioning NTP server O equ SNTPdebug No x Set this non zero to display SNTP debug information during execution 1 equ SNTPactions x Define
129. n item Show the contents of a chain given an item in the chain showColdChain Display the cold chain 17 Chapter 5 Network operations CPU specific 19 5 Network operations CPU specific The file NETCODE FTH contains code that will show significant benefit from being coded or is sensitive to the byte order of the underlying CPU The code in this file is used by PowerNet v3 onwards and should only be compiled once if both PowerNet and NETBOOT FTH are both compiled 5 1 Network order big endian operations Note that these functions have to be capable of fetching 32 bit cells from 16 bit aligned addresses not just from 32 bit aligned addresses Note also that these routines assume a byte addressed CPU w n addr ul6 Network order 16 bit fetch w n u16 addr Network order 16 bit store Must write MSB first if writing to some hardware n addr u32 Network order 32 bit fetch n u32 addr Network order 32 bit store w n w Network order W n E ein Network order version of comma wy CD w Network order W n x Network order version of comma 5 2 Internet checksum Because this code is used so much in the system it is worth coding it for maximum efficiency One of the following equates may be defined any value in the control file to compile CPU specific code for the Internet checksum CPU Cortex Cortex v7 e g M3 but n
130. n closed state CloseSocket sk Prepare a socket for closure Final closure and memory recovery is performed in the TCP idle action to avoid race hazards ChkTcpTxBuff cb ior If the TCPCB does not have a transmit buffer create it Return 0 if the buffer exists or has been created We assume that the TCPCB is valid 23 5 TCP header use GetTCPHdrLen tcp len Extract length of TCP header varies with options GetTCPPktLen ip len SFPOO05 Extract length of TCP packet gt TCPData tcp tcpdata Get pointer to TCP packet data GetTCPDataLen ip len SFP005 Extract length of TCP data packet GetMSS tcp defmss mss SFPO45 If the TCP header in a SYN or SYN ACK packet contains an MSS option return it otherwise return the default value the output is limited to the range 0 defMSS GetMSSsyn tcp mss SFPO45 If the TCP header in a SYN packet contains an MSS option return it otherwise return the default value of 536 Used by servers to read the incoming MSS in a SYN packet Chapter 23 TCP layer 71 GetMSSsyn ack tcp mss SFPO45 If the TCP header in a SYN packet contains an MSS option return it otherwise return the default value of 536 Used by clients to read the incoming MSS in a SYN ACK packet 23 6 TCP checksum handling TcpCksum tcp tcplen iprem iploc cksum A generic TCP checksum function The parameters supplied are used to form a pseudoheader
131. n tha tha e ooo tat ARCOUNT o o 44 44 4444 A query section contains the following fields QNAME RFC 1035 4 1 2 QTYPE RFC 1035 3 2 2 and QCLASS RFC 1035 3 2 4 5 The question section is used to carry the question in most queries i e the parameters that define what is being asked The section contains QDCOUNT usually 1 entries each of the following format O 1 2 3 4 5 67 8 9 012 3 4 5 44 42 4444 444444444 QNAME QTYPE 4 4 4 444 444 444444 QCLASS 4 4 4 44 4444 444444 where QNAME a domain name represented as a sequence of labels where each label consists of a length octet followed by that number of octets The domain name terminates with the zero length octet for the null label of the root Note that this field may be an odd number of octets no padding is used QTYPE a two octet code which specifies the type of the query The values for this field include all codes valid for a TYPE field together with some more general codes which can match more than one type of RR QCLASS a two octet code that specifies the class of the query For example the QCLASS field is IN for the Internet The answer authority and additional sections all share the same format a variable number of resource records where the number of records is specified in the corresponding count field in the header Each resource record has t
132. nclude AppDir AXPNconfig PowerNet configuration include 4ExampleDir NetCode network order stuff include AppDir WebConfig configuration tools include CpuDir drivers EtherSAM7x Ethernet driver include IpStack PowerNet bld PowerNet build The following equates select Flash or EEPROM storage for configuration data Only one should be set Both assume that the standard MPE tools for EEPROM and Flash read write are in use If these tools are not being used you will have to write your own versions of DataFlash gt RAM and RAM gt DataFlash below 1 equ EEPROMconfig N x Set non zero to use EEPROM configuration 0 equ Flashconfig NOTA Set non zero to use Flash configuration 39 1 EEPROM Flash area definition The structure declared here defines the layout of the configuration data region Layout of serial EEPROM or a Flash region which holds configuration information 1024 constant CfgData n Size of the configuration data area 256 equ URL len Size of a buffer of a domain or page name cfg 4 cfg Emagic V 5555AAAA 4 cfg Eunit 4 byte unit number 4 cfg EcustID 4 byte customer ID number 6 cfg EMACaddress 6 byte Ethernet MAC address 1 cfg EDNS non zero if we can do DNS lookups 1 cfg EDHCP non zero for DHCP 4 cfg EIPaddress X 4 byte IPv4 IP addresss 0 1 for DHCP 4 cfg EEnetIPMask 4 byte network IP mask 140 PowerNet TCP IP Stack 4 cfg EIPGateway 4 byte IP gateway 4 cf
133. nd SNTP 25 3 Ethernet task DoRunEther NAVES The task action that handles all general background Ethernet processing task EtherTask addr The Ethernet handler task RunEtherTask Launch the Ethernet support task 25 4 Routing AskForEtherRoute ip addr 0 See if we can get a route using ARP AskForEtherRoute ip addr 0 See if we can get a route using ARP but retrying several times Chapter 26 SLIP interface 26 SLIP interface The SLIP interface is handled by a task using a state machine See SLIP SLIPCOM FTH 26 1 SLIP equates CO equ FRAME_END NV char Frame end character DB equ FRAME_ESCAPE char Frame escape character DC equ TRANS_FRAME_END char Trans Frame end character DD equ TRANS_FRAME_ESCAPE char Trans Frame escape character 1000 equ SLIP_RX_TIMEOUT ms Receive timout in milliseconds 26 2 Slip input functions gotSlipChar char Char is saved in the input buffer gotTransFrameEsc N Received a TRANS FRAME ESCAPE gotTransFrameEnd N Received a TRANS FRAME END gotFrameEsc Received a FRAME ESCAPE StartOfPacket Set up for a new packet EndO0fPacket We got the end of a packet gotFrameEnd We received a FRAME END character GotSlipChar char Handle an incoming SLIP char GetSlipChars Receive characters from a SLIP port until all are in 26 3 Slip output function
134. ndlearpreply ese ssa canst sr ES canes ata 49 handlearprequest nnns 49 DAS CONO tea Ain 110 LEE 120 EE 112 hex gt string su anne 116 hmempage issiezda us eris RU LER d ers Fede 131 homepage i desse eer ek ENEE 126 hpostfile i dee Reste tiha h 149 bhtml type i e 118 http omd WEE I27 http get ee piocaid gxkeweseniost REGES ene VERS 127 Bttp posti iiocsersseiee iE rechter 128 oh EE 10 1 A Een 120 DETDLO cial adi 119 Httppages VOCs ccc ica a rada tad 131 httpport sits shia ie delle nie 14 117 httpserver 2 un sans ana 128 httpservico 2 Ee EE end 128 httpt ask ann ans san ae nl 128 I icnp AAA ag cis visa sen 31 ICMPCKEum eng bet ri E EE ES 43 Index lCmpmnon kin ann een 10 include offered lease opt 58 include paramreq opt 58 include req inf lease opt s 58 include requestaddr opt sss 58 incl de serverid Opt poe PE PR EAS 58 TICA EMMA 116 incteppacket 2 2 0 75 init commonqvarS cece eee eee ee 122 InIt consoleb ft EE 119 init consoleftp dp per REPE ETE 107 init consolehttp e eie Re reb RS 119 indjt consol6SV iii an od 98 injt consoletn 2 2B ratre iari 103 init etherrx dle cc42de 9 2 er Pax dai 81 indjt ethertx o ii ine Sheds aan 81 init notcp soCKet is de ere Rr rr us 69 Re GER 81 init webvarsi EE 122 InItether 2 15 00 ais 81 ind3tfileupd bee eercee Pee He ESIWUS Rie 14
135. nee det E ieacar chads 86 SCNOSUtP ipod id es 68 sendtcopflagS ooooococcococcoccnrna ee eee nee 72 SONO CPOPES a enee ir er ai aiie ni 72 SENdECPpkt u anna 72 EE 88 REDER EE e 72 Sendtoudp dns ai aaa 87 SSES ged Bechter dE es 72 SELVEADA na ann 127 servefil EE 127 SOFVEPAGE O cia red x bep teehee E 127 SELVELSt anne 10 EE 126 service Eden SE 95 SETVICELVECHO EE 95 Service e EE 95 Service NCCP ce nun sera a reed E 95 service modbus cece eee eens 95 service multichat cece eee 95 Service none 95 service telnet ccc ccc eee teens 95 eh EE 99 SELVICEIO Nein Cie 100 E E EE T See ei ci ts T3 setackdela eeh onoir ue dee See 72 EE ER Ee EE 80 setcommongstring cc cece eee eee 121 SOt COMM EE 73 setdatasock Se Seen ege GE PRI 111 setdefaultes cu sda ria 141 setdhcptimer nisse EE 55 S tdhstate c EE 55 sethttptimeout esee e shee es 119 setidlei 11s ii ida edad IM ENS T9 SOCIO O s nissen 45 setiphdr stick didas 47 SELASTLINE is ce ha near Sta ee area ave AAR 121 SetQVar EE 122 setqvardata ii sess lee una nennen nee 121 163 GT ak dE dE 45 A A ena en E aE EALER EREE 67 SELSNEPLIMEr au 67 SEHSOCKELEFFOR e en 41 EE 118 showW socket i en eer ann dae 91 showcoldchain va an 17 Shogezecchaip nee a ee Lf showpacketo icenib eb eperPbven4 vem eere vas 39 showtcpstate ai le sen IE IIS 70 E E EE 99 Skcans end iii ei enin n ESPER DE NENE 7
136. ng them FreeQB pb bf Chapter 9 PBUF buffers 31 Place a PBUF or I O buffer on the relevant free queue N B FreeQB cleans up the buffers before requeueing them Chapter 10 Queue diagnostic routines 33 10 Queue diagnostic routines The code in QUEUES Qdiags fth is only compiled if the equate DIAGS is non zero queue aligned equ qdhead len The head of the list is the original queue header forced to an aligned length cell BUFFHDRSIZE aligned equ qdentry len Each entry in the list consists of a link field plus the original PBUF header The entry must be aligned q queue Display queue info qlen queue len Count queue length qlen queue txtaddr Display the queue length qs Nese Display the lengths of the FreeloQ and the FreePbufQ Chapter 11 System wide equates 35 11 System wide equates This chapter documents DEFINES FTH which contains definitions of constants and equates used throughout PowerNet 11 1 Application definitions O equ INVALID SOCKET 0 Words returning a socket number return zero to indicate an invalid socket 1 equ SOCKET_ERROR X 1 Many BSD layer and lower layers return 1 for an error because a return of 0 as a length is valid It also permits systems to use O lt as an error check Do not change 11 2 Standard TCP IP and Winsock values PowerNet provides a number of standard equates taken from TCP IP definitions and the Winsock API These are
137. nged create SMCvector addr The device vector needed by PowerNet v3 and COMMON ETHERCOM FTH SMCvector constant IPDevice addr IPDevice is the default device name required by ETHERCOM FTH If you have multiple ports only one should be named IPDevice 24 10 System test This code is only compiled if the equate SNIFF is non zero 1536 buffer pbuff NV addr Buffer for SNIFF sniff Listens to the network and displays all the traffic that has a broadcast destination or is for this device SNIFF can be used to test reception Chapter 25 Ethernet processing task 83 25 Ethernet processing task The Ethernet ports are handled by a task which despatches PBUFs to and from other layers of the stack O equ LoseTX NX u When this EQU is set non zero every uth transmit packet will be discarded This equate is used when testing the TCP retry mechanism and for simulating lossy links O equ LoseRX u When this EQU is set non zero every uth receive packet will be discarded This equate is used when testing the TCP retry mechanism and for simulating lossy links 25 1 Ethernet packet handlers Send gt Ether pb rt len Send the data in the supplied PBuf chain params pb is a pbuf set to the IP layer returns bytes sent if OK else SOCKET ERROR EtherIpPacket pb Process a PBUF which holds a received Ethernet IP packet RxEtherPacket pbuf The PBUF holds a received Ethernet packet wh
138. nged for your system create SMIPserver X addr Holds the remote SMTP server IP address in network order Modify this for your own remote SMTP server 25 constant SMTPport port The port number used by SMTP servers Sender addr len Returns a string containing the sender s email address Note the use of the angle brackets Receiver addr len Returns a string containing the receiver s email address Note the use of the angle brackets Domain addr len Returns a string containing the sender s domain name Note the use of the angle brackets 38 2 Sending mail SendBody hsock Send the body of the message All errors are handled by THROWing send demo email ior This shows how to send eMail via SMTP The ior is returned 0 for success Chapter 39 Ethernet and Internet configuration 139 39 Ethernet and Internet configuration The file WebConfig fth defines configuration data and tools for configuring the Ethernet con troller TCP IP settings and other unit details such a remote web site that your equipment connects to These tools are useful during both development and production for initial unit setup You can use this file as a model for your own hardware Please copy this file from the installation folder to your application folder before use To avoid problems with defaults defined in other files compile WebConfig fth before the Ethernet driver or other PowerNet code 7 i
139. not documented here If you are interested see DEFINES FTH Although a large number of these equates are defined and are not currently used they occupy no memory in the target system because these are EQUates rather than CONSTANTs Chapter 12 TCP IP data structures 37 12 TCP IP data structures The definitions are in the file STRUCTS FTH You will find the books TCP IP Illustrated Volumes 1 and 2 useful when exploring the PowerNet data structures 12 1 Primary structures These structures are used in almost all systems STRUCT ether_hdr size of ether hdr structure Ethernet header The fields have the prefix ETHER STRUCT arp hdr size of arp hdr structure ARP header The fields have the prefix AR STRUCT arp_ip_data size of arp ip data structure ARP data STRUCT icmp hdr size of icmp header structure ICMP header structure The fields have the prefix ICMP STRUCT ip hdr size IP header structure The fields have the prefix IP_ STRUCT udp hdr size of udp header structure UDP header structure The fields have the prefix UH_ STRUCT socket NV size of socket structure The main socket structure The fields have the prefix SO_ STRUCT tcpcb N size TCP control block structure Notes e Sequence and ACK numbers are unsigned 32 bit numbers that can wrap They must be compared using circular arithmentic STRUCT port_struct size of structure Port co
140. nsport headers This value should be cell aligned Ethernet packets require 1518 bytes from the start of the Ethernet header to the end of the Frame Check Sequence FCS Note that some Ethernet DMA hardware does transfer the FCS Chapter 3 PowerNet configuration 11 10 equ BUFFHDRSIZE N n header size see Queues PBuffers fth for details 4 equ NUMFREEPBUFS n Number of PBUFs This is the maximum number of packets that can be in transit in PowerNet at any one time The PBUFs are allocated from the heap when PowerNet starts so there must be enough heap space to contain the buffers otherwise you will see a console error message 1 equ TXpbufs n High reliability systems and especially internet facing devices should set this equate to 1 This reserves an extra PBUF for TCP transmission which guarantees that transmission can proceed even if the other NUMFREEPBUFS PBUFs are consumed by incoming data packets as can happen when NUMFREEPBUFS is small a number of sockets are open and or a task is sending a quantity of data on a single socket without checking for input Setting TXpbufs to one can be particularly important when using Telnet over lossy links geologists please note 10 equ TRXBUFFSIZE n Data size in each IO buffer excl hdr TRXBUFFSIZE BUFFHDRSIZE equ TRxB uff n Size of complete IO buffer structure 40 equ NUMTRXBUFFERS n Number of IO buffers TRxBuff NUMTRXBUFFERS equ TRxBuffers n size of T
141. ntains a list of the basic header fields to process BaseHdrs value DefHdrs addr Holds the default header list for file and memory pages ReadHeaders Process the headers after the HTTP command line up to the first blank line Do not use this word for reading part headers If the response headers have already been read this word is a no op 35 8 Form body processing Words are provided for use with form results submitted as a POST request to an ASP page You can use these with simple URL encoded or multipart forms An example of multipart form handling is the file upload application in Examples WebPost fth This example includes boundary handling and parsing code 35 8 1 Tools Correct operation of this code requires a Content Length header in the request In many cases the body of a POST request is a very long line Because this server is designed for systems with limited RAM key value pairs are not read as a single line but are read and parsed character Chapter 35 HTTP Server 125 by character Keys are limited to 31 characters and values to SVtib 32 characters The service s TIB is where they are buffered BodyLeft addr Returns the address holding the remaining size of the HTTP body If no Content Length field has been found ReadHeaders will have set this to 1 BodyLeft n lt Reduce the remaining content by n CGIname caddr Buffer for name assembly CGIval caddr Buffer
142. ntrol data The fields have the prefix PORT_ Unused by systems with only a single port STRUCT iproute_struct X size of structure Routing table entry The fields have the prefix IPROUTE_ The entries are added to when a new IP address is received PSIZE ether_hdr ip_hdr udp_hdr equ PDATA_MAX The size of the largest data block STRUCT SOCKADDR_IN size Used to hold socket family always AF_INET port number and IP address The fields have the prefix SIN_ 12 2 SNMP structures STRUCT TAGLIST_ENTRY size SNMP Tx Rx taglist entry definition The fields have the prefix SNMP_ Chapter 13 Helpers and primitives 39 13 Helpers and primitives AddLink item anchor Used when a new item in the chain already exists e g it has been ALLOCATEd The item is added to the chain Note that this word requires the link to be at offset 0 in the item being added link var addr lay a link in a chain whose head is at var addr Add a link to a chain anchored at address var addr The old contents of var addr are added to the dictionary as the new link and the address of the new link is placed at var addr INTER PRETER only AddEndLink item anchor Add an item a structure to the end of of the chain anchored at anchor The link field must be at offset 0 in item DelLink item anchor remove item from chain Delete Remove an item from a chain achored at address anchor Note that this word require
143. o 0 0 0 0 0 equ useDNS flag Set non zero to compile DNS client code 1 equ DNSauto flag If useDNS and useDHCP are non zero set this non zero to get the DNS server address using DHCP O equ DNSauto flag DNSauto defaults to false if the build does not include both DHCP and DNS O equ useSNTP flag Set non zero to compile SNTP client code 1 equ SNTPauto flag If useSNTP and useDHCP are non zero set this non zero to get the SNTP NTP server address using DHCP undefined SNTPauto if SNTPauto defaults to false if the build does not include both DHCP and SNTP O equ RAMconfig flag This word is now redundant but is left in for compatibility with earlier systems Its function is replaced by the tools in Examples WebConfig fth Some systems use dynamic configuration either because of DHCP or because code is run from Flash and the configuarion is loaded from say serial EEPROM at runtime For these systems set this equate non zero so that some data buffers are created in IDATA or UDATA space rather than CDATA space Sample production configuration routines can be found in Examples WebConfig fth These rely on the words RAM gt DataFlash and DataFlash gt RAM Note that systems that copy Flash to RAM for execution can leave this equate set to zero 10 PowerNet TCP IP Stack 0 equ tftp n True to include TFTP 1 equ tcp n True for TCP as well as UDP UDP is always compiled 1 equ
144. ockid n If blockid is non zero then we are connected STATE IDLE VALUE TFTPState N n Current State Machine state ID 29 3 TFTP State Machine equates 29 4 Event action place holders and defaults The reciver uses these three DEFERred words to handle incoming TFTP events defer TEVENT BeginReceive c addr u okay Process a STARTRX upload to server request defer TEVENT RxData addr len Process a receive data request The parameters describe the TFTP data block NONAME c addr u okay 94 PowerNet TCP IP Stack Default to handle the string that comes with the STARTRX upload to server request Just display the string and return true to carry on NONAME addr len Default to process a received data block Just show the address and length 29 5 Utility Words DiscardTFTP Discard the current TFTP packet AbortTFTP c addr u Display the TFTP error message and discard the current packet Zcount zaddr zaddr len A version of COUNT for zero terminated strings returning the address of the first character and the length 29 6 TFTP State Handlers SmIDLE namelen The TFTP system is idle Perform a lot of error checks and report them if the equate DIAGS is true smSTARTRX N Handles start of receiving a file SmSTARTTX Ac Handles start of a refused transmission request smFINISHEDRX Handles the end of file reception smFINISHEDTX Handles
145. ore this address semaphore InterpSem addr Exclusive access semaphore for the Forth interpreter FileScript Nez Read and process a file with server side scripting until EOF or an error The file is already open and is not closed AspFileReq len Read and process a file of length len with server side scripting The file is already open All input is done using the FileCon Generic I O device see FATcore fth All output is done using TYPE and WebSend badFS Xe yz Discard three items and set error flags FileSend len buff Serve the file using the given buffer FileSend len Serve a plain file without scripting The file is open and the details are in the given PageDef structure ServeFile len type Serve a page from a file according to its page type extracted from the page name The request headers are read if they have not already been read 35 11 HTTP service task CloseHTTP N Run after processing input to see if the connection should be closed Serve404 qaddr qlen Serve a not found page ServePage N qaddr qlen Serve a page defined by the string qaddr glen which may include CGI vars The string is the command line with the command removed http cmd caddr len caddr len Deal with the command line after the command has been recognised The input is the complete line The output is the line without the command http get caddr len 128 PowerNet TCP IP St
146. ory buffer transfers When operating with fast CPUs note the following e The cycle time of the chip is 185ns min back to back access but the read access time is only 40ns This is detailed in the data sheet e At least 400ns is required between a data register access and a pointer register access At least 400ns is required after writing the pointer register and accessing the data register See the data sheet e The words EC and EC and the optional EW and EW 16 bit words by default assume that the SMC chip is memory mapped and that that the SMC memory area is contiguous If you have a 16 or 32 bit bus and one or more low address lines are ignored you must adapt these words yourself to suit your hardware 24 3 Configuration The following must be defined before the file DRIVERS SMC91C9z FTH is compiled const equ n n If you are using a standalone target with heads and you want interactive access to all the registers and bit masks define CONST as CONSTANT otherwise by default CONST is defined as EQU 50000000 const EtherBase addr Define the base address of the Ethernet controller O equ SMC16 flag If SMC16 is non zero the driver will use 16 bit register accesses where possible otherwise it will use two 8 bit accesses SMC16 should only be set non zero for little endian CPUs 1 equ fastCPU n Set this value false if no software intervention is required to meet the 400ns timing requirement before an
147. ot Cortex MO CPU ARM All ARM variants using the 32 bit ISA CPU H8 300H Hitachi H8 300H and H8S CPU 68K Motorola 68xxx CPUs CPU 386 Intel 386 and above i32 20 PowerNet TCP IP Stack If no CPU specific equate is defined the high level code will be used If the checksum words have been defined previously this section of code is ignored defined CPU Cortex if If this equate is defined any value will do a Cortex not MO machine code IP checksum routine will be used code cksum cksum addr len cksum ARM IP Checksum routine This word is safe against alignment issues as the network order word fetch is done as two byte fetches defined CPU ARM if If this equate is defined any value will do an ARM machine code IP checksum routine will be used code cksum cksum addr len cksum ARM IP Checksum routine This word is safe against alignment issues as the network order word fetch is done as two byte fetches defined CPU H8 300H if If this equate is defined any value will do an H8 300H or H8S machine code IP checksum routine will be used defined CPU 68K defined CPU Coldfire or if If this equate is defined any value will do a 68xxx Coldfire machine code IP checksum routine will be used defined CPU 386 if If this equate is defined any value will do a i386 machine code IP checksum routine will be used N B This code has not been tested cksum cksum addr len cksum
148. ound image for POWERNET HTM MemPage favicon ico IPSTACK TestPages favicon ico The page icon for these pages MemPage contact htm IPSTACKY TestPages contact htm Creates embedded memory page CONTACT HTM from the data in IP STACK contact htm MemPage form1 htm 4IPSTACK NTestPagesMformi htm A simple form MemPage thanks htm AIPSTACKANTestPagesNthanks htm The response to FORM1 HTM MemPage form2 htm 4IPSTACK NTestPagesMform2 htm A simple form with ASP and GET handling MemPage form3 htm 4IPSTACK NTestPagesMform3 htm A simple form with ASP and POST handling MemPage thanks asp AIPSTACKANTestPagesNthanks asp The scripted response to FORM2 HTM MemPage thanks3 asp 4IPSTACK NTestPagesNthanks3 asp The scripted response to FORM3 HTM Chapter 36 Web page handling 133 36 5 File pages The defaults for this section assume that the FAT file system in in use create PageDir addr The base directory for pages This will be prepended to the page name given to SearchPage The string is held as a counted string in the buffer Make sure that your application sets PageDir to point to its own pages The directory name must not end in a separator The version here sets the contents to PAGES and is only used if PageDir is undefined here PrepFilename caddr len Prepare a URL to be a file name For Windows DOS file systems convert characters to For Unices do nothing io X R ipv
149. ow Checking is the responsibility of the application cell user my opbuff addr Holds the current output buffer the first cell holding the buffer length BuffEmit char Send a character to the buffer BuffType caddr len Send a string to the buffer BuffCr XC ems Send a CR LF pair to the buffer create ConsoleBuff X addr OUT managed by upper driver Function despatch table for HTTP buffered I O OUT is managed by the upper level driver Buff addr len Return the address and length of the HTTP output buffer Init ConsoleBuff len addr O Initialise for console I O by the HTTP output buffer Len is the required size of the buffer and the address of the buffer is returned for success or zero is returned if the buffer could not be allocated The first cell of the buffer contains the length used the rest is for data Term ConsoleBuff Terminate buffer I O by freeing the buffer 120 PowerNet TCP IP Stack 35 3 Diagnostic control 1 value httpDiags n Set this non zero to get diagnostic information hd httpDiags if consoleio decimal A COMPILER macro used to surround debug code and terminated by HD HD debug message HD hd Httplo endif Terminates a HD HD structure hdLine N caddr len Display text with leading CR on Forth console If httpDiags is set to zero no action is taken 35 4 Transmit Utilities PDATA MAX equ WEB SIZE NX n Maximum
150. owerNet TCP IP Stack variable DHCPServer addr DHCP server IP address wvariable DHCPflags addr Holds the DHCP flags set to 8000 to force broadcast responses or 0 when we can accept unicast responses 20 3 2 DHCP transient data These variables contain data generated by the DHCP transactions It is later manipulated to set system variables and the DHCP control data after validation variable GivenIP IP address given by DHCP or BOOTP variable GivenMask IP mask given by DHCP or BOOTP variable GivenGateway NX IP gateway given by DHCP or BOOTP variable GivenServer IP address of DHCP server given by DHCP or BOOTP variable GivenLease addr Length of DHCP lease in seconds given by DHCP or BOOTP variable GivenT1 addr Time to RENEW in ms given by DHCP or BOOTP variable GivenT2 X addr time to REBIND in ms given by DHCP or BOOTP variable GivenReply addr Set non zero when a DHCP reply has been received but the data has not yet been been pro cessed During this time any following DHCP packets will be discarded variable GivenSNTP addr SNTP server returned by DHCP variable GivenDNS addr DNS server returned by DHCP 20 3 3 DHCP packet layout STRUCT dhcp N len BOOTP and DHCP payload structure after the IP and UDP headers CREATE BOOTPMAGIC addr Magic number used to identify BOOTP and DHCP packets 20 4 DHCP tools umin ul u2 ullu2 Minimum o
151. p string caddr len char caddr len Ignore leading delimiters and return the string to the right of the next delimiter character including the delimiter split addr len char laddr llen raddr rlen Extract a substring at the start of addr len returning raddr rlen the string remaining after char and the substring laddr llen which includes all characters before but not including char If the string does not contain the character raddr is addr len and rlen 0 split LR addr len char laddr llen raddr rlen Extract a substring at the start of addr len returning raddr rlen the string remaining after char and the substring laddr llen which includes all characters before but not including char If the string does not contain the character raddr is addr len and rlen 0 split RL addr len char raddr rlen laddr llen As split LR but the left string is returned topmost csplit addr len char raddr rlen laddr llen 116 PowerNet TCP IP Stack Extract a substring at the start of addr len returning the string raddr rlen which includes char if found and the string laddr llen which contains the text to left of char If the string does not contain the character raddr is addr len and rlen 0 string gt n addr len radix value Converts an ASCI string to a number in the given base Characters are converted to upper case before conversion string gt dec caddr len n Converts an ASCII string as a decimal number
152. parate buffers for each data area In order to avoid additional heap allocations and data copying PowerNet uses a single buffer and moves pointers as the PBUF is moved up and down the TCP IP stack 9 2 Data structures struct pbuf_hdr size size of pbuf_hdr structure PBUF buffer header definition The first four fields 10 bytes are common with the obsolete BF_HDR definition PSIZE pbuf_hdr equ pbuf n Size of complete pbuf structure 3FFF equ BUFFSIZEMASK mask The buffer size is held in the low 14 bits of the 16 bit type field This permits a maximum data size of BUFFSIZEMASK bytes C000 equ BUFFTYPEMASK mask The buffer type is held in the top 2 bits of the 16 bit type field 0000 equ DATABUFFER n Set into the type bits for I O buffers 4000 equ PBUFFER Kon Set into the type bits for PBUFs 9 3 PBUF handling pb size n pb set buffer size Set the size of a buffer and mark it as a PBUF PBHdrStart pbuf addr of packet header Return the address of the current header PBHdrLen pbuf len of packet header Return the length of the current header 30 PowerNet TCP IP Stack PBDataStart pbuf addr of data Return the address of the current data PBDataLen pbuf len of data Return the length of the current data PBDataLen len pbuf of data Set the length of the current data xPBData offset addr Set offset to buffer data bumpPBuffD
153. pport W and W as machine instructions a simple CMOVE version may be faster sm vp Starts the definition of a state machine s states smState Nn n 1 Defines the next state as an EQU and increments the state number sm n Finishes the state machine and defines an equate of the number of states gt maca caddr len dest flag O good Convert an Ethernet MAC address string into six bytes at dest If the string cannot be converted flag is returned non zero The string caddr len is in the form aa bb cc dd ee ff where the number base is hexadecimal Chapter 14 Socket Primitives 41 14 Socket Primitives The file SOCKETS SOCKPRIM FTH contains primitives for the sockets layers GetSocketError ErrorCode Return the last socket error code SetSocketError ErrorCode Set the last socket error code ClrSocketError Clear the last socket error code MAXSOCKETS cells equ SOCKLIST_LEN size The size of the sockets array SOCKLIST_LEN buffer socket_list addr The static sockets array equ socket_list_last addr The address of the last entry in the socket list initsockets Initialise the socket list O value NextSock socknum Returns the next socket number to be used This value is is ranged 0 n 1 not 1 n Sock Step to the next socket number wrapping as required NextSockEntry addr Return the socket list entry address for NextSock add h
154. r FTPannounce Issues FTP signon message decByte u caddr len u caddr len Accumulate the next byte of a comma separated set of numbers e g 1 25 33 4 The accumulator u is shifted left by 8 bits and the next number in the text is added The updated accumulator and remaining text are returned decByte u u Display the top byte of u as a decimal number and shift it left by 8 bits comma N Display a comma FTPabort426 426 Close the data socket and data file and command with a 426 response setDataSock ior Depending on the mode check or establish a data connection Return non zero on error quo char emit Display a double quotes pwdResp N Display the PWD response with no CR LF 2578rcResp NX A 257 response with the source buffer 33 9 Login and security Access to FTP is provided through the FTP verbs words USER PASS and optionally ACCT 112 PowerNet TCP IP Stack defer doFTPuser Process the FTP USER command The default accepts any user Once the user and password have been confirmed the ftpState variable can be set to 1 defer doFTPpass Process the FTP PASS command The default accepts any password Once the user and password have been confirmed the ftpState variable can be set to 1 defer doFTPacct Process the FTP ACCT command The default accepts any password Once the user and password have been confirmed the ftpState variable c
155. r more detils 35 14 Authentication Before PowerNet v4 4 authentication was provided by a deferred word Nobody reported using it so it has been removed to save memory This section shows how to put it back if required All the code to be added can be found towards the end of HTTP FTH More flexibility is provided in v4 4 because it is much easier to parse headers see Exam ples WebPost fth and scripting provides more choice as to which files are secured and which are public Add the line below to the HTTPdata structure int httpLogin login value Add the following definitions WebLogin addr Return the address of the service s login result defer WebAuthenticate caddr len res 0 Given a GET string returns a non zero code for permission to carry on If permission is refused zero is returned WebAuthenticate caddr len resl0 The default action of WebAuthenticate always returns true Restore the following code to HTTP CMD 2dup WebAuthenticate dup 0 if 2drop Null O s Invalid login 401 weberror exit endif WebLogin stash good login result create BaseHdrs addr Contains a list of the basic header fields to process Chapter 36 Web page handling 131 36 Web page handling Examples are given here for pages in memory and pages in files Feel free to experiment with mixed operation but note that the code in lt PNet gt Services Pages fth is maintained by MPE and may will change with future
156. racters It is always preceded by a CR LF pair and terminated by a CR LF pair The third marks the end of the form It is identical to the second type but has two additional characters at the end of the line 40 2 1 Form data Using the form above we receive two blocks of form data between boundary markers Content Disposition form data name appfile filename memcopy s Content Type application octet stream DOR OO OR OR RK RK KKK C COPYRIGHT Note that in our form the submit button is after the file browser so the file is sent first The order in which the elements of the form are sent is the order in which they appear in the HTML of the form The Content Disposition header tells us which element of the form is being returned and the Content Type header tells us the file is being transferred as 8 bit binary There is blank line CR LF pair between the last header and the start of the binary data Note that there is nothing to tell us the size of the data We must rely on detecting the boundary separator unless there is some magic data at the start of the binary data section Content Disposition form data name send Submit This represents the Submit button You can have several buttons of type submit They will 146 PowerNet TCP IP Stack each cause the form response You can use them to decide where to place the data e g primary or secondary application If you want a Cancel button your page w
157. rs unmask ints Re enable interrupts Needed with pre emptive schedulers flushDebug SFPOO3 Flush the debug queue Needed if debug is handled through some buffered serial lines SLIP or Telnet Chapter 2 PowerNet bld primary build file 7 2 8 Compiling PowerNet This section of POWERNET BLD pulls in all the required files Note that if you have coded versions of the network order memory words and or the Internet checksum routine heavily used you can use an existing or create your own for the CPU you are using The file for CPU specific code is NETCODE FTH If you define an EQUATE CPU xxx where xxx is one of ARM 386 68k and so on a CPU specific code definition will be compiled otherwise a default high level and slower version will be used 2 9 Compile the required services This section compiles the required services and establishes a task to handle any output they may need RunServices NV task action This is the action of SERVICETASK which provides I O support for all the services to avoid blocking problems in the service tasks themselves task ServiceTask addr The task used to provide I O for services RunServiceTask Run the service task 2 10 Initialisation Some initialisation code is provided in POWERNET BLD to make it easier to manage exten sions initip initialise the data structures Initialise the PowerNet data structures and the multitasker iptasks
158. rver 7 Examples a Sending mail by SMTP b ModBus client and server templates c POST handler with application binary updater d Configuration tools 1 2 Documentation The main commentary on the code and all the glossaries are generated directly from the source by the DocGen utility supplied with MPEs VFX Forth for Windows Both PDF and HTML versions are provided The code and its DocGen documentation should be considered the primary reference Please read it PowerNet TCP IP Stack Chapter 1 Introduction 1 3 Source Tree PowerNet 4 ARP Address Resolution Protocol 4 DEFINES FTH Various IP Constants qoas DHCP FTH DHCP client 4 DIAGS FTH Diagnostic Test routines 4 DNS fth DNS client GLOBALS FTH Global Vars Buffers ICMP FTH ICMP Packet handlers IP FTH LowLevel IP access NETCODE FTH Network and CPU dependent code POWERNET BLD Stack Build File T PRIMITIV FTH Useful code fragments ROUTING FTH Routing table handler qlcccELI SNTP fth SNTP client Foz STRUCTS FTH Various IP BSD Structures TCP FTH TCP Protocol Handler UDP FTH UDP Protocol Handler USERVARS FTH Required System Variables ETHER Ho ETHTASK FTH Ethernet TxRx Dispatcher Task Ho SMC91C9X FTH Reference Ethernet Driver SLIP T SLIPCOM FTH SLIP interface EXAMPLES T SMIPmail SMTP mail examples Ho WebConf
159. s 416 equ MAXSOCKETS n The maximum number of sockets available in the system The socket data structures are allo cated from the heap when required The amount of data used for each socket depends on e whether it is a UDP or TCP socket more for TCP e whether it is a server socket that requires a service data structure See the chapter on the server architecture for more details of this Do not set MAXSOCKETS much higher than you need under the expected maximum load otherwise overall system response may suffer Note that within PowerNet a socket number is a 16 bit item so the range is 2 65535 Socket 1 is a special case Sockets are numbered from 1 to MAXSOCKETS and socket 1 is special In practice you have MAXSOCKETS 1 sockets to use 6000 equ FirstPortNumber n First ephemeral port number 9000 equ LastPortNumber n Last 1 ephemeral port number 3 9 DNS client 1 equ DNSdebug x Set this non zero to display DNS debug information during execution 53 equ DNSport porti The standard port number for DNS servers 3 equ DNS X u Maximum number of DNS attempts if no response 5000 equ DNSms ms Maximum time in milliseconds allowed for a DNS transaction 512 equ DNS u Maximum size of the DNS payload variable DNSserver addr Holds DNS server or 0 if not configured yet 14 PowerNet TCP IP Stack 3 10 Servers and Services 5 equ ListenQ n TCP listening ports maintain
160. s Send gt Slip pb rt In int Send the data in the supplied PBuf chain PB the first pbuf in the chain only 1 allowed RT points to the required routing table entry int number of bytes sent if OK else SOCKET_ERROR 86 PowerNet TCP IP Stack SendSlipChar char Sends the char to the SLIP port send_frame_esc_char Sends the escape sequence to the SLIP port send frame end char Sends the escape sequence to the SLIP port SendSlipChar char Sends the character to the SLIP port processing escape characters SlipTx pbuf Send the pbuf chain out of the slip port 26 4 SLIP support task O value SlipDevice addr You MUST define a REAL serial port device for SLIP DoSlipPort X task action The action of the slip tasks task SlipPortTask NV addr Slip port task RunSlipTask Run the SLIP port task Changes will be necessary to support multiple SLIP devices The technique used by the TELNET launcher is appropriate See SERVICES TELNET FTH Chapter 27 BSD API layer 87 27 BSD API layer Despite its complexity this layer is unashamedly provided to ease porting applications whose description in the TCP IP literature is in terms of the well known BSD API The Windows Winsock API is similar to the BSD API Note that the PowerNet version does not provide all the facilities of the full BSD API See SOCKETSNBSD FTH 27 1 SOCKET_ERROR returns These words are provided to f
161. s the link to be at offset 0 in the item being removed ExecChain anchor Execute the contents of a chain with the following structure link xt Each word that is run has the stack effect link link Where link is the address of the link field in the structure Thus data that follows the xt can easily be accessed ShowPacket pbuf display the packet A diagnostic gt inet_aton caddr len ipaddr Convert a dotted Internet address string e g 192 168 0 1 into an IPv4 address If the string cannot be converted INADDR_NONE 1 is returned gt inet_digit n n gt gt 8 Perform number conversion of the low byte and shift n right by 8 bits gt inet_ntoa ipaddr c addr len Convert an IP address into a text string c addr len in dotted quad notation aaa bbb ccc ddd the standard text form IPaddress N ipaddr Display a v4 IP address in dotted quad notation Now obsolete IPv4 N ipaddr Display a v4 IP address ipaddr in dotted quad notation IPnet addr Display the v4 IP address stored in network order at addr IPloc addr Display the v4 IP address stored in native local order at addr free addr O 40 PowerNet TCP IP Stack Perform FREE DROP if the input is non zero CopyEthAdd src dest copy ethernet address Copy an Ethernet address This is an ugly bit of code which is faster than using ETHER_ ADDRESS_LEN CMOVE with most VFX compilers If your CPU does not su
162. s 29 Pbhdrst rt ndash Een 29 POIN1 ir EA S A T 30 pbuf EE 29 PUE ia ada 82 et 29 peekq i d Re teten nn ana a ca ah 25 EE 20 PP srorepniin nsii iii 118 TEE 14 e A oa e aane LA 6 E EE 140 pollserver aussah 140 RE iia tad de 88 Lo i d edb r rixt 113 Eh E e EE 37 POSTS Meca ii 128 POMO diurna rita is Mr Prepfilename une aaa 133 processheaders ee nen 123 processpacket 2ibolliccsr6t6i tetanya eei anah 47 e E EE 149 Processp rts mais susanne ee 149 eg d a een ae ie 49 E KEE 10 30 Prise 113 PowerNet TCP IP Stack Q LE EE EE 30 LTE 30 EE 25 UE 113 CUO cpm 25 KT 122 R Ee E EE 141 TAMCOnFigt engen nen 9 e EE 16 le eh e EE 148 readhe ders suisse nee 124 readkey c ae send 125 TEE 125 readralue rss mia 125 rebindallsockets nn 42 recelivebln ry erer ed ansehe a en 148 reciver ir es era 137 RR gx refxdqer 89 E ee nen 89 TECVINT OR EE 87 reiectdhcpin 6 cee eee 57 E EE 89 TOpsOCket ssc ceca sog d she 89 TESCLDLOCK atadas carl ERR Ead 147 Test resktreii anne 87 lun PU LABS 113 right String is i e ea d oh ne eee EN eiis 115 iu ETC 114 TIVE oes dona aas rta Gor a dolce dea gentil om Sane E 113 SEINE EE 113 route LIFE cra 11 45 ro te sample ms soo een 11 45 route search time eee 11 E EE 47 Fouteticker same ame 45 Tundhep Nester 60 runechosocktask eese eens 101 runeth rtaSk deca ecexc a 84 ru nhttptasEl ele dioe we
163. ser keyCount addr count of bytes left in buffer cell user keyQueue addr pointer to interface key queue 6 2 SLIP variables cell User portid addr SCC port identifier 01 0n cell User rxstate addr current rx packet state cell User rxpbuf addr pointer to current rx pbuf cell User rxnow addr pointer to next rx char cell User rxcount addr bytes entered into buffer cell User rxspace X addr space left in buffer cell User txpbuf addr pointer to current rx pbuf 21 22 cell User txnow pointer to next tx char cell User txcount bytes entered into buffer cell User txspace N space left in buffer cell User RXExpSlip i receive expiry time cell User community pointer to community string cell User commlen length of community string cell User pdutype N pdu type Get etc cell User reqid pdu request identifier cell User errStatus A es pdu error status cell User errIndex X pdu error index cell User numVars vars requested in pdu cell User tagsIn NX gt pdu tags in pointer cell User varsOut X me pdu vars out pointer cell User nextVar N pointer to next variable cell User outPacket pointer to outgoing packet buffer cell User replystart start of response cell User replylen N length of response cell User data current data pointer cell User spacele
164. socket socket HSOCKET O See if we can get a socket handle sub hsocket socket If the given socket address is in the table mark its socket as unused If the socket has already been removed no action is taken get socket addr HSOCKET addr O Given a socket handle return the socket address or 0 if the socket is not in use get socket inq HSOCKET glO Return the socket s input queue get socket outq HSOCKET glO Return the socket s output queue find hsocket port ip pcol port hs sk hsocket O Find a socket handle with matching IP protocol and port find hsocket tcpport ips ps ipd pd hs sk hsocket O Find a socket handle with matching IP and protocol and port find hsocket tcpport ips ps ipd pd hs sk hsocket O Find a socket handle with matching IP and protocol and port WaitForIpAddress ME 42 PowerNet TCP IP Stack Waits until we have a valid IP Address i e one that is not 0 0 0 0 numsockets res numsockets Count the number of socket handles in use RebindAllSockets ip gt Rebind sockets to new local IP address 14 1 Ephemeral ports Ephemeral ports are port numbers allocated by TCP IP when you make a connection These are in a range which does not conflict with the well known ports Each socket connection uses a different port number which allows TCP to identify multiple connections from one machine to the same port on anot
165. start required tasks Start all the required tasks PowerNet Start PowerNet PowerNet AE Display PowerNet state 2 11 Sanity checks Next user up size gt if Check that the USER area is large enough Chapter 3 PowerNet configuration 9 3 PowerNet configuration The file lt PNET gt PNconfig fth contains the default configuration for PowerNet To set your own configuration copy lt PNET gt PNconfig fth and rename it You can put the file where you like so placing it in your main application source folder is sensible Then compile your file before PowerNet bld which will ignore the default file if it finds a previously loaded configuration 3 1 Features and Services The following group of equates defines the facilities to be compiled The defaults here can be overridden by defining equates before the configuration file is compiled this can be useful for testing configuration changes 1 equ ethernet n nz for Ethernet systems True to include Ethernet support O equ slip NV n nz to include SLIP True to include a SLIP handler on a serial port O equ GenericIP flag Set this equate true if the Generic IP device structure defined in ETHERCOM FTH is required This is only required for systems using multiple IP devices in future releases of PowerNet 1 equ useDHCP flag Set non zero to compile DHCP client code If you set this and want an IP address to be assigned by a server set IpAddress t
166. t The example here is of uploading a new application binary image to the server DEFERred words are used to handle the target specific actions This example can be used as the basis of other POST handlers especially those using multipart forms For details of form encoding see RFCs 2045 and 2046 These can be obtained from http www rfc editor org To use the system you need PowerNet version 4 62 or later Compile the file lt Pnet gt Examples WebPost fth after the PowerNet build file When the system is running point your browser at the page Reflash htm When you have selected the required file press the Submit button This returns the form results and new binary to a page called NewApp asp which is actually a Forth word that performs the process When it is complete the page naresp asp is served to display the results to the user To provide flexibility in how the new binary is handled a simple interface is provided that can be used to save the new binary code to Flash or a file system e g on an SD card 40 1 Discussion The requirement is to be able to point any browser at the PowerNet web server and to be able to upload a new binary image to it using a form for data entry What is done with this file is application dependent but it may replace the existing application or it may be saved to an SD card 40 1 1 Form In order to send binary data to a server file upload a POST request must be made by the form Here is the H
167. t MAC address at addr route rt Show the routing table entry contents routes N Show all routing table entries qd q List the queue data socket sk Display the supplied socket structure socket HSOCKET Long form display from the supplied socket handle k sk 92 Show socket states in short form 1k Show all active socket states in long form ert Dee Display current socket error zZ PowerNet TCP IP Stack Dump 64kb of memory at 0000 0000 and time the result Mostly used for Telnet checking and performance testing ZZ N Perform Z above until a key is pressed Chapter 29 TFTP receiver 93 29 TFTP receiver The TFTP server receives files from a remote client Only one connection at a time is supported See SERVICES TFTP FTH In order to use the TFTP server you must define the actions required of the TFTP events N B This is alpha test code 29 1 Ident Block create MODULE addr Module name string create VERSION addr Version string create COPYRIGHT addr Copyright string 29 2 Global data O VALUE TFTP_Socket n Socket used by TFTP server 512 VALUE TFTP_BLOCKSIZE N n TFTP data block size TFTP BLOCKSIZE 4 VALUE TFTP_MAXPACKETSIZE N n TFTP data packet size O VALUE TFTP PACKET addr Current TFTP packet address O VALUE TFTP_PACKETSIZE Y n Current TFTP packet data block size O VALUE bl
168. t TN_QUIT clears the stack on exit TNbye ELS Use this to close the connection in Telnet TelnetService The Telnet service task launched for each established Telnet connection 32 5 Telnet listening task TNserverPass One iteration through the Telnet server TelnetServer stay here forever The Telnet listening task TelnetServer stay here forever The Telnet listening task O value TelnetTask Oltask Returns 0 or the Telnet server task if running RunTelnetSockTask Start the Telnet server task StopTelnet NcES Stop the Telnet server 32 6 Diagnostics This code is only compiled if the EQUate DIAGS is set non zero TelnetChain Display data about the Telnet sockets tn 3 synonym Display data about the Telnet sockets Chapter 33 FTP Server 105 33 FTP Server The Powernet FTP server is a multi threaded server that can accept multiple FTP connections The model used is described in SERVERS FTH The code for the command channel is based on the Telnet code The objectives of the design are to use not a lot of RAM and to keep the code size down by not providing many bells and whistles A side effect of the low RAM usage is that directory listings are rather slow Initially the intention was only to support the requirements of RFC959 the primary FTP specification The only client that actually works fully in this mode is WS_FTP In order to support clients
169. t for anything to happen The socket must be a TCP socket Listen hs state true O Check the socket state and return the state and true if it not listening Otherwise just return false waitListener hs flag Wait until a connection is established or closed closing Return flag false if established If the socket is not established there has been an error in the listening socket waitConnQ hs ior Wait until the listening socket has a connection pending Return 0 on success or non zero if the listening socket has failed repSocket hsi hs2 0 Given a socket make another of the same type using hs as a template repService ski sk2 ior create a new service data structure for sk2 using the details in ski as a template WaitNextConn NX hsl hsa O reason 1 Wait for the next connection on listening socket hsl create a socket and service for the connection and return the new socket hsa and 0 If a failure occurs return reason and 1 If the listening socket failed reason is non zero Saccept hs skaddr sklen hsnew SOCKET_ERROR The PowerNet version of the BSD accept call is named Saccept to prevent a name conflict with the input routine accept Wait until a connection has been made to the listening TCP socket hs or there is an error in the socket If a connection has been established transfer it to a new socket hsnew If skaddr is non zero the contents of sklen are at least S
170. tains the entire name name nlen and a trailing semi colon doHeader caddr len list Given a string check it against the given list of headers ProcessHeaders list 124 PowerNet TCP IP Stack We have already received the GET POST line Process each header line and finish at the first blank line ready for the message body This can be used for the header blocks in forms as well as the for the first header doCLength caddr len Process the string to extract the content length data a decimal number A valid results is saved in the HTTP service data s httpClength field variable FormType X addr Holds the status extracted from the first Content Type header This set is true if the header includes multipart form data 80 buffer Boundary NX addr Holds the boundary string nextChar caddr len caddr len char Get the next character from the string and step on MultiPart caddr len Check for the multipart form data field ExtractValue caddr len dest Given a string starting after the name portion of a name value pair e g name text save the value text without any quote marks at dest If there is no value text the destination is left unchanged Boundary caddr len Check for the boundary xxx field doCTypei caddr len Process the string to extract the content type data which is the multipart form item and the boundary string create BaseHdrs addr Co
171. the end of file transmission smRXDATA NAS Handles a received data packet smTXDATA X Handles transmission of a data packet smACKDATA N SS Handles a data acknowledge smWAITFORACK Handles waiting for a data acknowledge TFTP Server Task task TFTPTask addr The TFTP task data structure TFTP_Install flag Starts the TFTP server returning true for success or false for failure SUBJECT TO CHANGE 29 7 Event Action Handlers This code is currently commented out Read it as an application example Chapter 30 Support for TCP services 95 30 Support for TCP services PowerNet supports multithreaded TCP servers that can accept multiple connections The model used is that one task listens on a port establishes a connection passes the socket to a service task to run the service and then creates a new listening socket When a connection to a service task is no longer established a support task cleans up the service specific data closes the service socket and terminates the service task The focus of the tools is for servers using text e g HTTP and Telnet To enable use of standard Forth words and parsing tools a Generic I O device and a TIB are established for each connection From PowerNet v4 6 onwards and then again in v4 8 much attention to reducing RAM usage has taken place This comes at the expense of performance Use of the the low RAM configuration may be necessary for single chip applic
172. the file has been transferred variable BinStatus addr Holds the file receive status 0 good ResetBlock N Reset the next byte pointer StartRxApp A Initialise variables and buffers for file reception Block gt App NE Send the data block to the application All blocks except the last contain FlashBlock bytes of data StopRxApp Nees Clean up after receiving a file addData byte Add the byte to the binary buffer NotBoundary NX Add the partial boundary string to the data and clear the buffer create CrLf NX caddr Holds the four characters CR LF FullBndry N flag 148 PowerNet TCP IP Stack Check the contents of BndryBuff against the start of Boundary which holds the received boundary separator If the data does not match copy the data to the binary buffer If the data matches the complete boundary string return true otherwise return false By definition the marker string does not appear in the the binary The code reads the binary into a buffer that is 80 characters longer than the required Flash block size to accommodate the boundary string 70 chars maximum We check for the sequence CR LF and if found check for the following boundary string ReceiveBinary The separator line between the part headers and the binary file has been read Read the binary up to the concluding part boundary Later code will check if this is the final boundary If the boundary tail
173. ting table only contains entries for the received BOOTP reply and the broadcast address so there is no point in replying to the siaddr or the address in DHCPServerlD if it differs from BOOTPServer DHCPtype msgtype Display the message type as text SendDHCP msgtype pb bootp Send a DHCP message The fields and options are filled in as appropriate for the message type SendDiscover Send a DHCPDISCOVER message SendRequest Send a DHCPREQUEST message SendDecline Send a DHCPDECLINE message doDHidle N The idle action is just to restart the timer doDHinit Ss Send DHCPDISCOVER periodically until we get a response Chapter 20 DHCP and BOOTP 59 doDHselect N Select is currently a no op as we take the first offer we receive doDHrequest Send DHCPREQUEST periodically until we get a response doDHarpcheck The DHCP specification says that clients SHOULD check that the IP address given to them is not used elsewhere If a route is found the process is restarted doDHbound ADU Wait until the T1 timer expires and go to the RENEWING state doDHrenew NES Send DHCPREQUEST periodically until we get a response doDHrebind Atze Send DHCPREQUEST periodically until we get a response doDHrebooting Send DHCPREQUEST periodically until we get a response 20 8 Receive BOOTP DHCP packet DHCP packet reception is treated as a special case because DHCP us
174. tpmaxconns cesis eX IE ENSIS 14 dqvarss nem ee 117 121 ECPCODNG AAA area 74 HEXPDUES usina 11 un cked u near gal FUNSENE occ nase val 3ma6a EE 40 BCopyright EE REY 93 EE 93 EE 93 o eoin eA p E E 121 qvats EE 121 Socket dao 91 Cinet digit rd te 39 askforetherroute necia ino iia a res de 84 bootpsend sn 57 E I er en dor 20 CLlosesocket EE 70 filesend nu kr reegen 127 find hsocket tepporti eee e eee eee Al find Tout e iii hin 45 Pind g EE 121 Freegvar Sailen Bescher Sege uereg ideen 121 Et pact dues 112 Et ppass EE 112 TEE 112 WT neigen 42 getip ddress unseres 141 Eet haben gi Eege Eed Sen 142 gotslipchar micas cm gar 85 ioctlread race nenne ten Hase Hd 87 E E EE 87 TEE 47 pollsocket zucuuse ras are 87 sendslipchar iie 2 20 e c E EES bene pepe 86 155 smtp writelH cc een 135 smtpwrlte o sev ae 135 Csntppsend ee Sac ae Mae e 68 socket sa cn 37 svemit 25 ciar 98 SVkRey 7 resi e er UPR RERUM een sn 97 svterminat 2de bp eed a4 d e Pr pb E de 99 A st opn OTA EEE EYA 103 E EE 142 rebauthenticate cece eee eee eee 129 e TEE 93 KC ENEE 111 HELD en ee ae na andre 114 RS WEE CA iii 107 FEED Line ne een rn 107 SD PIG eis oraig assed sucha en ae di pue 48 ESC E DC 41 sv responsive iria e RR es 98 BUS OT ona 21 22 23 119 NOD MMC 19 DOdY LEP GEET 125 e BE HE 107 Leading ste seh b Red ee ER p hA pei 115 Iisten inn
175. tructure 37 13 Helpers and primitives cece ee 39 14 Socket Primitives 222 sera 41 14 1 Ephemeral ports EE 42 14 2 TCP control block creation and deletion 0 00 cece eee eee eee 42 15 ICMP handl ne de eras heed ine band oud Pa 3 EA Cet den en 43 16 Fee e ENEE E n d c Pa e 45 17 Basic IP Bayer ir era 47 A e RrdereetebepEEERRER KR blu are 4T IT 2 Sending IP packets oeste ERE na 4T 17 3 Receiving IP p acketsn Hrn na oes eenrr ERE SEN ES 4T 18 ARP Handler oos duras da e gun d ROI lb SCR EP rs da 49 19 UDP ET T PT 51 20 DHCP and RBOOTR as eee en RR hes 53 20 1 DHCP BOOTP state machine eures dee de di 53 20 2 State machine utilitiles llsssssssessesssesee ee meras 55 20 3 DHCP Data definitions u tees ee ne ne 55 20 3 1 DHCP control datae ae a RE EE dE EE 55 20 8 2 DHCP transient data EEN e ue edem E p RII ER en 56 20 3 3 DHCP packet layouts reste ea He eek Rei 56 204 DHCP TEE 56 20 5 DHCP state selection 0 cece m he he 57 20 6 UDP transmissi 0 eect eee ee ee enn E b 20 7 Outgoing message tools DT 20 8 Receive BOOTP DHCP packei 23 5 Se deed ENEE en ee 59 20 9 State machine initialisation and startup ssseseesssesee es 59 21 DNS client uy e gae eae E te e C SER eo ata f cs 61 21 1 Configuration essen anerkennen ee che 61 21 2 Queries and reapongen 6 e need ete tenet eenaee 61 21 3 TOONS EE 64 21 4 User words
176. tted address in the dictionary If not previously defined HERE is used name addr flag MPE 0000 Check to see if the supplied address is a valid NFA returning true if the address appears to be a valid NFA This word is implementation dependent For MPE cross compilers a valid NFA for MPE embedded systems satisfies the following e All characters within string are printable ASCII within range 33 126 e String Length is non zero in range 1 31 and bit 7 is set ignore bits 6 5 ip gt nfa addr nfa Attempt to move backwards from an address within a definition to the relevant NFA SF n R depth You can check for stack faults with n SF SF where n describes the stack change between SF and SF If the stack change is different an error message is generated This word will work on most systems in which the return address is held on the return stack JSF NV R depth perform stack check The end of an SF SF structure This word is not strictly portable as it assumes that the Forth return stack holds a valid return address In the vast majority of cases the assumption is true but beware of some 8051 implementations See GE rdepth N n Return the number of items on the return stack rs Display to the console the current contents of the return stack Where possible a word name is also displayed with the data value Chapter 4 Debugging tools 4 4 Cold Chain showExecChai
177. turn the current socket state to the address arg sendtoUDP hsocket buffer bufflen flags pb res res A factor used to send the buffer bufflen block of memory by UDP SaveSktRem sk remip remport A factor to return the socket s current remote IP address and port RestoreSktRem remip remport sk A factor to restore the sockets current remote IP address and port recvInfo sk name A factor to extract the remote IP and port details from a received TCP or UDP packet N B Replaces the now obsolete RecvUDPinfo and RecvTCPinfo RecvInfo uses a socket structure as input 88 PowerNet TCP IP Stack getSocketInfo hs name len If len contains at least SOCKADDR_IN and name is non zero name is the address of a SOCKADDR_IN structure Copy the remote IP address and port details to name 27 3 BSD Style API This is a loose implementation of the BSD sockets interface It is not exactly compliant but will run most BSD style code without too many nasty surprises 04004667F constant FIONREAD x IOCTLSOCKET command code to obtain the number of bytes available 080000001 constant GET_TCPSTATE x IOCTLSOCKET command code to get the TCP state ioctlsocket hs command arg res SOCKET_ERROR Perform socket operations selected by the command parameter Data is returned at arg The supported operations are FIONREAD and GET_TCPSTATE FIONREAD works with both UDP and TCP sockets pollSocket
178. ure sp xtGetTime an optional configuration and is not required for pure SNTP If set it must put the current timestamp on the stack as a 32 32 bit fractional RFC1361 time The stack effect is TimeLo TimeHi The default action is a word that returns a zero timestamp which is SNTP compliant behaviour This configuration option is supplied to give the system better resolution if the clock controller can generate an NTP compliant timestamp int sp SNTPserver IP address of the server to use Must be first int sp PollInterval Time between SNTP polls in seconds as a power of two int sp xtSetTime Callback to alert caller to a new NTP packet int sp xtGetTime xt of word to provide current timestamp or zero if n a end struct idata create SNTPparams addr The SNTPparams parameter block in IDATA space RAM Note This layout must match the layout of the SNTPparams structure above Patch this table with the actions you supply SNTPparams equ SNTPserver Address holding SNTP server IP address 22 3 SNTP state machine The SNTP system is controlled by a state machine which is run whenever the timer fo SNTPtimer times out The action performed is responsible for setting the next state and updating the timer The state machine actions are performed by SNTPidle which is called in the service task States of the SNTP state machine See RFC1361 Chapter 22 SNTP client 67 REBOOT NTPREQUEST Sent
179. urned otherwise SOCKET_ERROR and an error code are returned UDPConnect c addr u port socket ior Attempt to create a UDP socket and connect to a server Caddr u describes the server address either as a name or an IPaddress string and port is the requested port If u is zero caddr is treated as a 32 bit number representing an IPv4 address In this implementation u must be zero On success the socket and zero are returned otherwise SOCKET_ERROR and an error code are returned Chapter 28 PowerNet diagnostic tools 91 28 PowerNet diagnostic tools check_tcp_cksum ip tcp buff 12 flag Check incoming TCP cksum returning true for a good checkum dump_line address bytes Display a small memory area as a single line of bytes followed by the ASCII equivalent protocol protocol Display the protocol type Socket type type Display the socket type iphdr addr Display an ip header udp ip Prints UDP packet information tcpFlags fl Display flag word contents tep ip tcp Prints TCP packet information tcpcb cb Prints TCP packet information Sockaddr in sockaddr in Display the contents of a SOCKADDR IN or SOCKADDR structure show socket NX hs Short form of display of socket data netstat NE Display short form data about all non closed sockets ippkt ip Prints IP packet information etheradd addr Display an Etherne
180. web content sent in one packet WebSend caddr len Send an arbitrary sized data block to the HTTP client 35 5 CGI Support Common Gateway Interface CGI defines how data is passed between a browser client and a server The equivalent of a variable is a name value pair e g submit send Such pairs are sent by the browser after filling in a form CGI variables are URLencoded as key value pairs of the form keyl valuei amp key2 value2 amp When a form response is sent with a GET message the CGI variables are sent after the URI separated from it by a character When a form response is sent with a POST message the CGI variables appear in the body of the message When a GET message is used PowerNet receives the CGI variables before it knows what to do with them They are saved in structures called QVARs which hold counted strings Numeric values are converted from text by the appropriate Forth words Name comparision is case insensitive PowerNet manages two sets of these variables The first is a common set which may be used to hold system data such as the host s IP address The second set is allocated per connection as part of the service data and only exists for the duration of the connection 20 equ QvarName NV n Length including count byte of a QVAR s name 20 equ QvarData n Length including count byte of a QVAR s data area struct QVarRec n Structure of a single QVAR Chapter 35 HT
181. with the underlying system is handled by three DEFERred words 1024 equ FlashBlock len Unit size passed to the application Defer InitUpd caddr len Initialise the app s binary update system The input string is the file name to be received This is passed for validation purposes and in case the file is saved in a local file system Defer AddUpd caddr len Chapter 40 POST handlers and HTTP updates 147 Add the given memory block to the update All blocks except the last contain FlashBlock bytes of data Defer TermUpd Terminate the app s binary update system 40 4 2 Receiving a file 256 buffer Filename addr Buffer holding file name as a counted string 80 equ BndryBlock len Size of additional buffer for boundary detection The maximum size of a boundary string is 70 characters RFC2046 These are prefixed by CR LF at the start and will be followed by in the last boundary line FlashBlock buffer BinBuff addr Buffer for storing binary data BndryBlock buffer BndryBuff addr Buffer for storing potential boundary string data Holds a counted string starting with a CR variable NextByte NV addr Holds the address in BinBuff of the next character to be received variable FileSize addr Holds the number of bytes stored as binary data variable AppSize addr Holds the number of bytes transferred to the application variable BinDone addr Set if
182. y contain an odd number of bytes are forced to a 16 bit boundary c addr b addr 1 58 PowerNet TCP IP Stack COMPILER word saves b at addr and increments addr n addr x addr 4 COMPILER word saves r at addr and increments addr haligned opt opt Align option assumes that options start 16 bit aligned If necessary a zero pad byte is added INCLUDE_SERVERID_OPT opt opt Add served IP address to the options list INCLUDE_REQ_INF_LEASE_OPT opt opt Add request for an ininite lease to the options list INCLUDE_OFFERED_LEASE_OPT opt opt Add the offered lease to the options list INCLUDE_REQUESTADDR_OPT opt opt Add the offered IP address to the options list CREATE ParamRequestList Parameter Request List that indicates which responses we want INCLUDE PARAMREQ OPT opt opt Add parameter request list to the options list addDHCPopts msgtype bootp Add the relevant options for the message type to the options section of the DHCP message UseBroadcast ServerAddr IPAddr ServerAddr If ServerAddr and IPAddr are not the same and IPAddr is not INADDR BROADCAST the initialised value then substitute INADDR BROADCAST for ServerAddr So if siaddr is left at 0 in the DHCP offer the Request will be broadcast GetBOOTPServerAddr ipaddr If there is any doubt about the server IP address then broadcast the reply At this point the rou

Download Pdf Manuals

image

Related Search

Related Contents

Table des matières : Préface  New Features in ARCHLine.XP® 2007  Ferramenta Hidropneumática de Elemento Roscado 74200 Instruções de  Operating Instructions T4 – 24-110  HP LaserJet Enterprise 600 M603n  Tennnat F14 Manual 9010665 Rev. 00  Ferno 173 Series Fernoflex Cot Fastener Kit User Manual  User Manual  

Copyright © All rights reserved.
Failed to retrieve file