Skip to content

Move common protocol implementation to NativeProtocol #1377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Foundation.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@
5BF9B8021FABD5DA00EE1A7C /* CFBundle_Tables.c in Sources */ = {isa = PBXBuildFile; fileRef = 5BF9B7F71FABD5D400EE1A7C /* CFBundle_Tables.c */; };
5FE52C951D147D1C00F7D270 /* TestNSTextCheckingResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FE52C941D147D1C00F7D270 /* TestNSTextCheckingResult.swift */; };
6105D30F1FEBC5FC0022865A /* Message.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6105D30E1FEBC5FC0022865A /* Message.swift */; };
61D2F9AF1FECFB3E0033306A /* NativeProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61D2F9AE1FECFB3E0033306A /* NativeProtocol.swift */; };
61E0117D1C1B5590000037DD /* RunLoop.swift in Sources */ = {isa = PBXBuildFile; fileRef = EADE0B761BD15DFF00C49C64 /* RunLoop.swift */; };
61E0117E1C1B55B9000037DD /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F481BCC5DCB00ED97BB /* Timer.swift */; };
61E0117F1C1B5990000037DD /* CFRunLoop.c in Sources */ = {isa = PBXBuildFile; fileRef = 5B5D88D81BBC9AD800234F36 /* CFRunLoop.c */; };
Expand Down Expand Up @@ -781,6 +782,7 @@
5FE52C941D147D1C00F7D270 /* TestNSTextCheckingResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSTextCheckingResult.swift; sourceTree = "<group>"; };
6105D30E1FEBC5FC0022865A /* Message.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Message.swift; sourceTree = "<group>"; };
61A395F91C2484490029B337 /* TestNSLocale.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSLocale.swift; sourceTree = "<group>"; };
61D2F9AE1FECFB3E0033306A /* NativeProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeProtocol.swift; sourceTree = "<group>"; };
61D6C9EE1C1DFE9500DEF583 /* TestTimer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestTimer.swift; sourceTree = "<group>"; };
61E0117B1C1B554D000037DD /* TestRunLoop.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestRunLoop.swift; sourceTree = "<group>"; };
61F8AE7C1C180FC600FB62F0 /* TestNotificationCenter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNotificationCenter.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1020,6 +1022,7 @@
5B1FD9D11D6D16580080E83C /* URLSessionTask.swift */,
5B1FD9D21D6D16580080E83C /* TaskRegistry.swift */,
6105D30E1FEBC5FC0022865A /* Message.swift */,
61D2F9AE1FECFB3E0033306A /* NativeProtocol.swift */,
);
name = Session;
path = URLSession;
Expand Down Expand Up @@ -2294,6 +2297,7 @@
EADE0BA61BD15E0000C49C64 /* MassFormatter.swift in Sources */,
5BECBA3A1D1CAE9A00B39B1F /* NSMeasurement.swift in Sources */,
5BF7AEB21BCD51F9008F214A /* NSNumber.swift in Sources */,
61D2F9AF1FECFB3E0033306A /* NativeProtocol.swift in Sources */,
B9974B991EDF4A22007F15B8 /* HTTPURLProtocol.swift in Sources */,
5BCD03821D3EE35C00E3FF9B /* TimeZone.swift in Sources */,
EADE0BBC1BD15E0000C49C64 /* URLCache.swift in Sources */,
Expand Down
42 changes: 20 additions & 22 deletions Foundation/URLSession/Message.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Foundation/URLSession/Message.swift - URLSession & libcurl
// Foundation/URLSession/Message.swift - Message parsing for native protocols
//
// This source file is part of the Swift.org open source project
//
Expand All @@ -10,17 +10,14 @@
//
// -----------------------------------------------------------------------------
///
/// Common code for Header parsing
///
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------

import CoreFoundation

