Skip to content

Carving out common code out of HTTPMessage #1375

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
Dec 22, 2017
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 @@ -309,6 +309,7 @@
5BF9B8011FABD5DA00EE1A7C /* CFBundle_ResourceFork.c in Sources */ = {isa = PBXBuildFile; fileRef = 5BF9B7F61FABD5D400EE1A7C /* CFBundle_ResourceFork.c */; };
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 */; };
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 @@ -778,6 +779,7 @@
5EB6A15C1C188FC40037DCB8 /* TestJSONSerialization.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestJSONSerialization.swift; sourceTree = "<group>"; };
5EF673AB1C28B527006212A3 /* TestNotificationQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNotificationQueue.swift; sourceTree = "<group>"; };
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>"; };
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>"; };
Expand Down Expand Up @@ -1017,6 +1019,7 @@
5B1FD9D01D6D16580080E83C /* URLSessionDelegate.swift */,
5B1FD9D11D6D16580080E83C /* URLSessionTask.swift */,
5B1FD9D21D6D16580080E83C /* TaskRegistry.swift */,
6105D30E1FEBC5FC0022865A /* Message.swift */,
);
name = Session;
path = URLSession;
Expand Down Expand Up @@ -2206,6 +2209,7 @@
EADE0BCB1BD15E0000C49C64 /* XMLNode.swift in Sources */,
5BF7AEB01BCD51F9008F214A /* NSLocale.swift in Sources */,
EADE0BA31BD15E0000C49C64 /* NSKeyedArchiver.swift in Sources */,
6105D30F1FEBC5FC0022865A /* Message.swift in Sources */,
5BF7AEAD1BCD51F9008F214A /* NSError.swift in Sources */,
EADE0BB61BD15E0000C49C64 /* NSSortDescriptor.swift in Sources */,
5B23AB871CE62D17000DB898 /* Boxing.swift in Sources */,
Expand Down
112 changes: 112 additions & 0 deletions Foundation/URLSession/Message.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Foundation/URLSession/Message.swift - URLSession & libcurl
//
// 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
//
// -----------------------------------------------------------------------------
///
/// Common code for Header parsing
///
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------

import CoreFoundation

extension _HTTPURLProtocol {
/// An HTTP header being parsed.
///
/// It can either be complete (i.e. the final CR LF CR LF has been
/// received), or partial.
internal enum _ParsedResponseHeader {
case partial(_ResponseHeaderLines)
case complete(_ResponseHeaderLines)
init() {
self = .partial(_ResponseHeaderLines())
}
}
/// A type safe wrapper around multiple lines of headers.
///
/// This can be converted into an `HTTPURLResponse`.
internal struct _ResponseHeaderLines {
let lines: [String]
init() {
self.lines = []
}
init(headerLines: [String]) {
self.lines = headerLines
}
}
}

extension _HTTPURLProtocol._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? {
// The buffer must end in CRLF
guard
2 <= data.count &&
data[data.endIndex - 2] == _HTTPCharacters.CR &&
data[data.endIndex - 1] == _HTTPCharacters.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}
return byAppending(headerLine: line)
}
/// Append a status line.
///
/// If the line is empty, it marks the end of the header, and the result
/// 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 {
if line.isEmpty {
switch self {
case .partial(let header): return .complete(header)
case .complete: return .partial(_HTTPURLProtocol._ResponseHeaderLines())
}
} else {
let header = partialResponseHeader
return .partial(header.byAppending(headerLine: line))
}
}
private var partialResponseHeader: _HTTPURLProtocol._ResponseHeaderLines {
switch self {
case .partial(let header): return header
case .complete: return _HTTPURLProtocol._ResponseHeaderLines()
}
}
}

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

