// SPDX-License-Identifier: GPL-2.0-or-later module engine import encoding.base64 import net import net.http import net.urllib import os import strconv import time // Workers own their network connections. The caller owns file writes, callbacks // and mirror state, even with parallel downloads or a reentrant callback. struct DownloadTransport { messages chan NetMessage } struct NetMessage { payload &DownloadPayload chunk []u8 total i64 reply chan bool done bool response int result TransferResult } struct NetAttempt { payload &DownloadPayload messages chan NetMessage reply chan bool url string offset i64 mtime i64 timeout i64 user_agent string mut: response int written i64 headers []u8 headers_checked bool range_size i64 = -1 status TransferStatus = .failed } fn (mut handle Handle) new_download_transport() !&DownloadTransport { return &DownloadTransport{ messages: chan NetMessage{} } } fn (transport &DownloadTransport) submit(mut payload DownloadPayload) ! { timeout := if payload.handle.opts.integers[.disable_download_timeout] == 0 { i64(10 * time.second) } else { i64(-1) } mut attempt := &NetAttempt{ payload: payload messages: transport.messages reply: chan bool{} url: payload.url offset: payload.initial_size mtime: if payload.request.force { 0 } else { payload.existing_mtime } timeout: timeout user_agent: os.getenv_opt('HTTP_USER_AGENT') or { 'v.http' } } spawn attempt.run() } fn (transport &DownloadTransport) next() !(&DownloadPayload, TransferResult) { for { msg := <-transport.messages mut payload := msg.payload if msg.done { payload.response = msg.response if payload.handle.download_control.interrupted != 0 { return payload, TransferResult{ status: .failed, detail: 'download interrupted' } } return payload, msg.result } mut ok := payload.handle.download_control.interrupted == 0 if ok && msg.chunk.len > 0 { ok = payload.write_bytes(msg.chunk.data, uint(msg.chunk.len)) == uint(msg.chunk.len) if ok && msg.total > 0 { payload.emit(.progress, payload.written, msg.total, 0) } } msg.reply <- ok && payload.handle.download_control.interrupted == 0 } return error('no active download') } fn (mut attempt NetAttempt) run() { result := attempt.transfer() or { TransferResult{ status: if err.msg().contains('getaddrinfo failed') { TransferStatus.resolve_error } else { attempt.status } detail: err.msg() } } attempt.messages <- NetMessage{ payload: attempt.payload, done: true, response: attempt.response, result: result } } fn (mut attempt NetAttempt) send_bytes(chunk []u8, total i64) ! { // The synchronous reply keeps the transport's borrowed read buffer alive. attempt.messages <- NetMessage{ payload: attempt.payload, chunk: chunk, total: total, reply: attempt.reply } if !(<-attempt.reply) { return error('download stopped') } attempt.written += chunk.len } // Match proxy bypass rules against each redirect target as well as the initial URL. fn download_proxy(url urllib.URL) !&http.HttpProxy { host := url.hostname().trim_right('.').to_lower() bypass := os.getenv_opt('no_proxy') or { os.getenv('NO_PROXY') } for entry in bypass.split(',') { domain := entry.trim_space().trim('.').to_lower() if domain == '*' || (domain != '' && (host == domain || host.ends_with('.' + domain))) { return unsafe { nil } } if subnet := net.parse_cidr(domain) { if subnet.contains(host) { return unsafe { nil } } } } mut proxy := os.getenv(url.scheme + '_proxy') // CGI environments may populate HTTP_PROXY from a request header. if proxy == '' && url.scheme == 'https' { proxy = os.getenv('HTTPS_PROXY') } if proxy == '' { proxy = os.getenv_opt('all_proxy') or { os.getenv('ALL_PROXY') } } if proxy == '' { return unsafe { nil } } if !proxy.contains('://') { proxy = 'http://' + proxy } // net.http tunnels over HTTP or SOCKS5. An HTTPS proxy also requires TLS // to the proxy itself, independently of the TLS connection to the origin. if !proxy.starts_with('http://') && !proxy.starts_with('socks5://') { return error('this proxy protocol requires the libcurl backend') } return http.new_http_proxy(proxy) } fn (mut attempt NetAttempt) transfer() !TransferResult { attempt.send_bytes([], 0)! mut url := urllib.parse(attempt.url)! if url.scheme == 'file' { return attempt.copy_file(url) } for redirects in 0 .. 11 { if url.scheme !in ['http', 'https'] { return error('unsupported download protocol: ${url.scheme}') } mut request := http.Request{ url: url.str() user_agent: attempt.user_agent user_ptr: attempt validate: true proxy: download_proxy(url)! allow_redirect: false disable_connection_reuse: true max_retries: 1 stop_copying_limit: 1 read_timeout: attempt.timeout write_timeout: attempt.timeout on_progress: net_download_headers on_progress_body: net_download_body } request.add_header(.accept_encoding, 'identity') if auth := url.user { request.add_header(.authorization, 'Basic ' + base64.encode(('${auth.username}:${auth.password}').bytes())) } attempt.headers.clear() attempt.headers_checked = false if attempt.offset > 0 { request.add_header(.range, 'bytes=${attempt.offset}-') } else if attempt.mtime != 0 { request.add_header(.if_modified_since, time.unix(attempt.mtime).http_header_string()) } resp := request.do()! attempt.response = resp.status_code if resp.status_code in [301, 302, 303, 307, 308] { location := resp.header.get(.location) or { return error('redirect without Location') } if redirects == 10 { return error('too many redirects') } url = url.parse(location)! continue } if resp.status_code < 200 { return error('invalid final HTTP response') } if resp.status_code == 304 && (attempt.mtime == 0 || attempt.offset != 0) { return error('unexpected 304 response') } if resp.status_code >= 300 && resp.status_code < 400 && resp.status_code != 304 { return error('unexpected HTTP response ${resp.status_code}') } if resp.status_code >= 200 && resp.status_code < 300 && !resp.header.contains(.transfer_encoding) { if length := resp.header.get(.content_length) { size := strconv.parse_uint(length, 10, 63)! if u64(attempt.written) != size { return error('body length differs from Content-Length') } } } if resp.status_code == 206 && (attempt.offset == 0 || attempt.written != attempt.range_size) { attempt.status = .range_error return error('incomplete or unsolicited byte range') } modified := resp.header.get(.last_modified) or { '' } remote_time := if t := time.parse_rfc2616(modified) { t.unix() } else { i64(-1) } return TransferResult{ bytes: attempt.written unmodified: resp.status_code == 304 remote_time: remote_time effective_url: url.str() } } return error('too many redirects') } fn net_download_body(req &http.Request, chunk []u8, received u64, total u64, status int) ! { mut attempt := unsafe { &NetAttempt(req.user_ptr) } if status < 200 || status >= 300 || chunk.len == 0 { return } if status == 206 && (attempt.range_size < 0 || received > u64(attempt.range_size)) { attempt.status = .range_error return error('unexpected partial response') } if total > 0 && received > total { return error('body exceeds Content-Length') } attempt.send_bytes(chunk, i64(total))! } // Check the range before appending even one byte to a resumable partial. fn net_download_headers(req &http.Request, chunk []u8, _ u64) ! { mut attempt := unsafe { &NetAttempt(req.user_ptr) } if attempt.headers_checked { return } attempt.headers << chunk head := attempt.headers.bytestr() end := head.index('\r\n\r\n') or { if head.len > 65536 { return error('oversized HTTP response headers') } return } if end > 65536 { return error('oversized HTTP response headers') } attempt.headers_checked = true if attempt.offset == 0 { return } lines := head[..end].split('\r\n') code := lines[0].all_after(' ').all_before(' ').int() if code < 200 || code >= 300 { return } if code == 206 { for line in lines[1..] { if line.all_before(':').to_lower() != 'content-range' { continue } field := line.all_after(':').trim_space() if !field.starts_with('bytes ${attempt.offset}-') { break } bounds := field.all_after('-').split('/') if bounds.len != 2 { break } last := strconv.parse_int(bounds[0], 10, 64) or { break } size := strconv.parse_int(bounds[1], 10, 64) or { break } if size <= attempt.offset || last != size - 1 { break } attempt.range_size = size - attempt.offset return } } attempt.status = .range_error return error('server did not return the requested byte range') } fn (mut attempt NetAttempt) copy_file(url urllib.URL) !TransferResult { if url.host.to_lower() !in ['', 'localhost', '127.0.0.1'] || !url.path.starts_with('/') || url.path.contains('\x00') { return error('invalid local file URL') } mut file := os.open(url.path)! defer { file.close() } mut st := C.stat{} if C.fstat(file.fd, &st) != 0 { return os.last_error() } if st.st_mode & 0o170000 != 0o100000 { return error('download source is not a regular file') } size := i64(st.st_size) mtime := i64(st.st_mtime) if attempt.offset == 0 && attempt.mtime != 0 && mtime <= attempt.mtime { return TransferResult{ unmodified: true, effective_url: attempt.url } } if attempt.offset > 0 && attempt.offset >= size { return TransferResult{ status: .range_error } } file.seek(attempt.offset, .start)! remaining := size - attempt.offset mut buf := []u8{len: 65536} for attempt.written < remaining { n := file.read(mut buf)! if n == 0 || n > remaining - attempt.written { return error('local file changed during download') } attempt.send_bytes(buf[..n], remaining)! } return TransferResult{ bytes: attempt.written, expected: remaining, effective_url: attempt.url, remote_time: mtime } }