extension _HTTPURLProtocol {
/// An HTTP header being parsed.
extension _NativeProtocol {
/// A native protocol like FTP or HTTP header being parsed.
///
/// It can either be complete (i.e. the final CR LF CR LF has been
/// received), or partial.
Expand All @@ -45,19 +42,18 @@ extension _HTTPURLProtocol {
}
}

extension _HTTPURLProtocol._ParsedResponseHeader {
extension _NativeProtocol._ParsedResponseHeader {
/// Parse a header line passed by libcurl.
///
/// These contain the <CRLF> ending and the final line contains nothing but
/// that ending.
/// - Returns: Returning nil indicates failure. Otherwise returns a new
/// `ParsedResponseHeader` with the given line added.
func byAppending(headerLine data: Data) -> _HTTPURLProtocol._ParsedResponseHeader? {
func byAppending(headerLine data: Data) -> _NativeProtocol._ParsedResponseHeader? {
// The buffer must end in CRLF
guard
2 <= data.count &&
data[data.endIndex - 2] == _HTTPCharacters.CR &&
data[data.endIndex - 1] == _HTTPCharacters.LF
guard 2 <= data.count &&
data[data.endIndex - 2] == _Delimiters.CR &&
data[data.endIndex - 1] == _Delimiters.LF
else { return nil }
let lineBuffer = data.subdata(in: Range(data.startIndex..<data.endIndex-2))
guard let line = String(data: lineBuffer, encoding: String.Encoding.utf8) else { return nil}
Expand All @@ -69,36 +65,38 @@ extension _HTTPURLProtocol._ParsedResponseHeader {
/// is a complete header. Otherwise it's a partial header.
/// - Note: Appending a line to a complete header results in a partial
/// header with just that line.
private func byAppending(headerLine line: String) -> _HTTPURLProtocol._ParsedResponseHeader {
private func byAppending(headerLine line: String) -> _NativeProtocol._ParsedResponseHeader {
if line.isEmpty {
switch self {
case .partial(let header): return .complete(header)
case .complete: return .partial(_HTTPURLProtocol._ResponseHeaderLines())
case .complete: return .partial(_NativeProtocol._ResponseHeaderLines())
}
} else {
let header = partialResponseHeader
return .partial(header.byAppending(headerLine: line))
}
}
private var partialResponseHeader: _HTTPURLProtocol._ResponseHeaderLines {

private var partialResponseHeader: _NativeProtocol._ResponseHeaderLines {
switch self {
case .partial(let header): return header
case .complete: return _HTTPURLProtocol._ResponseHeaderLines()
case .complete: return _NativeProtocol._ResponseHeaderLines()
}
}
}

private extension _HTTPURLProtocol._ResponseHeaderLines {
private extension _NativeProtocol._ResponseHeaderLines {
/// Returns a copy of the lines with the new line appended to it.
func byAppending(headerLine line: String) -> _HTTPURLProtocol._ResponseHeaderLines {
func byAppending(headerLine line: String) -> _NativeProtocol._ResponseHeaderLines {
var l = self.lines
l.append(line)
return _HTTPURLProtocol._ResponseHeaderLines(headerLines: l)
return _NativeProtocol._ResponseHeaderLines(headerLines: l)
}
}

// Characters that we need for HTTP parsing:
struct _HTTPCharacters {
// Characters that we need for Header parsing:

struct _Delimiters {
/// *Carriage Return* symbol
static let CR: UInt8 = 0x0d
/// *Line Feed* symbol
Expand Down
27 changes: 27 additions & 0 deletions Foundation/URLSession/NativeProtocol.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//


import CoreFoundation
import Dispatch

internal class _NativeProtocol: URLProtocol {

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}

override func startLoading() {
NSRequiresConcreteImplementation()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor nit: In your next PR, could you make sure to fix the indentation here and in the method below? They should be indented by four spaces, not three.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thanks ! Actually, the concrete implementation of StartLoading will be moved here from HTTPURLProtocol. This is just a placeholder for now ..

}

override func stopLoading() {
NSRequiresConcreteImplementation()
}
}
10 changes: 5 additions & 5 deletions Foundation/URLSession/http/HTTPMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ private extension _HTTPURLProtocol._HTTPMessage._Header {
guard let (head, tail) = lines.decompose else { return nil }
let headView = head.unicodeScalars[...]
guard let nameRange = headView.rangeOfTokenPrefix else { return nil }
guard headView.index(after: nameRange.upperBound) <= headView.endIndex && headView[nameRange.upperBound] == _HTTPCharacters.Colon else { return nil }
guard headView.index(after: nameRange.upperBound) <= headView.endIndex && headView[nameRange.upperBound] == _Delimiters.Colon else { return nil }
let name = String(headView[nameRange])
var value: String?
let line = headView[headView.index(after: nameRange.upperBound)..<headView.endIndex]
Expand Down Expand Up @@ -241,21 +241,21 @@ private extension String.UnicodeScalarView.SubSequence {
/// The range of space (U+0020) characters.
var rangeOfSpace: Range<Index>? {
guard !isEmpty else { return startIndex..<startIndex }
guard let idx = index(of: _HTTPCharacters.Space!) else { return nil }
guard let idx = index(of: _Delimiters.Space!) else { return nil }
return idx..<self.index(after: idx)
}
// Has a space (SP) or horizontal tab (HT) prefix
var hasSPHTPrefix: Bool {
guard !isEmpty else { return false }
return self[startIndex] == _HTTPCharacters.Space || self[startIndex] == _HTTPCharacters.HorizontalTab
return self[startIndex] == _Delimiters.Space || self[startIndex] == _Delimiters.HorizontalTab
}
/// Unicode scalars after removing the leading spaces (SP) and horizontal tabs (HT).
/// Returns `nil` if the unicode scalars do not start with a SP or HT.
var trimSPHTPrefix: SubSequence? {
guard !isEmpty else { return nil }
var idx = startIndex
while idx < endIndex {
if self[idx] == _HTTPCharacters.Space || self[idx] == _HTTPCharacters.HorizontalTab {
if self[idx] == _Delimiters.Space || self[idx] == _Delimiters.HorizontalTab {
idx = self.index(after: idx)
} else {
guard startIndex < idx else { return nil }
Expand All @@ -271,6 +271,6 @@ private extension UnicodeScalar {
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-2
var isValidMessageToken: Bool {
guard UnicodeScalar(32) <= self && self <= UnicodeScalar(126) else { return false }
return !_HTTPCharacters.Separators.characterIsMember(UInt16(self.value))
return !_Delimiters.Separators.characterIsMember(UInt16(self.value))
}
}
2 changes: 1 addition & 1 deletion Foundation/URLSession/http/HTTPURLProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import CoreFoundation
import Dispatch

internal class _HTTPURLProtocol: URLProtocol {
internal class _HTTPURLProtocol: _NativeProtocol {

fileprivate var easyHandle: _EasyHandle!
fileprivate lazy var tempFileURL: URL = {
Expand Down
1 change: 1 addition & 0 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@
'Foundation/URLSession/URLSessionDelegate.swift',
'Foundation/URLSession/URLSessionTask.swift',
'Foundation/URLSession/TaskRegistry.swift',
'Foundation/URLSession/NativeProtocol.swift',
'Foundation/URLSession/TransferState.swift',
'Foundation/URLSession/libcurl/libcurlHelpers.swift',
'Foundation/URLSession/http/HTTPURLProtocol.swift',
Expand Down