Skip to content

Commit

Permalink
feat: support custom host header
Browse files Browse the repository at this point in the history
  • Loading branch information
koraykoska committed Nov 11, 2023
1 parent 1543bcb commit 6140eaa
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
14 changes: 13 additions & 1 deletion Sources/libwebsockets/WebsocketClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,12 @@ public class WebsocketClient: WebsocketConnection {
// TODO: Use query and all other params?
// lwsCCInfo.host = lws_canonical_hostname(context)
let lwsCCInfoHostHeader = "\(host):\(port)".utf8CString
lwsCCInfo.host = lwsCCInfoHostHeader.toCPointer()
let lwsCCInfoCustomHostHeader = headers[caseInsensitive: "host"]?.utf8CString ?? headers[caseInsensitive: "host:"]?.utf8CString
if let lwsCCInfoCustomHostHeader {
lwsCCInfo.host = lwsCCInfoCustomHostHeader.toCPointer()
} else {
lwsCCInfo.host = lwsCCInfoHostHeader.toCPointer()
}
let lwsCCInfoOrigin = origin.utf8CString
lwsCCInfo.origin = lwsCCInfoOrigin.toCPointer()
lwsCCInfo.protocol = websocketClientContext.lwsProtocols.name
Expand Down Expand Up @@ -398,6 +403,7 @@ public class WebsocketClient: WebsocketConnection {
// Make sure the below variables are retained until function end
_ = lwsCCInfoHost.count
_ = lwsCCInfoHostHeader.count
_ = lwsCCInfoCustomHostHeader?.count
_ = lwsCCInfoPath.count
_ = lwsCCInfoOrigin.count
}
Expand Down Expand Up @@ -974,6 +980,12 @@ internal func _lws_swift_websocketClientCallback(
let end = p.pointee?.advanced(by: len)

for header in websocketClient.headers {
let lowercaseHeaderKey = header.key.lowercased()
if lowercaseHeaderKey == "host" || lowercaseHeaderKey == "host:" {
// Host was set already in client connect info
continue
}

let keyString = header.key.utf8CString
let valueString = header.value.utf8CString
guard lws_add_http_header_by_name(
Expand Down
18 changes: 18 additions & 0 deletions Sources/libwebsockets/WebsocketTools.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,21 @@ internal extension Data {
}
}
}

internal extension Dictionary where Key == String {
subscript(caseInsensitive key: Key) -> Value? {
get {
if let k = keys.first(where: { $0.caseInsensitiveCompare(key) == .orderedSame }) {
return self[k]
}
return nil
}
set {
if let k = keys.first(where: { $0.caseInsensitiveCompare(key) == .orderedSame }) {
self[k] = newValue
} else {
self[key] = newValue
}
}
}
}

0 comments on commit 6140eaa

Please sign in to comment.