Skip to content

Commit 8ceaeb1

Browse files
committed
Fix an issue causing a crash when the Content-Lenght was negative
* Add an unit tests for the new exception * Fix an Swiftlint warning regarding the colon * Fix a spelling error
1 parent c42a483 commit 8ceaeb1

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

XCode/Sources/HttpParser.swift

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77

88
import Foundation
99

10-
enum HttpParserError: Error {
10+
enum HttpParserError: Error, Equatable {
1111
case invalidStatusLine(String)
12+
case negativeContentLength
1213
}
1314

1415
public class HttpParser {
@@ -29,6 +30,11 @@ public class HttpParser {
2930
request.queryParams = urlComponents?.queryItems?.map { ($0.name, $0.value ?? "") } ?? []
3031
request.headers = try readHeaders(socket)
3132
if let contentLength = request.headers["content-length"], let contentLengthValue = Int(contentLength) {
33+
// Prevent a buffer overflow and runtime error trying to create an `UnsafeMutableBufferPointer` with
34+
// a negative length
35+
guard contentLengthValue >= 0 else {
36+
throw HttpParserError.negativeContentLength
37+
}
3238
request.body = try readBody(socket, size: contentLengthValue)
3339
}
3440
return request

XCode/Sources/WebSockets.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ public class WebSocketSession: Hashable, Equatable {
233233
frm.rsv3 = fst & 0x10
234234
guard frm.rsv1 == 0 && frm.rsv2 == 0 && frm.rsv3 == 0
235235
else {
236-
throw WsError.protocolError("Reserved frame bit has not been negocitated.")
236+
throw WsError.protocolError("Reserved frame bit has not been negociated.")
237237
}
238238
let opc = fst & 0x0F
239239
guard let opcode = OpCode(rawValue: opc) else {

XCode/Tests/SwifterTestsHttpParser.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,14 @@ class SwifterTestsHttpParser: XCTestCase {
101101
XCTAssert(false, "Parser should not throw any errors if there is a valid 'Content-Length' header.")
102102
}
103103

104+
do {
105+
_ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\r\nContent-Length: -1\r\n\r\n"))
106+
} catch let error {
107+
let error = error as? HttpParserError
108+
XCTAssertNotNil(error)
109+
XCTAssertEqual(error!, HttpParserError.negativeContentLength)
110+
}
111+
104112
do {
105113
_ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nContent-Length: 5\n\n12345"))
106114
} catch {

0 commit comments

Comments
 (0)