Files
ziran/std/net_http_curl_linux.zi
T

501 lines
16 KiB
Ziran

#import "net_http"
#import "byte_text_linux"
#import "c_string"
curl :: #system_library "curl";
c :: #system_library "c";
#if #defined(_WIN32) {
// Windows long is 32 bits. An SRW lock replaces pthread_once there.
kernel32 :: #system_library "kernel32";
curl_global_init :: (flags: s32) -> s32 #foreign curl;
AcquireSRWLockExclusive :: (lock: *usize) #foreign kernel32;
ReleaseSRWLockExclusive :: (lock: *usize) #foreign kernel32;
} else {
curl_global_init :: (flags: s64) -> s32 #foreign curl;
CurlInitRoutine :: #type () #c_call;
pthread_once :: (control: *s32, routine: CurlInitRoutine) -> s32 #foreign c;
CurlMutexInit :: (mutex: *void, attributes: *void) -> s32 #foreign c "pthread_mutex_init";
CurlMutexLock :: (mutex: *void) -> s32 #foreign c "pthread_mutex_lock";
CurlMutexUnlock :: (mutex: *void) -> s32 #foreign c "pthread_mutex_unlock";
}
curl_easy_init :: () -> *void #foreign curl;
curl_easy_cleanup :: (handle: *void) #foreign curl;
curl_easy_reset :: (handle: *void) #foreign curl;
curl_easy_setopt :: (handle: *void, option: s32, args: ..any) -> s32 #foreign curl;
curl_easy_perform :: (handle: *void) -> s32 #foreign curl;
curl_easy_getinfo :: (handle: *void, option: s32, args: ..any) -> s32 #foreign curl;
curl_slist_append :: (list: *void, value: *u8) -> *void #foreign curl;
curl_slist_free_all :: (list: *void) #foreign curl;
CurlUrl :: 10002
CurlMethod :: 10036
CurlWriteData :: 10001
CurlWriteFunction :: 20011
CurlHeaders :: 10023
CurlAcceptEncoding :: 10102
CurlPostFields :: 10015
CurlPostSize :: 30120
CurlTimeoutMs :: 155
CurlConnectTimeoutMs :: 156
CurlNoSignal :: 99
CurlNoBody :: 44
CurlProxy :: 10004
CurlFollowLocation :: 52
CurlResponseCode :: 2097154
CurlMaxConnects :: 71
CurlPoolSlot :: struct {
handle: *void
origin: [512]u8
direct: bool
busy: bool
}
CurlLease :: struct {
handle: *void
slot: s32
}
// Four idle connections at most. A handle belongs to exactly one request
// while busy; excess concurrent requests retain their existing private handle.
curl_pool: [4]CurlPoolSlot;
curl_once: s32 = 0;
curl_init_result: s32 = -1;
#if #defined(_WIN32) {
curl_lock: usize = 0;
curl_pool_lock: usize = 0;
LockCurlPool :: () { AcquireSRWLockExclusive(*curl_pool_lock) }
UnlockCurlPool :: () { ReleaseSRWLockExclusive(*curl_pool_lock) }
CurlReady :: () -> bool {
AcquireSRWLockExclusive(*curl_lock)
if curl_once == 0 {
curl_init_result = curl_global_init(3)
curl_once = 1
}
ready := curl_init_result == 0
ReleaseSRWLockExclusive(*curl_lock)
return ready
}
} else {
// Same aligned pthread_mutex_t storage used by the native thread module.
curl_pool_lock: [8]u64;
LockCurlPool :: () { unused CurlMutexLock(cast(*void)*curl_pool_lock[0]) }
UnlockCurlPool :: () { unused CurlMutexUnlock(cast(*void)*curl_pool_lock[0]) }
InitCurl :: () {
curl_init_result = curl_global_init(3)
if curl_init_result == 0 {
curl_init_result = CurlMutexInit(cast(*void)*curl_pool_lock[0], null)
}
}
CurlReady :: () -> bool {
routine: CurlInitRoutine = InitCurl
return pthread_once(*curl_once, routine) == 0 &&
curl_init_result == 0
}
}
// Credentials in URL authorities retain a private handle. Normal bearer
// requests pool by origin and proxy policy, with every option reset afterward.
CurlOrigin :: (url: string) -> string {
start: s64 = 0
if StartsWith(url, "https://") { start = 8 }
else if StartsWith(url, "http://") { start = 7 }
else { return "" }
end := start
while end < url.count && url[end] != 47 && url[end] != 63 && url[end] != 35 {
if url[end] <= 32 || url[end] == 64 || url[end] == 92 { return "" }
end += 1
}
if end == start || end >= 512 { return "" }
return url[0:end]
}
AcquireCurl :: (url: string, direct: bool) -> CurlLease {
lease := CurlLease.{.slot = -1}
origin := CurlOrigin(url)
if origin.count == 0 {
lease.handle = curl_easy_init()
return lease
}
LockCurlPool()
chosen: s32 = -1
unused_slot: s32 = -1
for slot, index: curl_pool {
if slot.busy { continue }
if !slot.busy && unused_slot < 0 { unused_slot = cast(s32)index }
if slot.handle != null && slot.direct == direct && TextFromCString(*slot.origin[0]) == origin {
chosen = cast(s32)index
break
}
if slot.handle == null { unused_slot = cast(s32)index }
}
if chosen < 0 { chosen = unused_slot }
if chosen >= 0 {
slot := *curl_pool[chosen]
if slot.handle != null && (slot.direct != direct || TextFromCString(*slot.origin[0]) != origin) {
curl_easy_cleanup(slot.handle)
slot.handle = null
}
if slot.handle == null { slot.handle = curl_easy_init() }
if slot.handle != null && CopyCString(origin, slot.origin[:]) {
slot.direct = direct
slot.busy = true
lease.handle = slot.handle
lease.slot = chosen
}
}
UnlockCurlPool()
if lease.handle == null { lease.handle = curl_easy_init() }
return lease
}
ReleaseCurl :: (lease: CurlLease) {
// Reset clears borrowed headers, body, token and output pointers while
// retaining the connection and TLS session. Cookies are never enabled.
curl_easy_reset(lease.handle)
if lease.slot < 0 {
curl_easy_cleanup(lease.handle)
return
}
LockCurlPool()
curl_pool[lease.slot].busy = false
UnlockCurlPool()
}
#program_export
CloseCurlConnections :: () {
if !CurlReady() { return }
LockCurlPool()
for index: cast(s64)0..curl_pool.count - 1 {
slot := *curl_pool[index]
if slot.busy || slot.handle == null { continue }
curl_easy_cleanup(slot.handle)
slot.handle = null
slot.origin = .{}
}
UnlockCurlPool()
}
StartsWith :: (value: string, prefix: string) -> bool {
if value.count < prefix.count { return false }
index: s64 = 0
while index < cast(s64)prefix.count {
if value[index] != prefix[index] { return false }
index += 1
}
return true
}
MethodToken :: (value: string) -> bool {
if value.count == 0 || value.count >= 32 { return false }
index: s64 = 0
while index < cast(s64)value.count {
byte := value[index]
if !((byte >= cast(u8)65 && byte <= cast(u8)90) ||
(byte >= cast(u8)97 && byte <= cast(u8)122) ||
(byte >= cast(u8)48 && byte <= cast(u8)57) ||
byte == cast(u8)45) { return false }
index += 1
}
return true
}
HeaderName :: (value: string) -> bool {
if value.count == 0 || value.count >= 256 { return false }
index: s64 = 0
while index < cast(s64)value.count {
byte := value[index]
if !((byte >= cast(u8)65 && byte <= cast(u8)90) ||
(byte >= cast(u8)97 && byte <= cast(u8)122) ||
(byte >= cast(u8)48 && byte <= cast(u8)57) ||
byte == cast(u8)45) { return false }
index += 1
}
return true
}
CurlFailure :: enum {
None
InvalidLimit
InvalidUrl
InvalidMethod
Unavailable
ConfigureError
TransportError
TooLarge
}
CurlResult :: struct {
status: s32
length: s64
code: s32
truncated: bool
problem: CurlFailure
}
CurlOutput :: struct {
data: *u8
capacity: s64
length: s64
truncated: bool
}
CurlWriteCallback64 :: #type (data: *u8, size: u64,
count: u64, user: *void) -> u64 #c_call;
CurlWriteCallback32 :: #type (data: *u8, size: u32,
count: u32, user: *void) -> u32 #c_call;
AppendCurlOutput :: (data: *u8, size: u64, count: u64,
context: *CurlOutput) -> u64 {
if context == null || size == 0 || count == 0 { return 0 }
if size > cast(u64)9223372036854775807 / count {
context.truncated = true
return 0
}
bytes := size * count
if context.length < 0 || context.capacity < 1 ||
bytes > cast(u64)(context.capacity - context.length - 1) {
context.truncated = true
return 0
}
index: u64 = 0
while index < bytes {
context.data[context.length + cast(s64)index] = data[index]
index += 1
}
context.length += cast(s64)bytes
context.data[context.length] = cast(u8)0
return bytes
}
CurlWrite64 :: (data: *u8, size: u64, count: u64, user: *void) -> u64 {
return AppendCurlOutput(data, size, count, cast(*CurlOutput)user)
}
CurlWrite32 :: (data: *u8, size: u32, count: u32, user: *void) -> u32 {
return cast(u32)AppendCurlOutput(data, cast(u64)size,
cast(u64)count, cast(*CurlOutput)user)
}
SetCurlLong :: (handle: *void, option: s32, value: s32) -> bool {
if size_of(type_of(handle)) == 8 {
return curl_easy_setopt(handle, option, cast(s64)value) == 0
}
return curl_easy_setopt(handle, option, value) == 0
}
ReadCurlStatus :: (handle: *void) -> s32 {
if size_of(type_of(handle)) == 8 {
code: s64 = 0
if curl_easy_getinfo(handle, CurlResponseCode, *code) == 0 {
return cast(s32)code
}
} else {
code: s32 = 0
if curl_easy_getinfo(handle, CurlResponseCode, *code) == 0 {
return code
}
}
return 0
}
HeaderText :: (prefix: string, value: string, output: []u8) -> bool {
if prefix.count >= output.count ||
value.count >= output.count - prefix.count { return false }
index: s64 = 0
while index < cast(s64)prefix.count {
output[index] = prefix[index]
index += 1
}
offset: s64 = 0
while offset < cast(s64)value.count {
byte := value[offset]
if byte == cast(u8)0 || byte == cast(u8)10 || byte == cast(u8)13 {
return false
}
output[index + offset] = byte
offset += 1
}
output[index + offset] = cast(u8)0
return true
}
AddCurlHeader :: (headers: **void, prefix: string, value: string,
buffer: []u8) -> bool {
if !HeaderText(prefix, value, buffer) { return false }
next := curl_slist_append(headers.*, *buffer[0])
if next == null { return false }
headers.* = next
return true
}
AddNamedHeader :: (headers: **void, name: string, value: string,
buffer: []u8) -> bool {
if !HeaderName(name) || value.count >= 8192 || name.count + 2 >= buffer.count ||
value.count >= buffer.count - name.count - 2 { return false }
index: s64 = 0
while index < cast(s64)name.count {
buffer[index] = name[index]
index += 1
}
buffer[index] = cast(u8)58
buffer[index + 1] = cast(u8)32
offset: s64 = 0
while offset < cast(s64)value.count {
byte := value[offset]
if byte == cast(u8)0 || byte == cast(u8)10 || byte == cast(u8)13 {
return false
}
buffer[index + 2 + offset] = byte
offset += 1
}
buffer[index + 2 + offset] = cast(u8)0
next := curl_slist_append(headers.*, *buffer[0])
if next == null { return false }
headers.* = next
return true
}
// The caller owns output. It remains NUL terminated, including on failure.
// HTTP errors retain their status and body for protocol-level decisions.
#program_export
SendCurl :: (request: HttpRequest, output: []u8) -> CurlResult {
return SendCurlWithin(request, output, 20000)
}
// The same request with its own total timeout, for slow services such as
// model generation. Connecting still has 10 seconds.
#program_export
SendCurlWithin :: (request: HttpRequest, output: []u8, timeout_ms: s32) -> CurlResult {
return SendCurlConfigured(request, output, timeout_ms, false)
}
// Bypass inherited proxy settings and never follow redirects. Callers still
// own URL authorization; this is useful for private local service transports.
#program_export
SendCurlDirectWithin :: (request: HttpRequest, output: []u8, timeout_ms: s32) -> CurlResult {
return SendCurlConfigured(request, output, timeout_ms, true)
}
SendCurlConfigured :: (request: HttpRequest, output: []u8, timeout_ms: s32, direct: bool) -> CurlResult {
result: CurlResult
result.code = -1
if output.count == 0 { result.problem = .InvalidLimit; return result }
output[0] = cast(u8)0
url: [2048]u8
method: [32]u8
if request.url.count >= url.count || !HttpUrlValid(request.url) ||
!(StartsWith(request.url, "http://") ||
StartsWith(request.url, "https://")) ||
!CopyCString(request.url, url[:]) {
result.problem = .InvalidUrl
return result
}
if request.method.count >= method.count || !MethodToken(request.method) ||
!CopyCString(request.method, method[:]) {
result.problem = .InvalidMethod
return result
}
if !CurlReady() { result.problem = .Unavailable; return result }
lease := AcquireCurl(request.url, direct)
handle := lease.handle
if handle == null { result.problem = .Unavailable; return result }
context: CurlOutput
context.data = *output[0]
context.capacity = cast(s64)output.count
context.length = 0
context.truncated = false
headers: *void = null
// Negotiate encodings supported by this libcurl and decode them before
// the bounded write callback. Capacity limits apply to decoded bytes.
encoding: [1]u8
encoding[0] = cast(u8)0
configured := curl_easy_setopt(handle, CurlUrl, *url[0]) == 0 &&
curl_easy_setopt(handle, CurlMethod, *method[0]) == 0 &&
curl_easy_setopt(handle, CurlAcceptEncoding, *encoding[0]) == 0 &&
curl_easy_setopt(handle, CurlWriteData, *context) == 0 &&
timeout_ms > 0 && SetCurlLong(handle, CurlTimeoutMs, timeout_ms) &&
SetCurlLong(handle, CurlConnectTimeoutMs, 10000) &&
SetCurlLong(handle, CurlNoSignal, 1) &&
SetCurlLong(handle, CurlMaxConnects, 1)
if configured && direct {
proxy: [1]u8
proxy[0] = cast(u8)0
configured = curl_easy_setopt(handle, CurlProxy, *proxy[0]) == 0 &&
SetCurlLong(handle, CurlFollowLocation, 0)
}
if configured && request.method == "HEAD" {
configured = SetCurlLong(handle, CurlNoBody, 1)
}
if configured {
if size_of(type_of(handle)) == 8 {
writer: CurlWriteCallback64 = CurlWrite64
configured = curl_easy_setopt(handle, CurlWriteFunction,
writer) == 0
} else {
writer: CurlWriteCallback32 = CurlWrite32
configured = curl_easy_setopt(handle, CurlWriteFunction,
writer) == 0
}
}
// Named values allow 8191 bytes independently of the validated name.
// Include the maximum 255-byte name, ': ', and the trailing NUL.
header: [8449]u8
if configured && request.token.count > 0 {
configured = AddCurlHeader(*headers, "Authorization: Bearer ",
request.token, header[0:8192])
}
if configured && request.accept.count > 0 {
configured = AddCurlHeader(*headers, "Accept: ",
request.accept, header[0:8192])
}
if configured && request.content_type.count > 0 {
configured = AddCurlHeader(*headers, "Content-Type: ",
request.content_type, header[0:8192])
}
if configured && request.headers.count > 32 { configured = false }
index: s64 = 0
while configured && index < cast(s64)request.headers.count {
item := request.headers[index]
configured = AddNamedHeader(*headers, item.name, item.value,
header[:])
index += 1
}
if configured && headers != null {
configured = curl_easy_setopt(handle, CurlHeaders, headers) == 0
}
if configured && (request.body.count > 0 || request.method == "POST") {
empty: [1]u8
empty[0] = cast(u8)0
body_text := request.body
descriptor := cast(*TextDescriptor)(*body_text)
body: *u8 = *empty[0]
if request.body.count > 0 { body = descriptor.data }
configured = body != null &&
curl_easy_setopt(handle, CurlPostFields, body) == 0 &&
curl_easy_setopt(handle, CurlPostSize,
cast(s64)request.body.count) == 0
}
if configured {
result.code = curl_easy_perform(handle)
result.status = ReadCurlStatus(handle)
}
result.length = context.length
result.truncated = context.truncated
if !configured { result.problem = .ConfigureError }
else if context.truncated { result.problem = .TooLarge }
else if result.code != 0 { result.problem = .TransportError }
ReleaseCurl(lease)
if headers != null { curl_slist_free_all(headers) }
return result
}