// Characters that we need for HTTP parsing:
struct _HTTPCharacters {
/// *Carriage Return* symbol
static let CR: UInt8 = 0x0d
/// *Line Feed* symbol
static let LF: UInt8 = 0x0a
/// *Space* symbol
static let Space = UnicodeScalar(0x20)
static let HorizontalTab = UnicodeScalar(0x09)
static let Colon = UnicodeScalar(0x3a)
/// *Separators* according to RFC 2616
static let Separators = NSCharacterSet(charactersIn: "()<>@,;:\\\"/[]?={} \t")
}
93 changes: 0 additions & 93 deletions Foundation/URLSession/http/HTTPMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,83 +19,6 @@

import CoreFoundation


extension _HTTPURLProtocol {
/// An HTTP header being parsed.
///
/// It can either be complete (i.e. the final CR LF CR LF has been
/// received), or partial.
internal enum _ParsedResponseHeader {
case partial(_ResponseHeaderLines)
case complete(_ResponseHeaderLines)
init() {
self = .partial(_ResponseHeaderLines())
}
}
/// A type safe wrapper around multiple lines of headers.
///
/// This can be converted into an `HTTPURLResponse`.
internal struct _ResponseHeaderLines {
let lines: [String]
init() {
self.lines = []
}
init(headerLines: [String]) {
self.lines = headerLines
}
}
}

extension _HTTPURLProtocol._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? {
// The buffer must end in CRLF
guard
2 <= data.count &&
data[data.endIndex - 2] == _HTTPCharacters.CR &&
data[data.endIndex - 1] == _HTTPCharacters.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}
return byAppending(headerLine: line)
}
/// Append a status line.
///
/// If the line is empty, it marks the end of the header, and the result
/// 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 {
if line.isEmpty {
switch self {
case .partial(let header): return .complete(header)
case .complete: return .partial(_HTTPURLProtocol._ResponseHeaderLines())
}
} else {
let header = partialResponseHeader
return .partial(header.byAppending(headerLine: line))
}
}
private var partialResponseHeader: _HTTPURLProtocol._ResponseHeaderLines {
switch self {
case .partial(let header): return header
case .complete: return _HTTPURLProtocol._ResponseHeaderLines()
}
}
}
private extension _HTTPURLProtocol._ResponseHeaderLines {
/// Returns a copy of the lines with the new line appended to it.
func byAppending(headerLine line: String) -> _HTTPURLProtocol._ResponseHeaderLines {
var l = self.lines
l.append(line)
return _HTTPURLProtocol._ResponseHeaderLines(headerLines: l)
}
}
internal extension _HTTPURLProtocol._ResponseHeaderLines {
/// Create an `NSHTTPRULResponse` from the lines.
///
Expand Down Expand Up @@ -184,22 +107,6 @@ extension _HTTPURLProtocol._HTTPMessage._Version {
}
}


// Characters that we need for HTTP parsing:

struct _HTTPCharacters {
/// *Carriage Return* symbol
static let CR: UInt8 = 0x0d
/// *Line Feed* symbol
static let LF: UInt8 = 0x0a
/// *Space* symbol
static let Space = UnicodeScalar(0x20)
static let HorizontalTab = UnicodeScalar(0x09)
static let Colon = UnicodeScalar(0x3a)
/// *Separators* according to RFC 2616
static let Separators = NSCharacterSet(charactersIn: "()<>@,;:\\\"/[]?={} \t")
}

private extension _HTTPURLProtocol._HTTPMessage._StartLine {
init?(line: String) {
guard let r = line.splitRequestLine() else { return nil }
Expand Down
1 change: 1 addition & 0 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@
'Foundation/URLSession/Configuration.swift',
'Foundation/URLSession/libcurl/EasyHandle.swift',
'Foundation/URLSession/BodySource.swift',
'Foundation/URLSession/Message.swift',
'Foundation/URLSession/http/HTTPMessage.swift',
'Foundation/URLSession/libcurl/MultiHandle.swift',
'Foundation/URLSession/URLSession.swift',
Expand Down