2017-02-08 03:25:44 +03:00
|
|
|
//
|
|
|
|
// Response.swift
|
2017-07-19 20:54:47 +03:00
|
|
|
// SoftU2F
|
2017-02-08 03:25:44 +03:00
|
|
|
//
|
|
|
|
// Created by Benjamin P Toews on 2/7/17.
|
|
|
|
// Copyright © 2017 GitHub. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
enum ResponseError: Error {
|
|
|
|
case BadSize
|
|
|
|
case BadStatus
|
|
|
|
case BadCertificate
|
2017-02-08 03:49:05 +03:00
|
|
|
case BadData
|
2017-02-08 03:25:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
protocol Response {
|
|
|
|
var body: Data { get }
|
|
|
|
var trailer: ResponseStatus { get }
|
|
|
|
|
|
|
|
init(body: Data, trailer: ResponseStatus)
|
|
|
|
|
|
|
|
func validateBody() throws
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implement RawConvertible
|
|
|
|
extension Response {
|
|
|
|
public var raw: Data {
|
|
|
|
let writer = DataWriter()
|
|
|
|
writer.writeData(body)
|
|
|
|
writer.write(trailer)
|
|
|
|
|
|
|
|
return writer.buffer
|
|
|
|
}
|
|
|
|
|
|
|
|
public init(raw: Data) throws {
|
|
|
|
let reader = DataReader(data: raw)
|
|
|
|
let body = try reader.readData(reader.remaining - 2)
|
|
|
|
let trailer: ResponseStatus = try reader.read()
|
|
|
|
|
|
|
|
self.init(body: body, trailer: trailer)
|
2017-02-08 03:49:05 +03:00
|
|
|
|
|
|
|
try validateBody()
|
2017-02-08 03:25:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// For testing with libu2f-host
|
|
|
|
public init(raw: Data, bodyOnly: Bool) throws {
|
|
|
|
if bodyOnly {
|
|
|
|
self.init(body: raw, trailer: .NoError)
|
|
|
|
} else {
|
|
|
|
try self.init(raw: raw)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|