StringHTTPHandler.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. //////////////////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // StringHTTPHandler.swift
  4. // Starscream
  5. //
  6. // Created by Dalton Cherry on 8/25/19.
  7. // Copyright © 2019 Vluxe. All rights reserved.
  8. //
  9. // Licensed under the Apache License, Version 2.0 (the "License");
  10. // you may not use this file except in compliance with the License.
  11. // You may obtain a copy of the License at
  12. //
  13. // http://www.apache.org/licenses/LICENSE-2.0
  14. //
  15. // Unless required by applicable law or agreed to in writing, software
  16. // distributed under the License is distributed on an "AS IS" BASIS,
  17. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. // See the License for the specific language governing permissions and
  19. // limitations under the License.
  20. //
  21. //////////////////////////////////////////////////////////////////////////////////////////////////
  22. import Foundation
  23. public class StringHTTPHandler: HTTPHandler {
  24. var buffer = Data()
  25. weak var delegate: HTTPHandlerDelegate?
  26. public init() {
  27. }
  28. public func convert(request: URLRequest) -> Data {
  29. guard let url = request.url else {
  30. return Data()
  31. }
  32. var path = url.absoluteString
  33. let offset = (url.scheme?.count ?? 2) + 3
  34. path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
  35. if let range = path.range(of: "/") {
  36. path = String(path[range.lowerBound..<path.endIndex])
  37. } else {
  38. path = "/"
  39. if let query = url.query {
  40. path += "?" + query
  41. }
  42. }
  43. var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
  44. if let headers = request.allHTTPHeaderFields {
  45. for (key, val) in headers {
  46. httpBody += "\(key): \(val)\r\n"
  47. }
  48. }
  49. httpBody += "\r\n"
  50. guard var data = httpBody.data(using: .utf8) else {
  51. return Data()
  52. }
  53. if let body = request.httpBody {
  54. data.append(body)
  55. }
  56. return data
  57. }
  58. public func parse(data: Data) -> Int {
  59. let offset = findEndOfHTTP(data: data)
  60. if offset > 0 {
  61. buffer.append(data.subdata(in: 0..<offset))
  62. if parseContent(data: buffer) {
  63. buffer = Data()
  64. }
  65. } else {
  66. buffer.append(data)
  67. }
  68. return offset
  69. }
  70. //returns true when the buffer should be cleared
  71. func parseContent(data: Data) -> Bool {
  72. guard let str = String(data: data, encoding: .utf8) else {
  73. delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))
  74. return true
  75. }
  76. let splitArr = str.components(separatedBy: "\r\n")
  77. var code = -1
  78. var i = 0
  79. var headers = [String: String]()
  80. for str in splitArr {
  81. if i == 0 {
  82. let responseSplit = str.components(separatedBy: .whitespaces)
  83. guard responseSplit.count > 1 else {
  84. delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))
  85. return true
  86. }
  87. if let c = Int(responseSplit[1]) {
  88. code = c
  89. }
  90. } else {
  91. guard let separatorIndex = str.firstIndex(of: ":") else { break }
  92. let key = str.prefix(upTo: separatorIndex).trimmingCharacters(in: .whitespaces)
  93. let val = str.suffix(from: str.index(after: separatorIndex)).trimmingCharacters(in: .whitespaces)
  94. headers[key.lowercased()] = val
  95. }
  96. i += 1
  97. }
  98. if code != HTTPWSHeader.switchProtocolCode {
  99. delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers)))
  100. return true
  101. }
  102. delegate?.didReceiveHTTP(event: .success(headers))
  103. return true
  104. }
  105. public func register(delegate: HTTPHandlerDelegate) {
  106. self.delegate = delegate
  107. }
  108. private func findEndOfHTTP(data: Data) -> Int {
  109. let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
  110. var pointer = [UInt8]()
  111. data.withUnsafeBytes { pointer.append(contentsOf: $0) }
  112. var k = 0
  113. for i in 0..<data.count {
  114. if pointer[i] == endBytes[k] {
  115. k += 1
  116. if k == 4 {
  117. return i + 1
  118. }
  119. } else {
  120. k = 0
  121. }
  122. }
  123. return -1
  124. }
  125. }