-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
hget.c
2036 lines (1698 loc) · 52.5 KB
/
hget.c
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
/* HTTP getter 1.3
By Konamiman 1/2011 v1.1
By Oduvaldo Pavan Junior 07/2019 v1.3
ASM.LIB, BASE64.LIB and crt0msx_msxdos_advanced.rel
are available at www.konamiman.com
printf_simple.rel and putchar.rel can be obtained at
www.konamiman.com or retrieved from Fusion-C
sdcc --code-loc 0x180 --data-loc 0 -mz80 --disable-warning 196 --no-std-crt0
crt0_msxdos_advanced.rel printf_simple.rel putchar.rel base64.lib asm.lib hget.c
And then:
hex2bin -e com hget.ihx
Comments are welcome: konamiman@konamiman.com (original creator)
ducasp@gmail.com (1.3 update creator)
Version 1.3 should be TCP-IP v1.1 compliant, that means, TLS support, so you
can download files from https sites if your device is compliant.
It also removes an extra tick wait after calling TCPIP_WAIT, as there seems
to have no reason for it and it can lower the performance. Any needed WAIT
should be already done by adapter UNAPI when calling TCPIP_WAIT.
Also I've changed the download progress to a bar, it changes every 4%
increment of file size of known file size or there is a moving character if
file size is unknown. This is way easier on VDP / CALLs and allow better
performance on fast adapters that can use the extra CPU time.
*/
//#define DEBUG
#ifdef DEBUG
#define debug(x) {print("--- ");print(x);print("\r\n");}
#define debug2(x,y) {print("--- ");printf(x,y);print("\r\n");}
#define debug3(x,y,z) {print("--- ");printf(x,y,z);print("\r\n");}
#define debug4(x,y,z,a) {print("--- ");printf(x,y,z,a);print("\r\n");}
#define debug5(x,y,z,a,b) {print("--- ");printf(x,y,z,a,b);print("\r\n");}
#else
#define debug(x)
#define debug2(x,y)
#define debug3(x,y,z)
#define debug4(x,y,z,a)
#define debug5(x,y,z,a,b)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//These are available at www.konamiman.com
#include "asm.h"
#include "base64.h"
typedef unsigned char bool;
#define false (0)
#define true (!false)
#define _TERM0 0
#define _CONIN 1
#define _INNOE 8
#define _BUFIN 0x0A
#define _CONST 0x0B
#define _GDATE 0x2A
#define _GTIME 0x2C
#define _FFIRST 0x40
#define _OPEN 0x43
#define _CREATE 0x44
#define _CLOSE 0x45
#define _SEEK 0x4A
#define _READ 0x48
#define _WRITE 0x49
#define _IOCTL 0x4B
#define _PARSE 0x5B
#define _TERM 0x62
#define _DEFAB 0x63
#define _DEFER 0x64
#define _EXPLAIN 0x66
#define _GENV 0x6B
#define _DOSVER 0x6F
#define _REDIR 0x70
#define _CTRLC 0x9E
#define _STOP 0x9F
#define _NOFIL 0x0D7
#define _EOF 0x0C7
#define TICKS_TO_WAIT (20*60)
#define SYSTIMER ((uint*)0xFC9E)
#define TCP_BUFFER_SIZE (1024)
#define TCPOUT_STEP_SIZE (512)
#define HTTP_DEFAULT_PORT (80)
#define HTTPS_DEFAULT_PORT (443)
#define TCPIP_CAPAB_VERIFY_CERTIFICATE 16
#define TCPFLAGS_USE_TLS 4
#define TCPFLAGS_VERIFY_CERTIFICATE 8
#define MAX_REDIRECTIONS 10
enum TcpipUnapiFunctions {
UNAPI_GET_INFO = 0,
TCPIP_GET_CAPAB = 1,
TCPIP_NET_STATE = 3,
TCPIP_DNS_Q = 6,
TCPIP_DNS_S = 7,
TCPIP_TCP_OPEN = 13,
TCPIP_TCP_CLOSE = 14,
TCPIP_TCP_ABORT = 15,
TCPIP_TCP_STATE = 16,
TCPIP_TCP_SEND = 17,
TCPIP_TCP_RCV = 18,
TCPIP_WAIT = 29
};
enum TcpipErrorCodes {
ERR_OK = 0,
ERR_NOT_IMP,
ERR_NO_NETWORK,
ERR_NO_DATA,
ERR_INV_PARAM,
ERR_QUERY_EXISTS,
ERR_INV_IP,
ERR_NO_DNS,
ERR_DNS,
ERR_NO_FREE_CONN,
ERR_CONN_EXISTS,
ERR_NO_CONN,
ERR_CONN_STATE,
ERR_BUFFER,
ERR_LARGE_DGRAM,
ERR_INV_OPER
};
/* Strings */
#define strDefaultFilename "index.htm";
const char* strTitle=
"HTTP file downloader 1.3\r\n"
"By Oduvaldo (ducasp@gmail.com) 7/2019\r\n"
"Based on HGET 1.1 by Konamiman\r\n"
"\r\n";
const char* strUseQuestionMarkForHelp=
"\r\nFor extended help: hget ?\r\n";
const char* strShortUsage=
"Usage: hget <file URL>|<local file with the URL>|con [/l:<local file name>]\r\n"
" [/n] [/t] [/c] [/v] [/h] [/x:<headers file name>] [/a:<user>:<password>]\r\n";
const char* strLongUsage=
"\r\n"
"/c: Continue downloading a partially downloaded file.\r\n"
"/v: Verbose mode, shows all the HTTP headers sent and received.\r\n"
"/h: Show HTTP headers only, do not download any file.\r\n"
"/x: Send the contents of the specified text file as extra HTTP headers.\r\n"
"/a: Authentication parameters (basic HTTP authentication is used).\r\n"
"/u: Unsafe https, do not validate server certificate and hostname.\r\n"
"/n: Authenticate server certificate but not the hostname on https.\r\n"
"\r\n"
"If no local file name is specified, the name is taken from the\r\n"
"last part of the URL. If the URL ends with a slash or has no\r\n"
"slashes, then INDEX.HTM is used.\r\n"
"\r\n"
"If an existing local text file is specified instead of an URL,\r\n"
"then the URL is read from that file (useful for very large URLs).\r\n"
"\r\n"
"If \"con\" is specified instead of an URL, the name is read from the console\r\n"
"(useful for very large URLs or for redirecting, e.g. \"type url.txt|hget con\")\r\n"
"\r\n"
"TIP: Use /l:con to display the contents instead of saving to a file.";
const char* strInvParam = "Invalid parameter";
const char* strNoNetwork = "No network connection available";
const char* strCRLF = "\r\n";
const char* strWwwAuthenticate = "WWW-Authenticate";
#define TCP_CONN_FAILURE_KNOWN_REASONS 20
const char* strConnFailureReasons[21] = {
"Unknow failure opening connection\r\n",
"This connection has never been used since the implementation was initialized.\r\n",
"The TCPIP_TCP_CLOSE method was called.\r\n",
"The TCPIP_TCP_ABORT method was called.\r\n",
"A RST segment was received (the connection was refused or aborted by the remote host).\r\n",
"The user timeout expired.\r\n",
"The connection establishment timeout expired.\r\n",
"Network connection was lost while the TCP connection was open.\r\n",
"ICMP \"Destination unreachable\" message received.\r\n",
"TLS: The server did not provide a certificate.\r\n",
"TLS: Invalid server certificate.\r\n",
"TLS: Invalid server certificate (the host name didn't match).\r\n",
"TLS: Invalid server certificate (expired).\r\n",
"TLS: Invalid server certificate (self-signed).\r\n",
"TLS: Invalid server certificate (untrusted root).\r\n",
"TLS: Invalid server certificate (revoked).\r\n",
"TLS: Invalid server certificate (invalid certificate authority).\r\n",
"TLS: Invalid server certificate (invalid TLS version or cypher suite).\r\n",
"TLS: Our certificate was rejected by the peer.\r\n",
"TLS: Other error.\r\n",
"An error that is unknown to this software occurred...\r\n"};
/* Variables */
byte headersOnly = 0;
byte continueDownloading = 0;
byte verboseMode = 0;
byte fileHandle = 0;
byte conn = 0;
char* credentials;
char* domainName;
char localFileName[128];
char** arguments;
int argumentsCount;
byte continueReceived;
byte redirectionRequested = 0;
byte authenticationRequested;
byte authenticationSent;
int remainingInputData = 0;
byte* inputDataPointer;
int emptyLineReaded;
long contentLength,blockSize,currentBlock;
bool isFirstUpdate;
int isChunkedTransfer;
long currentChunkSize = 0;
int newLocationReceived;
int acceptsPartialDownloads;
long existingFileSize;
long receivedLength = 0;
byte* TcpInputData;
#define TcpOutputData TcpInputData
char extraHeadersFilePath[128];
byte remoteFilePath[256];
byte Buffer[512];
byte headerLine[256];
byte responseStatus[256];
char statusLine[256];
char redirectionFullLocation[256];
byte dosVersion[6];
int responseStatusCode;
int responseStatusCodeFirstDigit;
char* headerTitle;
char* headerContents;
Z80_registers regs;
unapi_code_block* codeBlock;
int ticksWaited;
int sysTimerHold;
char unapiImplementationName[80];
byte localFileIsConsole;
byte redirectionUrlIsNewDomainName;
bool zeroContentLengthAnnounced;
typedef struct {
byte remoteIP[4];
uint remotePort;
uint localPort;
int userTimeout;
byte flags;
int hostName;
} t_TcpConnectionParameters;
t_TcpConnectionParameters* TcpConnectionParameters;
bool TlsIsSupported = false;
bool useHttps = false;
bool mustCheckCertificate = true;
bool mustCheckHostName = true;
bool safeTlsIsSupported = true;
byte redirectionRequests = 0;
byte tcpIpSpecificationVersionMain;
byte tcpIpSpecificationVersionSecondary;
/* Some handy defines */
#define PrintNewLine() print(strCRLF)
#define LetTcpipBreathe() UnapiCall(codeBlock, TCPIP_WAIT, ®s, REGS_NONE, REGS_NONE)
#define SkipCharsWhile(pointer, ch) {while(*pointer == ch) pointer++;}
#define SkipCharsUntil(pointer, ch) {while(*pointer != ch) pointer++;}
#define SkipLF() GetInputByte()
#define ToLowerCase(ch) {ch |= 32;}
/* Function prototypes */
int NoParameters();
void PrintTitle();
void PrintUsageAndEnd(bool printLongUsage);
void Terminate(const char* errorMessage);
void CheckDosVersion();
void InitializeTcpipUnapi();
void CheckTcpipCapabilities();
bool LongHelpRequested();
void ProcessParameters();
void ProcessUrl(char* url, byte isRedirection);
void ProcessOptions();
void GetLocalFilePathIfNecessary();
char* SkipInitialColon(char* string);
int StringStartsWith(const char* stringToCheck, const char* startingToken);
void CheckNetworkConnection();
char* FindLastSlash(char* string);
char* FindFirstSlash(char* string);
char* FindFirstSemicolon(char* string);
void ExtractPortNumberFromDomainName();
void DoHttpWork();
void SendHttpRequest();
void ReadResponseHeaders();
void SendLineToTcp(char* string);
int DestinationFileExists();
int strcmpi(const char *a1, const char *a2);
int strncmpi(const char *a1, const char *a2, unsigned size);
void ResolveServerName();
void OpenTcpConnection();
void AbortIfEscIsPressed();
int EscIsPressed();
void CloseTcpConnection();
void SendTcpData(byte* data, int dataSize);
void print(char* s);
int ArgumentIs(char* argument, char* argumentStart);
char* ExplainDosErrorCode(byte code, char* destination);
void CloseLocalFile();
void InitializeHttpVariables();
void CheckHeaderErrors();
void DownloadHttpContents();
void SendCredentialsIfNecessary();
void ReadResponseStatus();
void ProcessResponseStatus();
void ReadNextHeader();
void ProcessNextHeader();
void TerminateWithHttpError();
byte GetInputByte();
void ExtractHeaderTitleAndContents();
int HeaderTitleIs(char* string);
int HeaderContentsIs(char* string);
void ReadAsMuchTcpDataAsPossible();
void DiscardBogusHttpContent();
void ResetTcpBuffer();
void PrintRedirectionInformation();
void PrintLongLength(char* message, long length, byte showOnlyKBytes);
int ContainsProtocolSpecifier(char* url);
char* ltoa(unsigned long num, char *string);
void TerminateWithDosErrorCode(char* message, byte errorCode);
void GetExsitingFileInfo();
void SendPartialRequestIfNecessary();
void OpenLocalFile();
void CreateLocalFile();
void UpdateReceivingMessage();
void WriteContentsToFile(byte* dataPointer, int size);
void PrepareLocalFileForAppend();
void DoDirectDatatransfer();
void DoChunkedDataTransfer();
long GetNextChunkSize();
void GetUnapiImplementationNameAndVersion();
void CheckIfLocalFileIsConsole();
int FirstParameterIsExistingfileName();
void ReadUrlFromFile();
int CharIsWhitespace(char ch);
void InitializeBufferPointers();
byte OpenFile(char* path, byte* fileHandle);
void CloseFile(byte fileHandle);
byte ReadFromFile(byte fileHandle, byte* address, int* amount);
void SendExtraHeadersIfNecessary();
byte CheckIfFileExists(char* path);
void RestoreDefaultAbortRoutine();
void DisableAutoAbort();
void TerminateWithCtrlCOrCtrlStop();
void EnsureTcpConnectionIsStillOpen();
void ReadUrlFromConsole();
/**********************
*** MAIN is here ***
**********************/
int main(char** argv, int argc)
{
useHttps = false;
mustCheckCertificate = true;
mustCheckHostName = true;
TlsIsSupported = false;
arguments = argv;
argumentsCount = argc;
PrintTitle();
if(NoParameters()) {
PrintUsageAndEnd(false);
}
if(LongHelpRequested())
{
PrintUsageAndEnd(true);
}
DisableAutoAbort();
InitializeBufferPointers();
CheckDosVersion();
InitializeTcpipUnapi();
GetUnapiImplementationNameAndVersion();
CheckTcpipCapabilities();
ProcessParameters();
CheckNetworkConnection();
printf("Local file path: %s\r\n", localFileName);
if(continueDownloading) {
PrintLongLength("Local file size: ", existingFileSize, 0);
PrintNewLine();
}
PrintNewLine();
print("* Press ESC at any time to cancel the process\r\n\r\n");
DoHttpWork();
Terminate(NULL);
return 0;
}
/****************************
*** FUNCTIONS are here ***
****************************/
void InitializeBufferPointers()
{
TcpConnectionParameters = (t_TcpConnectionParameters*)0x8000;
domainName =(char*)0x8100;
codeBlock = (unapi_code_block*)0x8300;
TcpInputData = (byte*)0x8400;
}
int NoParameters()
{
return (argumentsCount == 0);
}
void PrintTitle()
{
print(strTitle);
}
void PrintUsageAndEnd(bool printLongUsage)
{
print(strShortUsage);
print(printLongUsage ? strLongUsage : strUseQuestionMarkForHelp);
DosCall(0, ®s, REGS_MAIN, REGS_NONE);
}
void Terminate(const char* errorMessage)
{
if(errorMessage != NULL) {
printf("\r\x1BK*** %s\r\n", errorMessage);
}
CloseTcpConnection();
CloseLocalFile();
RestoreDefaultAbortRoutine();
regs.Bytes.B = (errorMessage == NULL ? 0 : 1);
DosCall(_TERM, ®s, REGS_NONE, REGS_NONE);
}
void RestoreDefaultAbortRoutine()
{
regs.Words.DE = 0;
DosCall(_DEFAB, ®s, REGS_MAIN, REGS_NONE);
}
void CheckDosVersion()
{
DosCall(_DOSVER, ®s, REGS_NONE, REGS_MAIN);
if(regs.Bytes.B < 2) {
Terminate("This program is for MSX-DOS 2 only.");
}
sprintf(dosVersion, "%i.%i%i", regs.Bytes.B, (regs.Bytes.C >> 4) & 0xF, regs.Bytes.C & 0xF);
debug("DOS version OK");
}
void InitializeTcpipUnapi()
{
int i;
i = UnapiGetCount("TCP/IP");
if(i==0) {
Terminate("No TCP/IP UNAPI implementations found");
}
UnapiBuildCodeBlock(NULL, 1, codeBlock);
regs.Bytes.B = 0;
UnapiCall(codeBlock, TCPIP_TCP_ABORT, ®s, REGS_MAIN, REGS_MAIN);
TcpConnectionParameters->remotePort = HTTP_DEFAULT_PORT;
TcpConnectionParameters->localPort = 0xFFFF;
TcpConnectionParameters->userTimeout = 0;
TcpConnectionParameters->flags = 0;
debug("TCP/IP UNAPI initialized OK");
}
void CheckTcpipCapabilities()
{
regs.Bytes.B = 1;
UnapiCall(codeBlock, TCPIP_GET_CAPAB, ®s, REGS_MAIN, REGS_MAIN);
if((regs.Bytes.L & (1 << 3)) == 0) {
Terminate("This TCP/IP implementation does not support active TCP connections.");
}
TlsIsSupported = false;
safeTlsIsSupported = false;
if(tcpIpSpecificationVersionMain == 0 || (tcpIpSpecificationVersionMain == 1 && tcpIpSpecificationVersionSecondary == 0))
return; //TCP/IP UNAPI <1.1 has no TLS support at all
if(regs.Bytes.D & TCPIP_CAPAB_VERIFY_CERTIFICATE)
safeTlsIsSupported = true;
regs.Bytes.B = 4;
UnapiCall(codeBlock, TCPIP_GET_CAPAB, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.H & 1)
TlsIsSupported = true;
}
bool LongHelpRequested()
{
return strcmpi(arguments[0], "?") == 0;
}
void ProcessParameters()
{
if(strcmpi(arguments[0], "con") == 0) {
ReadUrlFromConsole();
printf("URL to download: %s\r\n", domainName);
ProcessUrl(domainName, 0);
} else if(FirstParameterIsExistingfileName()) {
ReadUrlFromFile();
printf("URL to download: %s\r\n", domainName);
ProcessUrl(domainName, 0);
} else {
*domainName = '\0';
ProcessUrl(arguments[0], 0);
}
ProcessOptions();
}
int FirstParameterIsExistingfileName()
{
regs.Words.DE = (int)arguments[0];
regs.Bytes.B = 0;
regs.Words.IX = (int)Buffer;
DosCall(_FFIRST, ®s, REGS_ALL, REGS_AF);
return regs.Bytes.A == 0;
}
void ReadUrlFromFile()
{
byte tempFileHandle;
byte data;
char* pointer;
byte error;
int amount;
error = OpenFile(arguments[0], &tempFileHandle);
if(error != 0) {
TerminateWithDosErrorCode("Error when opening URL file: ", error);
}
amount = 255;
error = ReadFromFile(tempFileHandle, domainName, &amount);
if(error != 0) {
TerminateWithDosErrorCode("Error when reading URL file: ", error);
}
domainName[amount] = 13;
CloseFile(tempFileHandle);
pointer = domainName;
pointer--;
do {
++pointer;
data = *pointer;
if((data < 32 && !CharIsWhitespace(data)) || (data == 127)) {
Terminate("ERROR: The specified URL file is not a valid text file.");
}
} while(!CharIsWhitespace(data));
if(pointer == domainName) {
Terminate("ERROR: The specified URL file is empty.");
}
*pointer = '\0';
}
byte ReadFromFile(byte fileHandle, byte* address, int* amount)
{
regs.Bytes.B = fileHandle;
regs.Words.DE = (int)address;
regs.Words.HL = *amount;
DosCall(_READ, ®s, REGS_MAIN, REGS_MAIN);
*amount = regs.Words.HL;
return regs.Bytes.A;
}
int CharIsWhitespace(char ch)
{
return (ch==' ' || ch==13 || ch==10 || ch == 9);
}
void ProcessUrl(char* url, byte isRedirection)
{
char* pointer;
if(url[0] == '/') {
if(isRedirection) {
redirectionUrlIsNewDomainName = 0;
} else {
Terminate(strInvParam);
}
} else if(StringStartsWith(url, "http://")) {
TcpConnectionParameters->remotePort = HTTP_DEFAULT_PORT;
TcpConnectionParameters->flags = 0 ;
if(isRedirection) {
if (useHttps)
redirectionUrlIsNewDomainName = 1;
else
{
pointer = FindFirstSlash(url+7);
if ((pointer)&&(strncmpi(url+7, domainName, (pointer-url-7))))
redirectionUrlIsNewDomainName = 1;
else
redirectionUrlIsNewDomainName = 0;
}
}
strcpy(domainName, url + 7);
useHttps = false;
} else if((TlsIsSupported)&&(StringStartsWith(url, "https://"))) {
if(isRedirection) {
if (!useHttps)
redirectionUrlIsNewDomainName = 1;
else
{
pointer = FindFirstSlash(url+8);
if ((pointer)&&(strncmpi(url+8, domainName, (pointer-url-8))))
redirectionUrlIsNewDomainName = 1;
else
redirectionUrlIsNewDomainName = 0;
}
}
strcpy(domainName, url + 8);
useHttps = true;
TcpConnectionParameters->remotePort = HTTPS_DEFAULT_PORT;
TcpConnectionParameters->flags = TcpConnectionParameters->flags | TCPFLAGS_USE_TLS ;
} else if(ContainsProtocolSpecifier(url)) {
if(isRedirection) {
Terminate("Redirection request to HTTPS received, but this TCP/IP doesn't support TLS.");
} else {
Terminate("This TCP/IP implementation supports the HTTP protocol only.");
}
} /*else if(domainName[0]=='\0') {
if(isRedirection) {
Terminate("Redirection request received, but the new URL is empty.");
} else {
Terminate(strInvParam);
}
}*/ else {
if(isRedirection) {
Terminate("Redirection request received, but the new URL is not absolute.");
}
strcpy(domainName, url);
}
if(url[0] == '/') {
strcpy(remoteFilePath, url);
} else {
remoteFilePath[0] = '/';
remoteFilePath[1] = '\0';
pointer = FindFirstSlash(domainName);
if(pointer != NULL) {
*pointer = '\0';
strcpy(remoteFilePath+1, pointer+1);
}
ExtractPortNumberFromDomainName();
}
debug2("URL: %s", domainName);
debug2("Remote resource: %s", remoteFilePath);
debug2("Port number: %i", TcpConnectionParameters->remotePort);
}
int ContainsProtocolSpecifier(char* url)
{
return (strstr(url, "://") != NULL);
}
void ExtractPortNumberFromDomainName()
{
char* pointer;
pointer = FindFirstSemicolon(domainName);
if(pointer == NULL) {
if (!useHttps)
TcpConnectionParameters->remotePort = HTTP_DEFAULT_PORT;
else
TcpConnectionParameters->remotePort = HTTPS_DEFAULT_PORT;
return;
}
*pointer = '\0';
pointer++;
TcpConnectionParameters->remotePort = atoi(pointer);
}
void ProcessOptions()
{
int i;
byte error;
localFileName[0] = '\0';
extraHeadersFilePath[0] = '\0';
credentials = NULL;
for(i=1; i<argumentsCount; i++) {
if(ArgumentIs(arguments[i], "v")) {
verboseMode = 1;
debug("Verbose mode");
} else if(ArgumentIs(arguments[i], "u")) {
mustCheckCertificate = false;
mustCheckHostName = false;
debug("UNSAFE TLS");
} else if(ArgumentIs(arguments[i], "n")) {
mustCheckCertificate = true;
mustCheckHostName = false;
debug("TLS won't check host name");
} else if(ArgumentIs(arguments[i], "c")) {
continueDownloading = 1;
debug("Continue downloading");
} else if(ArgumentIs(arguments[i], "h")) {
headersOnly = 1;
debug("Headers only");
} else if(ArgumentIs(arguments[i], "l")) {
strcpy(localFileName, SkipInitialColon(arguments[i] + 2));
debug2("Specified local filename: %s", localFileName);
} else if(ArgumentIs(arguments[i], "a")) {
credentials = SkipInitialColon(arguments[i] + 2);
debug2("Credentials: %s", credentials);
} else if(ArgumentIs(arguments[i], "x")) {
strcpy(extraHeadersFilePath, SkipInitialColon(arguments[i] + 2));
} else {
Terminate(strInvParam);
}
}
GetLocalFilePathIfNecessary();
GetExsitingFileInfo();
if(extraHeadersFilePath[0] != '\0') {
error = CheckIfFileExists(extraHeadersFilePath);
if(error != 0) {
TerminateWithDosErrorCode("Error when searching the extra headers file: ", error);
}
}
}
void GetExsitingFileInfo()
{
if(!continueDownloading) {
return;
}
if(!DestinationFileExists()) {
print("WARNING: Resume download requested but local file does not exist.\r\n A new download will be started.\r\n\r\n");
continueDownloading = 0;
}
}
void GetLocalFilePathIfNecessary()
{
char* pointer;
if(localFileName[0] != '\0') {
return;
}
pointer = FindLastSlash(remoteFilePath);
if(pointer == NULL || pointer[1] == '\0') {
pointer = strDefaultFilename;
strcpy(localFileName, pointer);
} else {
strcpy(localFileName, pointer + 1);
}
debug2("Calculated local filename: %s", localFileName);
}
char* SkipInitialColon(char* string) {
if(*string == ':') {
return string + 1;
} else {
return string;
}
}
int StringStartsWith(const char* stringToCheck, const char* startingToken)
{
int len;
len = strlen(startingToken);
return strncmpi(stringToCheck, startingToken, len) == 0;
}
void CheckNetworkConnection()
{
UnapiCall(codeBlock, TCPIP_NET_STATE, ®s, REGS_NONE, REGS_MAIN);
if(regs.Bytes.B == 0 || regs.Bytes.B == 3) {
Terminate(strNoNetwork);
}
}
void InitializeVariables()
{
}
char* FindLastSlash(char* string)
{
char* pointer;
pointer = string + strlen(string);
while(pointer >= string) {
if(*pointer == '/') {
return pointer;
}
pointer--;
}
return NULL;
}
char* FindFirstSlash(char* string)
{
return strstr(string, "/");
}
char* FindFirstSemicolon(char* string)
{
return strstr(string, ":");
}
void DoHttpWork()
{
authenticationRequested = 0;
redirectionRequests = 0;
ResetTcpBuffer();
ResolveServerName();
OpenTcpConnection();
do {
InitializeHttpVariables();
SendHttpRequest();
ReadResponseHeaders();
CheckHeaderErrors();
if(redirectionRequested) {
PrintRedirectionInformation();
if(redirectionUrlIsNewDomainName) {
CloseTcpConnection();
ResolveServerName();
OpenTcpConnection();
}
ResetTcpBuffer();
} else if(continueReceived || authenticationRequested) {
DiscardBogusHttpContent();
}
} while(continueReceived || redirectionRequested || authenticationRequested);
if(headersOnly) {
return;
}
if(isChunkedTransfer) {
print("Content size is unknown (chunked data transfer)\r\n\r\n");
DownloadHttpContents();
} else if(contentLength != 0) {
PrintLongLength("Content size: ", contentLength, 0);
PrintNewLine();
PrintNewLine();
DownloadHttpContents();
}
}
void PrintRedirectionInformation()
{
printf("* Redirecting to: %s\r\n\r\n", redirectionFullLocation);
}
void PrintLongLength(char* message, long length, byte showOnlyKBytes)
{
long kbytes;
int bytes;
if(showOnlyKBytes) {
print(message);
} else {
printf("%s%s bytes", message, ltoa(length, Buffer));
}
if(showOnlyKBytes || length >= 1024*10) {
kbytes = length / 1024;
bytes = length % 1024;
if(bytes >= 512) {
kbytes++;
}
if(showOnlyKBytes) {
printf("%s KBytes", ltoa(kbytes, Buffer));
} else {
printf(" (%s KBytes)", ltoa(kbytes, Buffer));
}
}
}
void ResetTcpBuffer()
{
remainingInputData = 0;
inputDataPointer = TcpInputData;
}
void DiscardBogusHttpContent()
{
while(remainingInputData > 0) {
GetInputByte();
}
}
void InitializeHttpVariables()
{
redirectionRequested = 0;
authenticationSent = 0;
continueReceived = 0;
isChunkedTransfer = 0;
contentLength = 0;
newLocationReceived = 0;
acceptsPartialDownloads = 1;
}
void SendHttpRequest()
{
sprintf(TcpOutputData, "%s %s HTTP/1.1\r\n", headersOnly ? "HEAD" : "GET", remoteFilePath);
SendLineToTcp(TcpOutputData);
sprintf(TcpOutputData, "Host: %s\r\n", domainName);
SendLineToTcp(TcpOutputData);
sprintf(TcpOutputData, "User-Agent: HGET/1.3 (MSX-DOS %s; TCP/IP UNAPI; %s)\r\n", dosVersion, unapiImplementationName);
SendLineToTcp(TcpOutputData);
SendCredentialsIfNecessary();
SendPartialRequestIfNecessary();
SendExtraHeadersIfNecessary();
SendLineToTcp(strCRLF);
if(verboseMode) {
PrintNewLine();
}
}
void SendExtraHeadersIfNecessary()
{
byte tempFileHandle;
int amount;
byte error;