ObjFW  Diff

Differences From Artifact [05abbe7837]:

To Artifact [e73ed438ad]:


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
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







+










-







#import "OFData.h"
#import "OFDictionary.h"
#import "OFFile.h"
#import "OFFileManager.h"
#import "OFHTTPClient.h"
#import "OFHTTPRequest.h"
#import "OFHTTPResponse.h"
#import "OFIRI.h"
#import "OFLocale.h"
#import "OFOptionsParser.h"
#ifdef OF_HAVE_PLUGINS
# import "OFPlugin.h"
#endif
#import "OFSandbox.h"
#import "OFStdIOStream.h"
#import "OFSystemInfo.h"
#import "OFTCPSocket.h"
#import "OFTLSStream.h"
#import "OFURI.h"

#ifdef HAVE_TLS_SUPPORT
# import "ObjFWTLS.h"
#endif

#import "OFConnectSocketFailedException.h"
#import "OFGetItemAttributesFailedException.h"
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
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







-
-
+
+















-
+

















-
+







#define GIBIBYTE (1024 * 1024 * 1024)
#define MEBIBYTE (1024 * 1024)
#define KIBIBYTE (1024)

@interface OFHTTP: OFObject <OFApplicationDelegate, OFHTTPClientDelegate,
    OFStreamDelegate>
{
	OFArray OF_GENERIC(OFString *) *_URIs;
	size_t _URIIndex;
	OFArray OF_GENERIC(OFString *) *_IRIs;
	size_t _IRIIndex;
	int _errorCode;
	OFString *_outputPath, *_currentFileName;
	bool _continue, _force, _detectFileName, _detectFileNameRequest;
	bool _detectedFileName, _quiet, _verbose, _insecure, _ignoreStatus;
	bool _useUnicode;
	OFStream *_body;
	OFHTTPRequestMethod _method;
	OFMutableDictionary *_clientHeaders;
	OFHTTPClient *_HTTPClient;
	char *_buffer;
	OFStream *_output;
	unsigned long long _received, _length, _resumedFrom;
	ProgressBar *_progressBar;
}

- (void)downloadNextURI;
- (void)downloadNextIRI;
@end

#ifdef HAVE_TLS_SUPPORT
void
_reference_to_ObjFWTLS(void)
{
	_ObjFWTLS_reference = 1;
}
#endif

OF_APPLICATION_DELEGATE(OFHTTP)

