Differences From Artifact [63931bf44e]:
- File
src/OFHTTPClient.m
— part of check-in
[d1d36ae522]
at
2021-11-06 15:57:29
on branch trunk
— OFStream: New write API
The old write API made it too easy to lose bytes when a stream is set to
non-blocking mode. The new API always throws when not all bytes were
written, which forces handling the number of bytes being written being
smaller than the number of bytes requested to be written. (user: js, size: 29819) [annotate] [blame] [check-ins using]
To Artifact [0ef7b9c0c4]:
- File
src/OFHTTPClient.m
— part of check-in
[d30efa8bbf]
at
2021-11-13 13:04:13
on branch trunk
— Completely rework the TLS/SSL API
The previous API could never work cleanly and would always require
hacks, as it needed intercepting all interactions of OFTCPSocket with
the raw socket and did not work at all if the OFTCPSocket had anything
in its read buffer before starting the TLS handshake. This also could
not be fixed easily, as it would have required the object to contain two
read buffers, one for the unencrypted connection and one for the
encrypted connection. There was also no clean way to perform the
handshake in a non-blocking way.The new API is a lot cleaner and requires none of the hacks, but using
it requires slightly more work. But this is more than made up for by
making a fully asynchronous handshake possible. It uses the concept of a
stream wrapping another stream, meaning the entire connecting part is
being handled by OFTCPSocket and then the connected socket is passed off
to OFTLSStream to wrap it. This also makes for a lot cleaner separation
of concerns. (user: js, size: 30982) [annotate] [blame] [check-ins using]
︙ | ︙ | |||
24 25 26 27 28 29 30 | #import "OFData.h" #import "OFDictionary.h" #import "OFHTTPRequest.h" #import "OFHTTPResponse.h" #import "OFKernelEventObserver.h" #import "OFNumber.h" #import "OFRunLoop.h" | < | | > | 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 | #import "OFData.h" #import "OFDictionary.h" #import "OFHTTPRequest.h" #import "OFHTTPResponse.h" #import "OFKernelEventObserver.h" #import "OFNumber.h" #import "OFRunLoop.h" #import "OFString.h" #import "OFTCPSocket.h" #import "OFTLSStream.h" #import "OFURL.h" #import "OFAlreadyConnectedException.h" #import "OFHTTPRequestFailedException.h" #import "OFInvalidArgumentException.h" #import "OFInvalidEncodingException.h" #import "OFInvalidFormatException.h" #import "OFInvalidServerReplyException.h" #import "OFNotImplementedException.h" #import "OFNotOpenException.h" #import "OFOutOfMemoryException.h" #import "OFOutOfRangeException.h" #import "OFTruncatedDataException.h" #import "OFUnsupportedProtocolException.h" #import "OFUnsupportedVersionException.h" #import "OFWriteFailedException.h" static const unsigned int defaultRedirects = 10; OF_DIRECT_MEMBERS @interface OFHTTPClientRequestHandler: OFObject <OFTCPSocketDelegate, OFTLSStreamDelegate> { @public OFHTTPClient *_client; OFHTTPRequest *_request; unsigned int _redirects; bool _firstLine; OFString *_version; |
︙ | ︙ | |||
71 72 73 74 75 76 77 | - (void)closeAndReconnect; @end OF_DIRECT_MEMBERS @interface OFHTTPClientRequestBodyStream: OFStream <OFReadyForWritingObserving> { OFHTTPClientRequestHandler *_handler; | | | | | | 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 | - (void)closeAndReconnect; @end OF_DIRECT_MEMBERS @interface OFHTTPClientRequestBodyStream: OFStream <OFReadyForWritingObserving> { OFHTTPClientRequestHandler *_handler; OFStream *_stream; bool _chunked; unsigned long long _toWrite; bool _atEndOfStream; } - (instancetype)initWithHandler: (OFHTTPClientRequestHandler *)handler stream: (OFStream *)stream; @end OF_DIRECT_MEMBERS @interface OFHTTPClientResponse: OFHTTPResponse <OFReadyForReadingObserving> { OFStream *_stream; bool _hasContentLength, _chunked, _keepAlive; bool _atEndOfStream, _setAtEndOfStream; long long _toRead; } @property (nonatomic, setter=of_setKeepAlive:) bool of_keepAlive; - (instancetype)initWithStream: (OFStream *)stream; @end OF_DIRECT_MEMBERS @interface OFHTTPClientSyncPerformer: OFObject <OFHTTPClientDelegate> { OFHTTPClient *_client; OFObject <OFHTTPClientDelegate> *_delegate; |
︙ | ︙ | |||
292 293 294 295 296 297 298 | [_client->_delegate client: _client didPerformRequest: _request response: nil exception: exception]; } | | | | 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | [_client->_delegate client: _client didPerformRequest: _request response: nil exception: exception]; } - (void)createResponseWithStreamOrThrow: (OFStream *)stream { OFURL *URL = _request.URL; OFHTTPClientResponse *response; OFString *connectionHeader; bool keepAlive; OFString *location; id exception; response = [[[OFHTTPClientResponse alloc] initWithStream: stream] autorelease]; response.protocolVersionString = _version; response.statusCode = _status; response.headers = _serverHeaders; connectionHeader = [_serverHeaders objectForKey: @"Connection"]; if ([_version isEqual: @"1.1"]) { |
︙ | ︙ | |||
324 325 326 327 328 329 330 | else keepAlive = false; } if (keepAlive) { response.of_keepAlive = true; | | | 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | else keepAlive = false; } if (keepAlive) { response.of_keepAlive = true; _client->_stream = [stream retain]; _client->_lastURL = [URL copy]; _client->_lastWasHEAD = (_request.method == OFHTTPRequestMethodHead); _client->_lastResponse = [response retain]; } if (_redirects > 0 && (_status == 301 || _status == 302 || |
︙ | ︙ | |||
428 429 430 431 432 433 434 | withObject: _client withObject: _request withObject: response withObject: exception afterDelay: 0]; } | | | | 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | withObject: _client withObject: _request withObject: response withObject: exception afterDelay: 0]; } - (void)createResponseWithStream: (OFStream *)stream { @try { [self createResponseWithStreamOrThrow: stream]; } @catch (id e) { [self raiseException: e]; } } - (bool)handleFirstLine: (OFString *)line { |
︙ | ︙ | |||
470 471 472 473 474 475 476 | @throw [OFInvalidServerReplyException exception]; _status = (short)status; return true; } | | | | | | 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 | @throw [OFInvalidServerReplyException exception]; _status = (short)status; return true; } - (bool)handleServerHeader: (OFString *)line stream: (OFStream *)stream { OFString *key, *value, *old; const char *lineC, *tmp; char *keyC; if (line == nil) @throw [OFInvalidServerReplyException exception]; if (line.length == 0) { [_serverHeaders makeImmutable]; if ([_client->_delegate respondsToSelector: @selector(client: didReceiveHeaders:statusCode:request:)]) [_client->_delegate client: _client didReceiveHeaders: _serverHeaders statusCode: _status request: _request]; stream.delegate = nil; [self performSelector: @selector(createResponseWithStream:) withObject: stream afterDelay: 0]; return false; } lineC = line.UTF8String; |
︙ | ︙ | |||
531 532 533 534 535 536 537 | value = [old stringByAppendingFormat: @",%@", value]; [_serverHeaders setObject: value forKey: key]; return true; } | | | < | 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 | value = [old stringByAppendingFormat: @",%@", value]; [_serverHeaders setObject: value forKey: key]; return true; } - (bool)stream: (OFStream *)stream didReadLine: (OFString *)line exception: (id)exception { bool ret; if (exception != nil) { if ([exception isKindOfClass: [OFInvalidEncodingException class]]) exception = [OFInvalidServerReplyException exception]; [self raiseException: exception]; return false; } @try { if (_firstLine) { _firstLine = false; ret = [self handleFirstLine: line]; } else ret = [self handleServerHeader: line stream: stream]; } @catch (id e) { [self raiseException: e]; ret = false; } return ret; } |
︙ | ︙ | |||
593 594 595 596 597 598 599 | chunked = [[headers objectForKey: @"Transfer-Encoding"] isEqual: @"chunked"]; if (chunked || [headers objectForKey: @"Content-Length"] != nil) { stream.delegate = nil; OFStream *requestBody = [[[OFHTTPClientRequestBodyStream alloc] | | < | | | < < | | > > > > > > > > > > > > > > > > > > > > > > | | > > > > > > > > > > > > > > > | | | | | | | | | > > | < < | < < < < | < < | | | 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 | chunked = [[headers objectForKey: @"Transfer-Encoding"] isEqual: @"chunked"]; if (chunked || [headers objectForKey: @"Content-Length"] != nil) { stream.delegate = nil; OFStream *requestBody = [[[OFHTTPClientRequestBodyStream alloc] initWithHandler: self stream: stream] autorelease]; if ([_client->_delegate respondsToSelector: @selector(client:wantsRequestBody:request:)]) [_client->_delegate client: _client wantsRequestBody: requestBody request: _request]; } else [stream asyncReadLine]; return nil; } - (void)handleStream: (OFStream *)stream { /* * As a work around for a bug with split packets in lighttpd when using * HTTPS, we construct the complete request in a buffer string and then * send it all at once. * * We do not use the streams's write buffer in case we need to resend * the entire request (e.g. in case a keep-alive connection timed out). */ @try { [stream asyncWriteString: constructRequestString(_request)]; } @catch (id e) { [self raiseException: e]; return; } } - (void)socket: (OFTCPSocket *)sock didConnectToHost: (OFString *)host port: (uint16_t)port exception: (id)exception { if (exception != nil) { [self raiseException: exception]; return; } if ([_client->_delegate respondsToSelector: @selector(client:didCreateTCPSocket:request:)]) [_client->_delegate client: _client didCreateTCPSocket: sock request: _request]; if ([_request.URL.scheme caseInsensitiveCompare: @"https"] == OFOrderedSame) { OFTLSStream *stream; @try { stream = [OFTLSStream streamWithStream: sock]; } @catch (OFNotImplementedException *e) { [self raiseException: [OFUnsupportedProtocolException exceptionWithURL: _request.URL]]; return; } if ([_client->_delegate respondsToSelector: @selector(client:didCreateTLSStream:request:)]) [_client->_delegate client: _client didCreateTLSStream: stream request: _request]; stream.delegate = self; [stream asyncPerformClientHandshakeWithHost: _request.URL.host]; } else { sock.delegate = self; [self performSelector: @selector(handleStream:) withObject: sock afterDelay: 0]; } } - (void)stream: (OFTLSStream *)stream didPerformClientHandshakeWithHost: (OFString *)host exception: (id)exception { if (exception != nil) { [self raiseException: exception]; return; } [self performSelector: @selector(handleStream:) withObject: stream afterDelay: 0]; } - (void)start { OFURL *URL = _request.URL; OFStream *stream; /* Can we reuse the last socket? */ if (_client->_stream != nil && !_client->_stream.atEndOfStream && [_client->_lastURL.scheme isEqual: URL.scheme] && [_client->_lastURL.host isEqual: URL.host] && (_client->_lastURL.port == URL.port || [_client->_lastURL.port isEqual: URL.port]) && (_client->_lastWasHEAD || _client->_lastResponse.atEndOfStream)) { /* * Set _stream to nil, so that in case of an error it won't be * reused. If everything is successful, we set _stream again * at the end. */ stream = [_client->_stream autorelease]; _client->_stream = nil; [_client->_lastURL release]; _client->_lastURL = nil; [_client->_lastResponse release]; _client->_lastResponse = nil; stream.delegate = self; [self performSelector: @selector(handleStream:) withObject: stream afterDelay: 0]; } else [self closeAndReconnect]; } - (void)closeAndReconnect { @try { OFURL *URL = _request.URL; OFTCPSocket *sock; uint16_t port; OFNumber *URLPort; [_client close]; sock = [OFTCPSocket socket]; if ([URL.scheme caseInsensitiveCompare: @"https"] == OFOrderedSame) port = 443; else port = 80; URLPort = URL.port; if (URLPort != nil) port = URLPort.unsignedShortValue; sock.delegate = self; [sock asyncConnectToHost: URL.host port: port]; } @catch (id e) { [self raiseException: e]; } } @end @implementation OFHTTPClientRequestBodyStream - (instancetype)initWithHandler: (OFHTTPClientRequestHandler *)handler stream: (OFStream *)stream { self = [super init]; @try { OFDictionary OF_GENERIC(OFString *, OFString *) *headers; OFString *transferEncoding, *contentLengthString; _handler = [handler retain]; _stream = [stream retain]; headers = _handler->_request.headers; transferEncoding = [headers objectForKey: @"Transfer-Encoding"]; _chunked = [transferEncoding isEqual: @"chunked"]; contentLengthString = [headers objectForKey: @"Content-Length"]; |
︙ | ︙ | |||
757 758 759 760 761 762 763 | } return self; } - (void)dealloc { | | | | | | | | | | | | > | | | | | 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 | } return self; } - (void)dealloc { if (_stream != nil) [self close]; [_handler release]; [super dealloc]; } - (size_t)lowlevelWriteBuffer: (const void *)buffer length: (size_t)length { /* TODO: Use non-blocking writes */ if (_stream == nil) @throw [OFNotOpenException exceptionWithObject: self]; /* * We must not send a chunk of size 0, as that would end the body. We * always ignore writing 0 bytes to still allow writing 0 bytes after * the end of stream. */ if (length == 0) return 0; if (_atEndOfStream) @throw [OFWriteFailedException exceptionWithObject: self requestedLength: length bytesWritten: 0 errNo: ENOTCONN]; if (_chunked) [_stream writeFormat: @"%zX\r\n", length]; else if (length > _toWrite) @throw [OFOutOfRangeException exception]; [_stream writeBuffer: buffer length: length]; if (_chunked) [_stream writeString: @"\r\n"]; if (!_chunked) { _toWrite -= length; if (_toWrite == 0) _atEndOfStream = true; } return length; } - (bool)lowlevelIsAtEndOfStream { return _atEndOfStream; } - (void)close { if (_stream == nil) @throw [OFNotOpenException exceptionWithObject: self]; if (_chunked) [_stream writeString: @"0\r\n\r\n"]; else if (_toWrite > 0) @throw [OFTruncatedDataException exception]; _stream.delegate = _handler; [_stream asyncReadLine]; [_stream release]; _stream = nil; [super close]; } - (int)fileDescriptorForWriting { return ((OFStream <OFReadyForWritingObserving> *)_stream) .fileDescriptorForWriting; } @end @implementation OFHTTPClientResponse @synthesize of_keepAlive = _keepAlive; - (instancetype)initWithStream: (OFStream *)stream { self = [super init]; _stream = [stream retain]; return self; } - (void)dealloc { if (_stream != nil) [self close]; [super dealloc]; } - (void)setHeaders: (OFDictionary *)headers { |
︙ | ︙ | |||
887 888 889 890 891 892 893 | @throw [OFInvalidServerReplyException exception]; } } } - (size_t)lowlevelReadIntoBuffer: (void *)buffer length: (size_t)length { | | | | | | | | | | | | 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 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 | @throw [OFInvalidServerReplyException exception]; } } } - (size_t)lowlevelReadIntoBuffer: (void *)buffer length: (size_t)length { if (_stream == nil) @throw [OFNotOpenException exceptionWithObject: self]; if (_atEndOfStream) return 0; if (!_hasContentLength && !_chunked) return [_stream readIntoBuffer: buffer length: length]; if (_stream.atEndOfStream) @throw [OFTruncatedDataException exception]; /* Content-Length */ if (!_chunked) { size_t ret; if (length > (unsigned long long)_toRead) length = (size_t)_toRead; ret = [_stream readIntoBuffer: buffer length: length]; if (ret > length) @throw [OFOutOfRangeException exception]; _toRead -= ret; if (_toRead == 0) _atEndOfStream = true; return ret; } /* Chunked */ if (_toRead == -2) { char tmp[2]; switch ([_stream readIntoBuffer: tmp length: 2]) { case 2: _toRead++; if (tmp[1] != '\n') @throw [OFInvalidServerReplyException exception]; case 1: _toRead++; if (tmp[0] != '\r') @throw [OFInvalidServerReplyException exception]; } if (_setAtEndOfStream && _toRead == 0) _atEndOfStream = true; return 0; } else if (_toRead == -1) { char tmp; if ([_stream readIntoBuffer: &tmp length: 1] == 1) { _toRead++; if (tmp != '\n') @throw [OFInvalidServerReplyException exception]; } if (_setAtEndOfStream && _toRead == 0) _atEndOfStream = true; return 0; } else if (_toRead > 0) { if (length > (unsigned long long)_toRead) length = (size_t)_toRead; length = [_stream readIntoBuffer: buffer length: length]; _toRead -= length; if (_toRead == 0) _toRead = -2; return length; } else { void *pool = objc_autoreleasePoolPush(); OFString *line; size_t pos; @try { line = [_stream tryReadLine]; } @catch (OFInvalidEncodingException *e) { @throw [OFInvalidServerReplyException exception]; } if (line == nil) return 0; pos = [line rangeOfString: @";"].location; if (pos != OFNotFound) line = [line substringToIndex: pos]; if (line.length < 1) { /* * We have read the empty string because the stream is * at end of stream. */ if (_stream.atEndOfStream && pos == OFNotFound) @throw [OFTruncatedDataException exception]; else @throw [OFInvalidServerReplyException exception]; } @try { |
︙ | ︙ | |||
1022 1023 1024 1025 1026 1027 1028 | } - (bool)lowlevelIsAtEndOfStream { if (_atEndOfStream) return true; | | | | > | | | | | | 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 | } - (bool)lowlevelIsAtEndOfStream { if (_atEndOfStream) return true; if (_stream == nil) @throw [OFNotOpenException exceptionWithObject: self]; if (!_hasContentLength && !_chunked) return _stream.atEndOfStream; return _atEndOfStream; } - (int)fileDescriptorForReading { if (_stream == nil) return -1; return ((OFStream <OFReadyForReadingObserving> *)_stream) .fileDescriptorForReading; } - (bool)hasDataInReadBuffer { return (super.hasDataInReadBuffer || _stream.hasDataInReadBuffer); } - (void)close { if (_stream == nil) @throw [OFNotOpenException exceptionWithObject: self]; _atEndOfStream = false; [_stream release]; _stream = nil; [super close]; } @end @implementation OFHTTPClientSyncPerformer - (instancetype)initWithClient: (OFHTTPClient *)client |
︙ | ︙ | |||
1119 1120 1121 1122 1123 1124 1125 | [_delegate client: client didPerformRequest: request response: response exception: nil]; } | | | | | | | | > > > > > > > > > > > | 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 | [_delegate client: client didPerformRequest: request response: response exception: nil]; } - (void)client: (OFHTTPClient *)client didCreateTCPSocket: (OFTCPSocket *)TCPSocket request: (OFHTTPRequest *)request { if ([_delegate respondsToSelector: @selector(client:didCreateTCPSocket:request:)]) [_delegate client: client didCreateTCPSocket: TCPSocket request: request]; } - (void)client: (OFHTTPClient *)client didCreateTLSStream: (OFTLSStream *)TLSStream request: (OFHTTPRequest *)request { if ([_delegate respondsToSelector: @selector(client:didCreateTLSStream:request:)]) [_delegate client: client didCreateTLSStream: TLSStream request: request]; } - (void)client: (OFHTTPClient *)client wantsRequestBody: (OFStream *)body request: (OFHTTPRequest *)request { if ([_delegate respondsToSelector: |
︙ | ︙ | |||
1242 1243 1244 1245 1246 1247 1248 | redirects: redirects] autorelease] start]; objc_autoreleasePoolPop(pool); } - (void)close { | | | | 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 | redirects: redirects] autorelease] start]; objc_autoreleasePoolPop(pool); } - (void)close { [_stream release]; _stream = nil; [_lastURL release]; _lastURL = nil; [_lastResponse release]; _lastResponse = nil; } @end |