| 1 | // Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT license |
| 3 | // that can be found in the LICENSE file. |
| 4 | module http |
| 5 | |
| 6 | #flag windows -I @VEXEROOT/thirdparty/vschannel |
| 7 | #flag -l ws2_32 -l crypt32 -l secur32 -l user32 |
| 8 | #include "vschannel.c" |
| 9 | // Win7 needs TLS 1.2 selected before Schannel credentials are acquired. |
| 10 | #define vschannel_use_tls12_client_protocol() (protocol = SP_PROT_TLS1_2_CLIENT) |
| 11 | |
| 12 | pub struct C.TlsContext {} |
| 13 | |
| 14 | const C.vsc_init_resp_buff_size int |
| 15 | |
| 16 | fn C.new_tls_context() C.TlsContext |
| 17 | fn C.vschannel_use_tls12_client_protocol() |
| 18 | fn C.vschannel_init(tls_ctx &C.TlsContext, validate_server_certificate C.BOOL) |
| 19 | fn C.vschannel_last_error(tls_ctx &C.TlsContext) int |
| 20 | |
| 21 | fn vschannel_ssl_do(req &Request, port int, method Method, host_name string, path string, data string, header Header) !Response { |
| 22 | mut ctx := C.new_tls_context() |
| 23 | C.vschannel_use_tls12_client_protocol() |
| 24 | C.vschannel_init(&ctx, C.BOOL(if req.validate { 1 } else { 0 })) |
| 25 | mut buff := unsafe { malloc_noscan(C.vsc_init_resp_buff_size) } |
| 26 | addr := host_name |
| 27 | sdata := req.build_request_headers_with(method, host_name, port, path, data, header) |
| 28 | $if trace_http_request ? { |
| 29 | eprintln('> ${sdata}') |
| 30 | } |
| 31 | length := C.request(&ctx, port, addr.to_wide(), sdata.str, sdata.len, &buff, v_realloc) |
| 32 | err_code := C.vschannel_last_error(&ctx) |
| 33 | C.vschannel_cleanup(&ctx) |
| 34 | if length <= 0 { |
| 35 | if err_code != 0 { |
| 36 | return vschannel_request_error(err_code) |
| 37 | } |
| 38 | return error('http: vschannel request failed') |
| 39 | } |
| 40 | response_text := unsafe { buff.vstring_with_len(length) } |
| 41 | if req.on_progress != unsafe { nil } { |
| 42 | req.on_progress(req, unsafe { buff.vbytes(length) }, u64(length))! |
| 43 | } |
| 44 | $if trace_http_response ? { |
| 45 | eprintln('< ${response_text}') |
| 46 | } |
| 47 | if req.on_finish != unsafe { nil } { |
| 48 | req.on_finish(req, u64(response_text.len))! |
| 49 | } |
| 50 | return vschannel_parse_response(response_text, err_code) |
| 51 | } |
| 52 | |