-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapplication.c
More file actions
2903 lines (2602 loc) · 134 KB
/
application.c
File metadata and controls
2903 lines (2602 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************
Copyright (C) 2009-23 S Combes
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Code for Application layer protocols :
1. FTP (Client sender only) Partially written
2. POP3 Partial written
3. HTTP (GET and POST) with RFC 7616 auth partially written
*********************************************/
#include "config.h"
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> // for Malloc/free
#include <string.h>
#include <avr/eeprom.h>
#include <avr/interrupt.h>
#include "link.h"
#include "network.h"
#include "transport.h"
#include "application.h"
#include "lfsr.h"
#include "w25q.h"
#include "isp.h"
#include "md5.h"
#include "sha1.h"
#include "sha256.h"
#include "ripemd160.h"
#include "mem23sram.h"
#define EEPROM_IN_SPIRAM (0x0000) // Start of EEPROM copi in SPIRAM
#define FLASH_IN_SPIRAM (0x0400)
extern IP4_address NullIP,myIP;
extern IP4_address BroadcastIP;
extern IP4_address GWIP;
extern IP4_address DNSIP;
extern IP4_address subnetMask;
extern IP4_address subnetBroadcastIP;
extern IP4_address NTPIP;
extern char buffer[MSG_LENGTH];
extern uint8_t ISP_state;
extern char hex[];
uint8_t HA1[]={0x54,0x75,0xfe,0x51,0xa1,0xff,0x26,0xee,0x88,0x28,0x27,0x19,0xcf,0xe8,0xe2,0x1b};
// MD5 of "user:prog@iot-isp:password" - testing only!
uint16_t lfsrsave;
extern uint16_t lfsr;
char tmp[85];
extern uint32_t time_now;
extern uint32_t protect_time;
extern uint32_t time_set;
extern uint8_t deferral;
extern volatile uint8_t timecount;
extern Status MyState;
extern IP4_address IsolatedIP;
extern IP4_address FTP_IP;
extern MAC_address myMAC;
extern uint8_t DHCP_lease[4];
extern TCP_TCB TCB[MAX_TCP_ROLES];
extern uint16_t UDP_Port[MAX_UDP_PORTS];
extern MergedPacket MashE;
extern uint8_t fuseL,fuseH,fuseE;
#ifdef AUTH7616
extern uint8_t nonce;
extern uint8_t opaque;
#endif
// ----------------------------------------------------------------------------------
uint8_t caseFreeCompare(const char * s1,const char * s2, uint8_t len)
{
uint8_t i=0;
while (len--) {
if (toupper(s1[i])!=toupper(s2[i])) return TRUE;
i++;
}
return FALSE;
}
#ifdef HELLO_HTTP_WORLD
// Own file
#else
#ifdef NET_PROG
uint8_t cfmnonce; // make a new webpage for each erase to prevent bookmarking
extern ISP_chipData chipData;
uint8_t uploadTo=0;
#define FLASH_UPLOAD (1<<1)
#define EEPROM_UPLOAD (1<<2)
uint8_t thisMicro=0;
#endif
static const char myhost[]=HOSTNAME;
extern uint8_t dummy;
uint16_t expectLen; // Special use - passing param to callback
uint8_t progress; // Special use - passing param to callback
#ifdef USE_POP3
uint8_t iPOP3_Connect;
#endif
#ifdef WHEREABOUTS
extern uint8_t minute,hour;
extern uint8_t gis,ris,fis; // Locations of GRF (0-11)
extern uint8_t lastMode;
extern IP4_address WHEREABOUTSIP;
#endif
#ifdef USE_HTTP
uint8_t ringBuffer[MAX_RING_BUFFER];
char bdry[70];
uint8_t POSTflags=0; // Note used as bit flags, so more than one may be set
uint8_t bufferPtr=0;
uint16_t bytesInPOST=0; // Bytes left to read in POST body
uint8_t bdryLength=0;
uint16_t debug=16; // temp
#endif
void ISP_EEPROMDataToRAM(void);
void ISP_FLASHDataToRAM(void);
#ifdef USE_SHA256
// ----------------------------------------------------------------------------------
uint8_t AuthorisedSHA256(char * toHash2,char * cnonce,char * response)
{ // RFC 7616 auth method
// Destroys 1st 68 characters of buffer
// 'response' is a 32 byte SHA hash (i.e. each byte can range from 0-255)
SHA256_CTX context;
char nc[]="00000001"; // TODO work on other nos
char tmp[32];
SHA256Init(&context);
SHA256Update(&context,toHash2,strlen(toHash2));
SHA256Final(&context);
memcpy(tmp,buffer,32);
SHA256Init(&context);
SHA256AddExpandedHash(&context,HA1);
SHA256Update(&context,":",1);
//SHA256Update(&context,cnonce,strlen(cnonce)); // Was nonce twice? Chk
SHA256Update(&context,nonce,strlen(nonce));
SHA256Update(&context,":",1);
SHA256Update(&context,nc,strlen(nc));
SHA256Update(&context,":",1);
SHA256Update(&context,cnonce,strlen(cnonce));
SHA256Update(&context,":auth:",1);
SHA256AddExpandedHash(&context,&tmp[16]);
SHA256Final(&context);
return !SHA256_MATCH(response,buffer);
}
#endif
// ----------------------------------------------------------------------------------
// TEST MD5
#ifdef USE_MD5
//#define TEST_MD5
//#define TEST_SHA1
//#define TEST_SHA256
//#define TEST_RIPEMD160
void MDBcast() {
for (int i=31;i>=0;i--) buffer[8+i]=buffer[i];
buffer[0]=tmp[0];
buffer[1]=tmp[1];
buffer[2]=tmp[2];
buffer[3]=tmp[3];
buffer[4]=tmp[4];
buffer[5]=tmp[5];
buffer[6]=lfsrsave>>8;
buffer[7]=lfsrsave&0xFF;
genericUDPBcast((uint16_t *)buffer,20);
}
static void MDLFSRBcast(uint16_t len)
{
uint16_t i;
#ifdef TEST_MD5
MD5_CTX context;
MD5Init(&context);
/*
char tmp3 []="GET:/";
MD5Update(&context,tmp3,strlen(tmp3));
MD5Final(&context);
memcpy(&tmp[16],buffer,16);
MD5Init(&context);
MD5AddExpandedHash(&context,HA1);
char tmp4[]=":NoNcE:";
MD5Update(&context,tmp4,strlen(tmp4));
MD5AddExpandedHash(&context,&tmp[16]);
MD5Final(&context);
uint8_t match=MD5_MATCH(ttmp,buffer);
buffer[0]=(match)?0x11:0x00;
for (int8_t i=31;i>=0;i--) buffer[4+i]=buffer[i];
buffer[0]='B';
buffer[1]='U';
buffer[2]='F';
buffer[3]='=';
genericUDPBcast((uint16_t)buffer,18);
*/
for (uint16_t k=0;k<500;k++) {
i=0;
lfsr=lfsrsave;
while (i<len) {
uint8_t size=rand()%80;
if ((i+size)>=len) {
size=len-i;
}
for (int j=0;j<size;j++) {
tmp[j]=Rnd8bit();
//if ((i+j)==17) tmp[j]^=0x04; // False positive test : Toggle one bit
}
MD5Update(&context,tmp,size);
i+=size;
}
}
MD5Final(&context);
tmp[0]='M';
tmp[1]='D';
tmp[2]='5';
tmp[3]='=';
tmp[4]=len>>8;
tmp[5]=(len&0xFF);
MDBcast();
#endif
#ifdef TEST_SHA256
SHA256_CTX sha256context;
SHA256Init(&sha256context);
/*
SHA256Update(&sha256context,"abc",3);
SHA256Final(&sha256context);*/
for (uint16_t k=0;k<1;k++) {
i=0;
lfsr=lfsrsave;
while (i<len) {
uint8_t size=rand()%80;
if ((i+size)>=len) {
size=len-i;
}
for (int j=0;j<size;j++) {
tmp[j]=Rnd8bit();
// if ((i+j)==17) tmp[j]^=0x04; // False positive test : Toggle one bit
}
SHA256Update(&sha256context,tmp,size);
i+=size;
}
}
SHA256Final(&sha256context);
tmp[0]='S';
tmp[1]='2';
tmp[2]='5';
tmp[3]='6';
tmp[4]=len>>8;
tmp[5]=(len&0xFF);
MDBcast();
#endif
#ifdef TEST_SHA1
SHA1_CTX shacontext;
SHA1Init(&shacontext);
for (uint16_t k=0;k<500;k++) {
i=0;
lfsr=lfsrsave;
while (i<len) {
uint8_t size=rand()%80;
if ((i+size)>=len) {
size=len-i;
}
for (int j=0;j<size;j++) {
tmp[j]=Rnd8bit();
// if ((i+j)==17) tmp[j]^=0x04; // False positive test : Toggle one bit
}
SHA1Update(&shacontext,tmp,size);
i+=size;
}
}
SHA1Final(&shacontext);
tmp[0]='S';
tmp[1]='H';
tmp[2]='A';
tmp[3]='1';
tmp[4]=len>>8;
tmp[5]=(len&0xFF);
MDBcast();
#endif
#ifdef TEST_RIPEMD160
RIPEMD160_CTX ripcontext;
RIPEMD160Init(&ripcontext);
i=0;
lfsr=lfsrsave;
while (i<len) {
uint8_t size=rand()%80;
if ((i+size)>=len) {
size=len-i;
}
for (int j=0;j<size;j++) {
tmp[j]=Rnd8bit();
// if ((i+j)==17) tmp[j]^=0x04; // False positive test : Toggle one bit
}
RIPEMD160Update(&ripcontext,tmp,size);
i+=size;
}
RIPEMD160Final(&ripcontext);
tmp[0]='R';
tmp[1]='1';
tmp[2]='6';
tmp[3]='0';
tmp[4]=len>>8;
tmp[5]=(len&0xFF);
MDBcast();
#endif
}
static void MDCharBcast(char * string,uint16_t len)
{
MD5_CTX context;
MD5Init(&context);
MD5Update(&context,string,len);
MD5Final(&context);
buffer[24]=len>>8;
buffer[25]=(len&0xFF);
MDBcast();
}
// Digests a string and broadcasts the result.
static void MDStringBcast(char * string) // Suitable when does not contain \0
{
uint16_t len=strlen(string);
MDCharBcast(string,len);
}
// Digests a reference suite of strings and prints the results.
void MDTestSuite ()
{
/* From RFC 1321 Test Vectors
MD5("") = d41d8cd98f00b204e9800998ecf8427e
MD5("a") = 0cc175b9c0f1b6a831c399e269772661
MD5("abc") = 900150983cd24fb0d6963f7d28e17f72
MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0
MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b
MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f
MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a
*/
//SHA1_CTX shacontext;
//SHA1Init(&shacontext);
/*
SHA1Init(&shacontext);
SHA1Update(&shacontext,"abc",3);
SHA1Final(&shacontext);
*/
/*
for (int k=0;k<1000;k++) {
int i=0;
while (i<1000) {
uint8_t size=rand()%80;
if ((i+size)>=1000) {
size=1000-i;
}
for (int j=0;j<size;j++) {
tmp[j]=Rnd8bit();
}
SHA1Update(&shacontext,tmp,size);
i+=size;
}
}
SHA1Final(&shacontext);
MDBcast();
*/
//unsigned char digest[16];
/*
MDStringBcast("");
MDStringBcast("a");
MDStringBcast("message digest");
MDStringBcast("abcdefghijklmnopqrstuvwxyz");
MDStringBcast
("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
MDStringBcast
("12345678901234567890123456789012345678901234567890123456789012345678901234567890");
*/
for (uint16_t k=0;k<65534;k++) {
//for (uint16_t k=0;k<5;k++) {
for (int i=0;i<1500;i+=10) {
//for (int i=0;i<1500;i++) {
// for (int i=0;i<1;i++) {
lfsrsave=lfsr;
MDLFSRBcast(i);
}
}
}
#else
void MDTestSuite () {} // Dummy when test suppressed
#endif
//#endif
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
#ifdef USE_FTP
extern uint8_t FTP_status;
extern uint8_t FTP_target;
static uint16_t FTP_passive_port;
extern FTP_job FTP_queue;
// Time and date definitions
// YEAR : uint16_t : 4 digit year, e.g. 2012
// Month : uint8_t : 1-12
// DOM : uint8_t 1-31
// DOW : 0=Mon
/*void Tester()
{
initiateTCPconnection(&MashE,newPort(TCP_PORT),FTP_SERVER_PORT,FTP_IP,TCP_FTP_CLIENT);
}*/
// ----------------------------------------------------------------------------------
uint8_t queueForFTP(uint8_t command,char * filename, char * data)
{ // TODO does not use linked list yet
// Queue a packet for FTP transmission. Will be sent as and when the FTP status
// reaches FTP_OK_SEND (and the filename and command are sent sooner when the status
// reaches FTP_WAIT_SEND to initiate the OK. Uses malloc and hence the calling
// variables are no longer needed once queued.
// Merges the command and filename e.g. "APPE filename.txt" ready to send. Arguably
// wastes 5 bytes per send, but is simpler.
// Return status indicates if memory was available.
static const char cmds[3][5] PROGMEM ={"APPE","STOR","STOU"};
FTP_queue.command=command;
FTP_queue.comd_filename=malloc(5+strlen(filename)); // Space for command and name
if (FTP_queue.comd_filename == NULL) return FALSE;
FTP_queue.payload=malloc(strlen(data));
if (FTP_queue.payload == NULL) {
free(FTP_queue.comd_filename); // Free recently assigned filename
return FALSE;
}
strcpy(FTP_queue.comd_filename,&cmds[command][0]);
FTP_queue.comd_filename[4]=0x20; // Space
strcpy(&FTP_queue.comd_filename[5],filename);
strcpy(FTP_queue.payload,data);
return TRUE;
}
// -----------------------------------------------------------------------------------
void FTPUpdate(void)
{ // Change the state of FTP_status to the 'FTP_target' state.
// Really only valid for FTP_CLOSED (close all)
// FTP_READY (open main connection, but not the secondary)
// Closed, but told to start - so do so.
if (FTP_status==FTP_CLOSED && FTP_target != FTP_CLOSED) {
Initiate_TCP_connection(&MashE,newPort(TCP_PORT),FTP_SERVER_PORT,FTP_IP,TCP_FTP_CLIENT);
FTP_status=FTP_STARTED;
}
// Ready and something in queue - start the passive connection
else if (FTP_status==FTP_READY && (FTP_queue.command!=NONE)) {
Initiate_TCP_connection(&MashE,newPort(TCP_PORT),FTP_passive_port,FTP_IP,TCP_FTP_PASSIVE);
FTP_status=FTP_WAIT_PASSIVE;
}
// Passive connection working and something in queue - send the request
else if (FTP_status==FTP_WAIT_PASSIVE &&
TCB[TCP_FTP_PASSIVE].status==TCP_ESTABLISHED &&
FTP_queue.command!=NONE)
{
TCP_SimpleDataOut(FTP_queue.comd_filename,TCP_FTP_CLIENT,TRUE);
free(FTP_queue.comd_filename); // Send command and filename (e.g. "STOR file")
FTP_status=FTP_WAIT_SEND;
}
// Told to close, or inconsistent state - close down.
else if (FTP_target==FTP_CLOSED || FTP_target < FTP_status) {
TCP_SimpleDataOutProgmem(PSTR("QUIT\r\n"),TCP_FTP_CLIENT,TRUE);
FTP_status=FTP_QUITTING;
}
// Other state changes are done in handleFTP(), which is event driven by
// replies. i.e. called automatically on receipt of packets.
return;
}
// ---------------------------------------------------------------------------------
void handleFTP(MergedPacket * Mash, const uint16_t length)
{ // Handle incoming FTP packet. Moves us through the FTP_state machine.
// Currently expect exact status triplets : e.g. "220". Will not cover all cases
// May need updating. TODO.
uint8_t i;
if (length < 3) return; // Nothing : avoid reading the memory : might have leftovers
if (FTP_status==FTP_STARTED && !strncmp("220",Mash->TCP_payload.chars,3))
{ // Heard the OK response
TCP_SimpleDataOut("USER pi\r\n",TCP_FTP_CLIENT,TRUE);
FTP_status=FTP_USER_SENT;
}
else if (FTP_status==FTP_USER_SENT && !strncmp("331",Mash->TCP_payload.chars,3))
{ // Asking for password
TCP_SimpleDataOut("PASS dummy\r\n",TCP_FTP_CLIENT,TRUE);
FTP_status=FTP_PASS_SENT;
}
else if ((FTP_status==FTP_USER_SENT || FTP_status==FTP_PASS_SENT) &&
!strncmp("230",Mash->TCP_payload.chars,3))
{ // Logged in
TCP_SimpleDataOut("TYPE I\r\n",TCP_FTP_CLIENT,TRUE);
FTP_status=FTP_BIN_SENT;
}
else if (FTP_status==FTP_BIN_SENT && !strncmp("200",Mash->TCP_payload.chars,3))
{ // Binary mode OK
TCP_SimpleDataOut("PASV\r\n",TCP_FTP_CLIENT,TRUE);
FTP_status=FTP_PASV_SENT;
}
else if (FTP_status==FTP_PASV_SENT && !strncmp("227",Mash->TCP_payload.chars,3))
{ // Passive mode OK
i=4;
while (Mash->TCP_payload.bytes[i] < 0x30 || Mash->TCP_payload.bytes[i] > 0x39) i++; // Find intial digit
// Reject if from a different IP address
if (atoi(&Mash->TCP_payload.chars[i]) != (Mash->IP4.source & 0xFF000000)>>24) return;
while (Mash->TCP_payload.bytes[i++] != 0x2C) {} // Find next comma
if (atoi(&Mash->TCP_payload.chars[i]) != (Mash->IP4.source & 0xFF0000)>>16) return;
while (Mash->TCP_payload.bytes[i++] != 0x2C) {} // Find next comma
if (atoi(&Mash->TCP_payload.chars[i]) != (Mash->IP4.source & 0xFF00)>>8) return;
while (Mash->TCP_payload.bytes[i++] != 0x2C) {} // Find next comma
if (atoi(&Mash->TCP_payload.chars[i]) != (Mash->IP4.source & 0xFF)) return;
while (Mash->TCP_payload.bytes[i++] != 0x2C) {} // Find next comma
FTP_passive_port=atoi(&Mash->TCP_payload.chars[i]);
while (Mash->TCP_payload.bytes[i++] != 0x2C) {} // Find next comma
FTP_passive_port=(FTP_passive_port<<8)+atoi(&Mash->TCP_payload.chars[i]);
FTP_status=FTP_READY;
}
else if (FTP_status==FTP_WAIT_SEND && !strncmp("150",Mash->TCP_payload.chars,3)) {
TCP_SimpleDataOut(FTP_queue.payload,TCP_FTP_PASSIVE,TRUE);
free(FTP_queue.payload);
FTP_queue.command=NONE; // TODO linked list needed
TCP_FIN(Mash,TCP_FTP_PASSIVE);
FTP_status=FTP_OK_SEND;
}
else if (FTP_status==FTP_OK_SEND && !strncmp("226",Mash->TCP_payload.chars,3)) {
FTP_status=FTP_READY; // Will set up passive again if more items in queue
}
else if (!strncmp("221",Mash->TCP_payload.chars,3)) // Goodbye message
FTP_status=FTP_CLOSED;
return;
}
#endif
// ----------------------------------------------------------------------------------
#ifdef USE_HTTP
uint16_t Progress(uint16_t start,uint16_t length,uint8_t * result) { // *** NOT TESTED/RIGHT WAY? *** TODO
static const char head[] PROGMEM={"<html><head><title>Progress</title></head><body><label for=\"p\""\
">Progress:</label><meter id=\"d\" value=\"0.60\"></meter></body></html>"};
uint16_t i=0;
while ((length--) && start<sizeof(head)) {
if (i==103) {
result[i++]='0'+(progress/10)%10;
} else if (i==104) {
result[i++]='0'+progress%10;
} else result[i++]=pgm_read_byte(&head[start]);
start++;
}
return sizeof(head); // sizeof(text)-1 should be right ... but doesn't work? TODO
}
// ----------------------------------------------------------------------------------
uint8_t ringBufferCompare(uint8_t ptr,const char * c1,uint8_t len) { // Respects ring
while (len--) {
if (ringBuffer[ptr]!=*(c1++)) return TRUE;
ptr=(ptr+1)%MAX_RING_BUFFER;
}
return FALSE;
}
// ----------------------------------------------------------------------------------
void resetHTTPServer(void)
{ // On SYN on server, make sure params are clear
POSTflags=0;
bufferPtr=0;
bytesInPOST=0;
bdryLength=0;
}
// ----------------------------------------------------------------------------------
void sendHTML(/*const*/ MergedPacket * Mash, uint16_t newData)
{ // Routine called sendHTML because we are server. So if we are asked to do something in HTTP it will
// be to reply (serve). But we may not receive enough in
// a given packet to go ahead and send, especially with POST. But we will have ACK'd.
#ifdef USE_LCD
lcd_clrscr();
#endif
#ifdef AUTH7616
uint8_t authorisedPkt=FALSE;
#else
uint8_t authorisedPkt=TRUE; // No auth, implies all packets are OK
#endif
authorisedPkt=TRUE; // TODO
if (!newData) return; // Just an ACK
// We have a TCP packet with a certain payload length
// only the last 'newData' bytes have not been seen before (usually this will be whole payload)
uint16_t length=Mash->IP4.totalLength-(Mash->IP4.headerLength+Mash->TCP.headerLength)*4;
uint16_t offset=length-newData; // Position of first new data byte
//char toHash2[]="GET:/";
//char cnonce[]="dummy";
//char response[]="dummy";
#ifdef FILESYSTEM
#else
// POST is more of a problem than GET as the form submission can be in the next packet or
// split across two or more. Use a ring buffer to help retain a 'look back' interval.
// Since we are parsing the submitted HTML, we could be spoofed by a crafted packet. Not
// clear what what we can do about that, given that we are code size limited, but do
// inisit on what we expected and watch for buffer overflow. TODO.
if (!(strncmp("POST ",Mash->TCP_payload.chars,5))) { // Assume *** that this is in new packet TODO improve
POSTflags=POST_READING;
uploadTo=0;
ringBuffer[bufferPtr]='\0'; // Prevents immediate false match
// Make slot in flash - for now, always use slot 0.
#define SLOT (0)
//TODO w25SectorErase(((uint16_t)SLOT)<<12,SLOT<<4);
}
if (POSTflags) { // We are reading a POST
linkReadRandomAccess((uint16_t)(&Mash->TCP_payload.chars[offset]-(char *)Mash));
for (uint16_t indx=offset;indx<length;indx++) { // Starts at zero - will re-read 'POST ' - no harm, and
asm("WDR"); // Can be slow - so sort out WDT TODO ???
// helps on next pkt which doesn't have POST preamble (if a continuation)
uint8_t last=ringBuffer[bufferPtr];
bufferPtr=(bufferPtr+1)%MAX_RING_BUFFER;
ringBuffer[bufferPtr]=linkNextByte();
if (POSTflags&POST_INTO_FILE) { // Interpret Intel HEX file (Safe for Unix and Windows
// because we look at ':', mandatory line start, not line endings)
// Within file, we stop using ringBuffer as a ring : always starts at 0 and never fully fill.
if (ringBuffer[bufferPtr]==' ' && bufferPtr!=0) { bufferPtr--; continue; } // Strip spaces
if (ringBuffer[bufferPtr]!=':') {
if (bufferPtr==(MAX_RING_BUFFER-1)) { // We have overflowed - file not as expected
// HTTP_error("Invalid file");
break;
}
continue; // next char
}
// we have read a ':'
if (bufferPtr==0) { // 0 = first line of file, special case : no line to process
bufferPtr=MAX_RING_BUFFER-1; // Drop that ':'
continue;
}
// So now buffer contains a line to process, with initial ':' dropped. Ends \n or \r\n.
// Intel hex format "ccaaaatt[bb][bb] ... cs" : Count cc, Address aaaa, Type tt, cc x bytes, then checksum
uint8_t byteCount=(hexDigit(ringBuffer[0])<<4)|hexDigit(ringBuffer[1]);
uint16_t address =(hexDigit(ringBuffer[4])<<4)|hexDigit(ringBuffer[5])|
(((uint16_t)hexDigit(ringBuffer[2]))<<12)|(((uint16_t)hexDigit(ringBuffer[3]))<<8);
uint8_t choice =(hexDigit(ringBuffer[6])<<4)|hexDigit(ringBuffer[7]);
uint8_t csum=(hexDigit(ringBuffer[8+byteCount*2])<<4)|hexDigit(ringBuffer[9+byteCount*2]);
csum+=byteCount+address+(address>>8)+choice;
for (int i=0;i<byteCount;i++) {
buffer[i]=(hexDigit(ringBuffer[8+i*2])<<4)|hexDigit(ringBuffer[9+i*2]);
csum+=buffer[i];
}
if (csum!=0) { /* HTTP_error("Invalid file"); */break; }
// Write to SPI RAM
if (choice==0) memWriteBufferMemoryArray((uint32_t)address,(uint16_t)byteCount,(uint8_t *)buffer);
if (choice==1) { // All read in so move to flash/eeprom
POSTflags=POST_NONE;
uploadTo=EEPROM_UPLOAD; // TODO
if (uploadTo & EEPROM_UPLOAD) {
ISPactivate();
for (address=0;address<chipData.sizeOfEEPROM;address+=16) {
asm("WDR"); // Programming is slow
memReadBufferMemoryArray((uint32_t)address,16,(uint8_t *)buffer);
for (uint8_t i=0;i<16;i++) {
ISPwriteEEPROMbyte(address+i,buffer[i]);
}
}
uint8_t valid=TRUE;
for (address=0;address<chipData.sizeOfEEPROM;address+=16) {
memReadBufferMemoryArray((uint32_t)(address),16,(uint8_t *)buffer);
asm("WDR");
for (uint8_t i=0;i<16;i++) {
uint8_t chk=ISPreadEEPROMbyte(address+i);
valid=valid&&(chk==buffer[i]);
}
}
ISPquiescent();
uploadTo&=(~EEPROM_UPLOAD);
if (valid) { HTTP_WITH_PREAMBLE(TCP_SERVER,UploadSuccess); }
else { HTTP_WITH_PREAMBLE(TCP_SERVER,UploadFailure); }
}
if (uploadTo & FLASH_UPLOAD) {
// For Flash
ISPactivate();
for (address=0;address<chipData.sizeOfFlash;address+=chipData.flashPageSize) {
asm("WDR"); // Programming is slow
for (uint8_t j=0;j<chipData.flashPageSize;j+=16) {
memReadBufferMemoryArray((uint32_t)(address+j),16,(uint8_t *)buffer);
for (uint8_t i=0;i<16;i+=2) {
ISPloadFlashPageLH((j+i)/2,buffer[i],buffer[i+1]);
}
}
ISPwriteFlashPage(address);
}
uint8_t valid=TRUE;
for (address=0;address<chipData.sizeOfFlash;address+=16) {
memReadBufferMemoryArray((uint32_t)(address),16,(uint8_t *)buffer);
asm("WDR"); // Programming is slow
for (uint8_t i=0;i<16;i+=2) {
uint8_t chk=ISPreadFlashHighByte((address+i)/2);
valid=valid&&(chk==buffer[i+1]);
chk=ISPreadFlashLowByte((address+i)/2);
valid=valid&&(chk==buffer[i]);
}
}
ISPquiescent();
uploadTo&=(~FLASH_UPLOAD);
if (valid) { HTTP_WITH_PREAMBLE(TCP_SERVER,UploadSuccess); }
else { HTTP_WITH_PREAMBLE(TCP_SERVER,UploadFailure); }
}
return;
}
else if (choice!=0) break; // Invalid file
bufferPtr=MAX_RING_BUFFER-1; // Reset
} else if (POSTflags&POST_INTO_CONTENT) {
uint8_t ptr=(bufferPtr+MAX_RING_BUFFER-7)%MAX_RING_BUFFER;
if (!ringBufferCompare(ptr,"flashhex",8)) { // NB. Flashhex appears in HTML
POSTflags|=(POST_FILE_NEXT);
continue; // Won't match again this cycle
}
if (!ringBufferCompare(ptr,"toeeprom",8)) { // NB. toeeprom appears in HTML
uploadTo=EEPROM_UPLOAD;
continue;
}
if (!ringBufferCompare(ptr,"toflash",7)) { // NB. toflash appears in HTML
uploadTo=FLASH_UPLOAD;
continue;
}
if (!ringBufferCompare(ptr,"toall",5)) { // NB. toall appears in HTML
uploadTo=FLASH_UPLOAD|EEPROM_UPLOAD;
continue;
}
}
if (last=='\r' && ringBuffer[bufferPtr]=='\n') { // End of line, so parse line.
// While in Header, we are looking for patterns:
// a) "Content-Length: xxx" for unknown no of digits x, 1 to 5
// b) "boundary=--[& <=70 chars]"
// c) "\r\n\r\n" : end of header
// Once past Header, we're looking for name="flashhex", then the next \r\n\r\n pair.
// File ends when we see boundary again.
if (POSTflags&POST_READING) { // still in header
if (!bytesInPOST) { // Not found length yet
uint8_t digitCount=0;
uint8_t ptr=(bufferPtr+MAX_RING_BUFFER-2)%MAX_RING_BUFFER; // Must keep +ve
uint16_t mult=1;
while (isdigit(ringBuffer[ptr])) {
bytesInPOST+=((uint8_t)ringBuffer[ptr]-'0')*mult;
digitCount++;
if (digitCount>5) break;
mult*=10;
ptr=(ptr+MAX_RING_BUFFER-1)%MAX_RING_BUFFER;
}
if (digitCount==0 || digitCount>5) { bytesInPOST=0; }
else {
if (ringBufferCompare((ptr+MAX_RING_BUFFER-15)%MAX_RING_BUFFER,
"Content-Length:",15)) bytesInPOST=0;
}
// Now bytesInPOST non-zero => bytesInPOST correct.
}
if (!(POSTflags&POST_FOUND_BDRY)) { // Still looking for boundary
for (uint8_t i=1;i<71 && (!(POSTflags&POST_FOUND_BDRY));i++) { // can technically be 1 to 70 bytes
uint8_t ptr=(bufferPtr+MAX_RING_BUFFER-2-10+MAX_RING_BUFFER-i)%MAX_RING_BUFFER;
if (!ringBufferCompare(ptr,"boundary=--",11)) {
POSTflags|=POST_FOUND_BDRY;
bdryLength=i;
ptr=(bufferPtr+MAX_RING_BUFFER-1+MAX_RING_BUFFER-i)%MAX_RING_BUFFER;
for (uint8_t j=0;j<bdryLength;j++) {
bdry[j]=ringBuffer[ptr];
ptr=(ptr+1)%MAX_RING_BUFFER;
}
}
}
}
uint8_t ptr=(bufferPtr+MAX_RING_BUFFER-3)%MAX_RING_BUFFER;
if (!ringBufferCompare(ptr,"\r\n",2)) {
POSTflags&=(~POST_READING);
POSTflags|=(POST_INTO_CONTENT);
continue; // Need new loop iteration before we process more
}
} else { // into payload
if (POSTflags&POST_FILE_NEXT) {
uint8_t ptr=(bufferPtr+MAX_RING_BUFFER-3)%MAX_RING_BUFFER;
if (!ringBufferCompare(ptr,"\r\n",2)) {
POSTflags&=(~POST_FILE_NEXT);
POSTflags|=(POST_INTO_FILE);
bufferPtr=MAX_RING_BUFFER-1; // So file lines always start at 0
continue; // Need new loop iteration before we process more
}
}
}
}
}
/*
i=0;
if (1==1) { //Mash->TCP_payload.chars[i]=='/') {
while ((++i)<newData) {
if (Mash->TCP_payload.chars[i]=='\r' && Mash->TCP_payload.chars[i+1]=='\n' && Mash->TCP_payload.chars[i+2]=='\r' && Mash->TCP_payload.chars[i+3]=='\n') {
// Mash->TCP_payload.chars[i+4]=='R' && Mash->TCP_payload.chars[i+5]=='=' && Mash->TCP_payload.chars[i+10]=='R' && Mash->TCP_payload.chars[i+11]=='=') {
gis=((Mash->TCP_payload.chars[i+6] -'0')*10+(Mash->TCP_payload.chars[i+7] -'0'))%12; // keep input valid with %12
ris=((Mash->TCP_payload.chars[i+10]-'0')*10+(Mash->TCP_payload.chars[i+11]-'0'))%12;
fis=((Mash->TCP_payload.chars[i+14]-'0')*10+(Mash->TCP_payload.chars[i+15]-'0'))%12;
if (lastMode==MODE_LAN) lastMode=MODE_OFF; // Force a refresh
TCP_SimpleDataOut(PSTR("HTTP/1.1 200 OK\r\nCache-control: no-cache,no-store\r\nConnection: close\r\nContent-Length: 1412\r\n\r\n"),TCP_SERVER);
TCP_ComplexDataOut(&MashE,TCP_SERVER,0,OVERSIZE_WHERE); // Oversize method (uses gis,ris, which may have just changed)
break;
}
}
} else
TCP_SimpleDataOut(PSTR("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n<html><head><title>404 Not Found</title></head><body><h1>Not found</h1></body></html>"),TCP_SERVER,FALSE);
*/
#define ICON_BYTES (0x2868)
// Odd Heisen bug - Sure Mash->HTTP was working before. Mash->TCP_payload.chars is equivalent union.
//} else if (!strncmp("GET ",Mash->HTTP,4))
} else if (!strncmp("GET ",Mash->TCP_payload.chars,4))
{ // It's a GET
if (!authorisedPkt) {
uint8_t len=4; // Skip GET itself
Mash->TCP_payload.chars[3]=':'; // For Hash of method:uri
#define MAX_URI (100) // Assume URI must fit in current pkt. Reasonable (we define URIs)
while (len<MAX_URI && Mash->TCP_payload.chars[len]!='\r') len++; // <200 to avoid overflow
if (len<MAX_URI) {
// First see if the nc is correct.
/*linkReadRandomAccess((uint16_t)(&Mash->TCP_payload.chars[offset]-(char *)Mash)); // Position the read
char c;
while (TRUE) {
do { c=linkNextByte(); } while (c!='n');
if ( linkNextByte()!='c') continue;
if ( linkNextByte()!='=') continue;
char clientNC[10];
}
SHA256_CTX context; // Create H2 - hash of method and URI
SHA256Init(&context);
SHA256Update(&context,Mash->TCP_payload.chars,len);
SHA256Final(&context);
memcpy(tmp,buffer,32);
SHA256Init(&context);
SHA256AddExpandedHash(&context,HA1);
SHA256Update(&context,":",1);
SHA256Update(&context,nonce,strlen(nonce));
SHA256Update(&context,":",1);
SHA256Update(&context,nc,strlen(nc));
SHA256Update(&context,":",1);
SHA256Update(&context,cnonce,strlen(cnonce));
SHA256Update(&context,":auth:",1);
SHA256AddExpandedHash(&context,&tmp[16]);
SHA256Final(&context);
*/
// Need to find cnonce,response and proposed nc
//uint16_t cnon=len;
//AuthorisedSHA256(Mash->TCP_payload.chars,cnonce,response);
}
}
//send401Unauthorised();
// if ((length >= 15 && !caseFreeCompare("favicon.ico",&Mash->HTTP[5],11)) ||
// (length >= 12 && !caseFreeCompare("icon.ico",&Mash->HTTP[5],8)))
if ((length >= 15 && !caseFreeCompare("favicon.ico",&Mash->TCP_payload.chars[5],11)) ||
(length >= 12 && !caseFreeCompare("icon.ico",&Mash->TCP_payload.chars[5],8)))
{
HTTP_WITH_PREAMBLE_CACHE(TCP_SERVER,ISPbitmap);
}
//else if (length >= 12 && !caseFreeCompare(PSTR("isp0.png"),&Mash->TCP_payload.chars[5],8)) // PSTR doesn't work
#ifdef NET_PROG
//else if (length >= 12 && !caseFreeCompare("isp9.bmp",&Mash->HTTP[5],8))