static void
help(OFStream *stream, bool full, int status)
{
	[OFStdErr writeLine:
	    OF_LOCALIZED(@"usage",
	    @"Usage: %[prog] -[cehHmoOPqv] uri1 [uri2 ...]",
	    @"Usage: %[prog] -[cehHmoOPqv] iri1 [iri2 ...]",
	    @"prog", [OFApplication programName])];

	if (full) {
		[stream writeString: @"\n"];
		[stream writeLine: OF_LOCALIZED(@"full_usage",
		    @"Options:\n    "
		    @"-b  --body           "
447
448
449
450
451
452
453
454
455


456
457
458


459
460
461
462
463
464
465
447
448
449
450
451
452
453


454
455
456


457
458
459
460
461
462
463
464
465







-
-
+
+

-
-
+
+







	/* Dropped after parsing options */
	sandbox.allowsUnveil = true;

	[OFApplication of_activateSandbox: sandbox];
#endif

#ifndef OF_AMIGAOS
	[OFLocale addLocalizationDirectoryURI:
	    [OFURI fileURIWithPath: @LOCALIZATION_DIR]];
	[OFLocale addLocalizationDirectoryIRI:
	    [OFIRI fileIRIWithPath: @LOCALIZATION_DIR]];
#else
	[OFLocale addLocalizationDirectoryURI:
	    [OFURI fileURIWithPath: @"PROGDIR:/share/ofhttp/localization"]];
	[OFLocale addLocalizationDirectoryIRI:
	    [OFIRI fileIRIWithPath: @"PROGDIR:/share/ofhttp/localization"]];
#endif

	optionsParser = [OFOptionsParser parserWithOptions: options];
	while ((option = [optionsParser nextOption]) != '\0') {
		switch (option) {
		case 'b':
			[self setBody: optionsParser.argument];
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
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







-
+

-
+



















-
+

-
-
+
+














-
+







	[sandbox unveilPath: @"/etc/ssl" permissions: @"r"];

	sandbox.allowsUnveil = false;
	[OFApplication of_activateSandbox: sandbox];
#endif

	_outputPath = [outputPath copy];
	_URIs = [optionsParser.remainingArguments copy];
	_IRIs = [optionsParser.remainingArguments copy];

	if (_URIs.count < 1)
	if (_IRIs.count < 1)
		help(OFStdErr, false, 1);

	if (_quiet && _verbose) {
		[OFStdErr writeLine: OF_LOCALIZED(@"quiet_xor_verbose",
		    @"%[prog]: -q / --quiet and -v / --verbose are mutually "
		    @"exclusive!",
		    @"prog", [OFApplication programName])];
		[OFApplication terminateWithStatus: 1];
	}

	if (_outputPath != nil && _detectFileName) {
		[OFStdErr writeLine: OF_LOCALIZED(
		    @"output_xor_detect_filename",
		    @"%[prog]: -o / --output and -O / --detect-filename are "
		    @"mutually exclusive!",
		    @"prog", [OFApplication programName])];
		[OFApplication terminateWithStatus: 1];
	}

	if (_outputPath != nil && _URIs.count > 1) {
	if (_outputPath != nil && _IRIs.count > 1) {
		[OFStdErr writeLine:
		    OF_LOCALIZED(@"output_only_with_one_uri",
		    @"%[prog]: Cannot use -o / --output when more than one URI "
		    OF_LOCALIZED(@"output_only_with_one_iri",
		    @"%[prog]: Cannot use -o / --output when more than one IRI "
		    @"has been specified!",
		    @"prog", [OFApplication programName])];
		[OFApplication terminateWithStatus: 1];
	}

	if (_insecure)
		_HTTPClient.allowsInsecureRedirects = true;

#ifdef OF_WINDOWS
	_useUnicode = [OFSystemInfo isWindowsNT];
#else
	_useUnicode = ([OFLocale encoding] == OFStringEncodingUTF8);
#endif

	[self performSelector: @selector(downloadNextURI) afterDelay: 0];
	[self performSelector: @selector(downloadNextIRI) afterDelay: 0];
}

-	(void)client: (OFHTTPClient *)client
  didCreateTLSStream: (OFTLSStream *)stream
	     request: (OFHTTPRequest *)request
{
	/* Use setter instead of property access to work around GCC bug. */
607
608
609
610
611
612
613
614

615
616
617
618
619
620
621
607
608
609
610
611
612
613

614
615
616
617
618
619
620
621







-
+







		char buffer[4096];
		size_t length = [_body readIntoBuffer: buffer length: 4096];
		[body writeBuffer: buffer length: length];
	}
}

-	       (bool)client: (OFHTTPClient *)client
  shouldFollowRedirectToURI: (OFURI *)URI
  shouldFollowRedirectToIRI: (OFIRI *)IRI
		 statusCode: (short)statusCode
		    request: (OFHTTPRequest *)request
		   response: (OFHTTPResponse *)response
{
	if (_verbose) {
		void *pool = objc_autoreleasePoolPush();
		OFDictionary OF_GENERIC(OFString *, OFString *) *headers =
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
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







-
+

-
+













-
+












-
+


-
+


-
+



-
+







			[OFStdOut writeFormat: @"  %@: %@\n", key, object];

		objc_autoreleasePoolPop(pool);
	}

	if (!_quiet) {
		if (_useUnicode)
			[OFStdOut writeFormat: @"☇ %@", URI.string];
			[OFStdOut writeFormat: @"☇ %@", IRI.string];
		else
			[OFStdOut writeFormat: @"< %@", URI.string];
			[OFStdOut writeFormat: @"< %@", IRI.string];
	}

	_length = 0;

	return true;
}

-      (bool)stream: (OFStream *)response
  didReadIntoBuffer: (void *)buffer
	     length: (size_t)length
	  exception: (id)exception
{
	if (exception != nil) {
		OFString *URI;
		OFString *IRI;

		[_progressBar stop];
		[_progressBar draw];
		[_progressBar release];
		_progressBar = nil;

		if (!_quiet) {
			[OFStdOut writeString: @"\n  "];
			[OFStdOut writeLine: OF_LOCALIZED(@"download_error",
			    @"Error!")];
		}

		URI = [_URIs objectAtIndex: _URIIndex - 1];
		IRI = [_IRIs objectAtIndex: _IRIIndex - 1];
		[OFStdErr writeLine: OF_LOCALIZED(
		    @"download_failed_exception",
		    @"%[prog]: Failed to download <%[uri]>!\n"
		    @"%[prog]: Failed to download <%[iri]>!\n"
		    @"  %[exception]",
		    @"prog", [OFApplication programName],
		    @"uri", URI,
		    @"iri", IRI,
		    @"exception", exception)];

		_errorCode = 1;
		[self performSelector: @selector(downloadNextURI)
		[self performSelector: @selector(downloadNextIRI)
			   afterDelay: 0];
		return false;
	}

	[_output writeBuffer: buffer length: length];

	_received += length;
690
691
692
693
694
695
696
697

698
699
700
701
702
703
704
690
691
692
693
694
695
696

697
698
699
700
701
702
703
704







-
+








		if (!_quiet) {
			[OFStdOut writeString: @"\n  "];
			[OFStdOut writeLine:
			    OF_LOCALIZED(@"download_done", @"Done!")];
		}

		[self performSelector: @selector(downloadNextURI)
		[self performSelector: @selector(downloadNextIRI)
			   afterDelay: 0];
		return false;
	}

	return true;
}

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
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







-
+


-
+








-
+


-
+








-
+


-
+







		if ([exception isKindOfClass:
		    [OFResolveHostFailedException class]]) {
			if (!_quiet)
				[OFStdOut writeString: @"\n"];

			[OFStdErr writeLine:
			    OF_LOCALIZED(@"download_resolve_host_failed",
			    @"%[prog]: Failed to download <%[uri]>!\n"
			    @"%[prog]: Failed to download <%[iri]>!\n"
			    @"  Failed to resolve host: %[exception]",
			    @"prog", [OFApplication programName],
			    @"uri", request.URI.string,
			    @"iri", request.IRI.string,
			    @"exception", exception)];
		} else if ([exception isKindOfClass:
		    [OFConnectSocketFailedException class]]) {
			if (!_quiet)
				[OFStdOut writeString: @"\n"];

			[OFStdErr writeLine:
			    OF_LOCALIZED(@"download_failed_connection_failed",
			    @"%[prog]: Failed to download <%[uri]>!\n"
			    @"%[prog]: Failed to download <%[iri]>!\n"
			    @"  Connection failed: %[exception]",
			    @"prog", [OFApplication programName],
			    @"uri", request.URI.string,
			    @"iri", request.IRI.string,
			    @"exception", exception)];
		} else if ([exception isKindOfClass:
		    [OFInvalidServerResponseException class]]) {
			if (!_quiet)
				[OFStdOut writeString: @"\n"];

			[OFStdErr writeLine: OF_LOCALIZED(
			    @"download_failed_invalid_server_response",
			    @"%[prog]: Failed to download <%[uri]>!\n"
			    @"%[prog]: Failed to download <%[iri]>!\n"
			    @"  Invalid server response!",
			    @"prog", [OFApplication programName],
			    @"uri", request.URI.string)];
			    @"iri", request.IRI.string)];
		} else if ([exception isKindOfClass:
		    [OFUnsupportedProtocolException class]]) {
			if (!_quiet)
				[OFStdOut writeString: @"\n"];

			[OFStdErr writeLine: OF_LOCALIZED(@"no_tls_support",
			    @"%[prog]: No TLS support in ObjFW!\n"
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
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







-
+


-
+
















-
+


-
+





-
+














-
-
+
+

-
+







				error = OF_LOCALIZED(
				    @"download_failed_read_or_write_failed_"
				    @"write",
				    @"Write failed");

			[OFStdErr writeLine: OF_LOCALIZED(
			    @"download_failed_read_or_write_failed",
			    @"%[prog]: Failed to download <%[uri]>!\n"
			    @"%[prog]: Failed to download <%[iri]>!\n"
			    @"  %[error]: %[exception]",
			    @"prog", [OFApplication programName],
			    @"uri", request.URI.string,
			    @"iri", request.IRI.string,
			    @"error", error,
			    @"exception", exception)];
		} else if ([exception isKindOfClass:
		    [OFHTTPRequestFailedException class]]) {
			short statusCode;
			OFString *codeString;

			if (_ignoreStatus) {
				exception = nil;
				goto after_exception_handling;
			}

			statusCode = response.statusCode;
			codeString = [OFString stringWithFormat: @"%hd %@",
			    statusCode, OFHTTPStatusCodeString(statusCode)];
			[OFStdErr writeLine: OF_LOCALIZED(@"download_failed",
			    @"%[prog]: Failed to download <%[uri]>!\n"
			    @"%[prog]: Failed to download <%[iri]>!\n"
			    @"  HTTP status code: %[code]",
			    @"prog", [OFApplication programName],
			    @"uri", request.URI.string,
			    @"iri", request.IRI.string,
			    @"code", codeString)];
		} else
			@throw exception;

		_errorCode = 1;
		[self performSelector: @selector(downloadNextURI)
		[self performSelector: @selector(downloadNextIRI)
			   afterDelay: 0];
		return;
	}

after_exception_handling:
	if (_method == OFHTTPRequestMethodHead)
		goto next;

	if (_detectFileNameRequest) {
		_currentFileName = [fileNameFromContentDisposition(
		    [response.headers objectForKey: @"Content-Disposition"])
		    copy];
		_detectedFileName = true;

		/* Handle this URI on the next -[downloadNextURI] call */
		_URIIndex--;
		/* Handle this IRI on the next -[downloadNextIRI] call */
		_IRIIndex--;

		[self performSelector: @selector(downloadNextURI)
		[self performSelector: @selector(downloadNextIRI)
			   afterDelay: 0];
		return;
	}

	if ([_outputPath isEqual: @"-"])
		_output = [OFStdOut copy];
	else {
984
985
986
987
988
989
990
991

992
993
994

995
996
997


998
999
1000
1001
1002
1003
1004
1005
1006
1007

1008
1009
1010
1011
1012


1013
1014
1015


1016
1017

1018
1019
1020
1021
1022
1023

1024
1025

1026
1027

1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038

1039
1040

1041
1042
1043

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062

1063
1064
1065
1066
1067
1068
1069
984
985
986
987
988
989
990

991
992
993

994
995


996
997
998
999
1000
1001
1002
1003
1004
1005
1006

1007
1008
1009
1010


1011
1012
1013


1014
1015
1016

1017
1018
1019
1020
1021
1022

1023
1024

1025
1026

1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037

1038
1039

1040
1041
1042

1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061

1062
1063
1064
1065
1066
1067
1068
1069







-
+


-
+

-
-
+
+









-
+



-
-
+
+

-
-
+
+

-
+





-
+

-
+

-
+










-
+

-
+


-
+


















-
+







	[response asyncReadIntoBuffer: _buffer length: [OFSystemInfo pageSize]];
	return;

next:
	[_currentFileName release];
	_currentFileName = nil;

	[self performSelector: @selector(downloadNextURI) afterDelay: 0];
	[self performSelector: @selector(downloadNextIRI) afterDelay: 0];
}

- (void)downloadNextURI
- (void)downloadNextIRI
{
	OFString *URIString = nil;
	OFURI *URI;
	OFString *IRIString = nil;
	OFIRI *IRI;
	OFMutableDictionary *clientHeaders;
	OFHTTPRequest *request;

	_received = _length = _resumedFrom = 0;

	if (_output != OFStdOut)
		[_output release];
	_output = nil;

	if (_URIIndex >= _URIs.count)
	if (_IRIIndex >= _IRIs.count)
		[OFApplication terminateWithStatus: _errorCode];

	@try {
		URIString = [_URIs objectAtIndex: _URIIndex++];
		URI = [OFURI URIWithString: URIString];
		IRIString = [_IRIs objectAtIndex: _IRIIndex++];
		IRI = [OFIRI IRIWithString: IRIString];
	} @catch (OFInvalidFormatException *e) {
		[OFStdErr writeLine: OF_LOCALIZED(@"invalid_uri",
		    @"%[prog]: Invalid URI: <%[uri]>!",
		[OFStdErr writeLine: OF_LOCALIZED(@"invalid_iri",
		    @"%[prog]: Invalid IRI: <%[iri]>!",
		    @"prog", [OFApplication programName],
		    @"uri", URIString)];
		    @"iri", IRIString)];

		_errorCode = 1;
		goto next;
	}

	if (![URI.scheme isEqual: @"http"] && ![URI.scheme isEqual: @"https"]) {
	if (![IRI.scheme isEqual: @"http"] && ![IRI.scheme isEqual: @"https"]) {
		[OFStdErr writeLine: OF_LOCALIZED(@"invalid_scheme",
		    @"%[prog]: Invalid scheme: <%[uri]>!",
		    @"%[prog]: Invalid scheme: <%[iri]>!",
		    @"prog", [OFApplication programName],
		    @"uri", URIString)];
		    @"iri", IRIString)];

		_errorCode = 1;
		goto next;
	}

	clientHeaders = [[_clientHeaders mutableCopy] autorelease];

	if (_detectFileName && !_detectedFileName) {
		if (!_quiet) {
			if (_useUnicode)
				[OFStdOut writeFormat: @"⠒ %@", URI.string];
				[OFStdOut writeFormat: @"⠒ %@", IRI.string];
			else
				[OFStdOut writeFormat: @"? %@", URI.string];
				[OFStdOut writeFormat: @"? %@", IRI.string];
		}

		request = [OFHTTPRequest requestWithURI: URI];
		request = [OFHTTPRequest requestWithIRI: IRI];
		request.headers = clientHeaders;
		request.method = OFHTTPRequestMethodHead;

		_detectFileNameRequest = true;
		[_HTTPClient asyncPerformRequest: request];
		return;
	}

	if (!_detectedFileName) {
		[_currentFileName release];
		_currentFileName = nil;
	} else
		_detectedFileName = false;

	if (_currentFileName == nil)
		_currentFileName = [_outputPath copy];

	if (_currentFileName == nil)
		_currentFileName = [URI.path.lastPathComponent copy];
		_currentFileName = [IRI.path.lastPathComponent copy];

	if ([_currentFileName isEqual: @"/"]) {
		[_currentFileName release];
		_currentFileName = nil;
	}

	if (_currentFileName == nil)
1086
1087
1088
1089
1090
1091
1092
1093

1094
1095

1096
1097
1098

1099
1100
1101
1102
1103
1104
1105
1106
1107

1108
1109
1086
1087
1088
1089
1090
1091
1092

1093
1094

1095
1096
1097

1098
1099
1100
1101
1102
1103
1104
1105
1106

1107
1108
1109







-
+

-
+


-
+








-
+


			[clientHeaders setObject: range forKey: @"Range"];
		} @catch (OFGetItemAttributesFailedException *e) {
		}
	}

	if (!_quiet) {
		if (_useUnicode)
			[OFStdOut writeFormat: @"⇣ %@", URI.string];
			[OFStdOut writeFormat: @"⇣ %@", IRI.string];
		else
			[OFStdOut writeFormat: @"< %@", URI.string];
			[OFStdOut writeFormat: @"< %@", IRI.string];
	}

	request = [OFHTTPRequest requestWithURI: URI];
	request = [OFHTTPRequest requestWithIRI: IRI];
	request.headers = clientHeaders;
	request.method = _method;

	_detectFileNameRequest = false;
	[_HTTPClient asyncPerformRequest: request];
	return;

next:
	[self performSelector: @selector(downloadNextURI) afterDelay: 0];
	[self performSelector: @selector(downloadNextIRI) afterDelay: 0];
}
@end