| 1 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 2 | module engine |
| 3 | |
| 4 | import encoding.base64 |
| 5 | import net |
| 6 | import net.http |
| 7 | import net.urllib |
| 8 | import os |
| 9 | import strconv |
| 10 | import time |
| 11 | |
| 12 | // Workers own their network connections. The caller owns file writes, callbacks |
| 13 | // and mirror state, even with parallel downloads or a reentrant callback. |
| 14 | struct DownloadTransport { |
| 15 | messages chan NetMessage |
| 16 | } |
| 17 | |
| 18 | struct NetMessage { |
| 19 | payload &DownloadPayload |
| 20 | chunk []u8 |
| 21 | total i64 |
| 22 | reply chan bool |
| 23 | done bool |
| 24 | response int |
| 25 | result TransferResult |
| 26 | } |
| 27 | |
| 28 | struct NetAttempt { |
| 29 | payload &DownloadPayload |
| 30 | messages chan NetMessage |
| 31 | reply chan bool |
| 32 | url string |
| 33 | offset i64 |
| 34 | mtime i64 |
| 35 | timeout i64 |
| 36 | user_agent string |
| 37 | mut: |
| 38 | response int |
| 39 | written i64 |
| 40 | headers []u8 |
| 41 | headers_checked bool |
| 42 | range_size i64 = -1 |
| 43 | status TransferStatus = .failed |
| 44 | } |
| 45 | |
| 46 | fn (mut handle Handle) new_download_transport() !&DownloadTransport { |
| 47 | return &DownloadTransport{ messages: chan NetMessage{} } |
| 48 | } |
| 49 | |
| 50 | fn (transport &DownloadTransport) submit(mut payload DownloadPayload) ! { |
| 51 | timeout := if payload.handle.opts.integers[.disable_download_timeout] == 0 { |
| 52 | i64(10 * time.second) |
| 53 | } else { |
| 54 | i64(-1) |
| 55 | } |
| 56 | mut attempt := &NetAttempt{ |
| 57 | payload: payload |
| 58 | messages: transport.messages |
| 59 | reply: chan bool{} |
| 60 | url: payload.url |
| 61 | offset: payload.initial_size |
| 62 | mtime: if payload.request.force { 0 } else { payload.existing_mtime } |
| 63 | timeout: timeout |
| 64 | user_agent: os.getenv_opt('HTTP_USER_AGENT') or { 'v.http' } |
| 65 | } |
| 66 | spawn attempt.run() |
| 67 | } |
| 68 | |
| 69 | fn (transport &DownloadTransport) next() !(&DownloadPayload, TransferResult) { |
| 70 | for { |
| 71 | msg := <-transport.messages |
| 72 | mut payload := msg.payload |
| 73 | if msg.done { |
| 74 | payload.response = msg.response |
| 75 | if payload.handle.download_control.interrupted != 0 { |
| 76 | return payload, TransferResult{ status: .failed, detail: 'download interrupted' } |
| 77 | } |
| 78 | return payload, msg.result |
| 79 | } |
| 80 | mut ok := payload.handle.download_control.interrupted == 0 |
| 81 | if ok && msg.chunk.len > 0 { |
| 82 | ok = payload.write_bytes(msg.chunk.data, uint(msg.chunk.len)) == uint(msg.chunk.len) |
| 83 | if ok && msg.total > 0 { |
| 84 | payload.emit(.progress, payload.written, msg.total, 0) |
| 85 | } |
| 86 | } |
| 87 | msg.reply <- ok && payload.handle.download_control.interrupted == 0 |
| 88 | } |
| 89 | return error('no active download') |
| 90 | } |
| 91 | |
| 92 | fn (mut attempt NetAttempt) run() { |
| 93 | result := attempt.transfer() or { |
| 94 | TransferResult{ |
| 95 | status: if err.msg().contains('getaddrinfo failed') { |
| 96 | TransferStatus.resolve_error |
| 97 | } else { |
| 98 | attempt.status |
| 99 | } |
| 100 | detail: err.msg() |
| 101 | } |
| 102 | } |
| 103 | attempt.messages <- NetMessage{ payload: attempt.payload, done: true, response: attempt.response, result: result } |
| 104 | } |
| 105 | |
| 106 | fn (mut attempt NetAttempt) send_bytes(chunk []u8, total i64) ! { |
| 107 | // The synchronous reply keeps the transport's borrowed read buffer alive. |
| 108 | attempt.messages <- NetMessage{ payload: attempt.payload, chunk: chunk, total: total, reply: attempt.reply } |
| 109 | if !(<-attempt.reply) { return error('download stopped') } |
| 110 | attempt.written += chunk.len |
| 111 | } |
| 112 | |
| 113 | // Match proxy bypass rules against each redirect target as well as the initial URL. |
| 114 | fn download_proxy(url urllib.URL) !&http.HttpProxy { |
| 115 | host := url.hostname().trim_right('.').to_lower() |
| 116 | bypass := os.getenv_opt('no_proxy') or { os.getenv('NO_PROXY') } |
| 117 | for entry in bypass.split(',') { |
| 118 | domain := entry.trim_space().trim('.').to_lower() |
| 119 | if domain == '*' || (domain != '' && (host == domain || host.ends_with('.' + domain))) { |
| 120 | return unsafe { nil } |
| 121 | } |
| 122 | if subnet := net.parse_cidr(domain) { |
| 123 | if subnet.contains(host) { return unsafe { nil } } |
| 124 | } |
| 125 | } |
| 126 | mut proxy := os.getenv(url.scheme + '_proxy') |
| 127 | // CGI environments may populate HTTP_PROXY from a request header. |
| 128 | if proxy == '' && url.scheme == 'https' { proxy = os.getenv('HTTPS_PROXY') } |
| 129 | if proxy == '' { proxy = os.getenv_opt('all_proxy') or { os.getenv('ALL_PROXY') } } |
| 130 | if proxy == '' { return unsafe { nil } } |
| 131 | if !proxy.contains('://') { proxy = 'http://' + proxy } |
| 132 | // net.http tunnels over HTTP or SOCKS5. An HTTPS proxy also requires TLS |
| 133 | // to the proxy itself, independently of the TLS connection to the origin. |
| 134 | if !proxy.starts_with('http://') && !proxy.starts_with('socks5://') { |
| 135 | return error('this proxy protocol requires the libcurl backend') |
| 136 | } |
| 137 | return http.new_http_proxy(proxy) |
| 138 | } |
| 139 | |
| 140 | fn (mut attempt NetAttempt) transfer() !TransferResult { |
| 141 | attempt.send_bytes([], 0)! |
| 142 | mut url := urllib.parse(attempt.url)! |
| 143 | if url.scheme == 'file' { return attempt.copy_file(url) } |
| 144 | for redirects in 0 .. 11 { |
| 145 | if url.scheme !in ['http', 'https'] { |
| 146 | return error('unsupported download protocol: ${url.scheme}') |
| 147 | } |
| 148 | mut request := http.Request{ |
| 149 | url: url.str() |
| 150 | user_agent: attempt.user_agent |
| 151 | user_ptr: attempt |
| 152 | validate: true |
| 153 | proxy: download_proxy(url)! |
| 154 | allow_redirect: false |
| 155 | disable_connection_reuse: true |
| 156 | max_retries: 1 |
| 157 | stop_copying_limit: 1 |
| 158 | read_timeout: attempt.timeout |
| 159 | write_timeout: attempt.timeout |
| 160 | on_progress: net_download_headers |
| 161 | on_progress_body: net_download_body |
| 162 | } |
| 163 | request.add_header(.accept_encoding, 'identity') |
| 164 | if auth := url.user { |
| 165 | request.add_header(.authorization, 'Basic ' + base64.encode(('${auth.username}:${auth.password}').bytes())) |
| 166 | } |
| 167 | attempt.headers.clear() |
| 168 | attempt.headers_checked = false |
| 169 | if attempt.offset > 0 { |
| 170 | request.add_header(.range, 'bytes=${attempt.offset}-') |
| 171 | } else if attempt.mtime != 0 { |
| 172 | request.add_header(.if_modified_since, time.unix(attempt.mtime).http_header_string()) |
| 173 | } |
| 174 | resp := request.do()! |
| 175 | attempt.response = resp.status_code |
| 176 | if resp.status_code in [301, 302, 303, 307, 308] { |
| 177 | location := resp.header.get(.location) or { return error('redirect without Location') } |
| 178 | if redirects == 10 { return error('too many redirects') } |
| 179 | url = url.parse(location)! |
| 180 | continue |
| 181 | } |
| 182 | if resp.status_code < 200 { return error('invalid final HTTP response') } |
| 183 | if resp.status_code == 304 && (attempt.mtime == 0 || attempt.offset != 0) { |
| 184 | return error('unexpected 304 response') |
| 185 | } |
| 186 | if resp.status_code >= 300 && resp.status_code < 400 && resp.status_code != 304 { |
| 187 | return error('unexpected HTTP response ${resp.status_code}') |
| 188 | } |
| 189 | if resp.status_code >= 200 && resp.status_code < 300 && !resp.header.contains(.transfer_encoding) { |
| 190 | if length := resp.header.get(.content_length) { |
| 191 | size := strconv.parse_uint(length, 10, 63)! |
| 192 | if u64(attempt.written) != size { |
| 193 | return error('body length differs from Content-Length') |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | if resp.status_code == 206 && (attempt.offset == 0 || attempt.written != attempt.range_size) { |
| 198 | attempt.status = .range_error |
| 199 | return error('incomplete or unsolicited byte range') |
| 200 | } |
| 201 | modified := resp.header.get(.last_modified) or { '' } |
| 202 | remote_time := if t := time.parse_rfc2616(modified) { t.unix() } else { i64(-1) } |
| 203 | return TransferResult{ |
| 204 | bytes: attempt.written |
| 205 | unmodified: resp.status_code == 304 |
| 206 | remote_time: remote_time |
| 207 | effective_url: url.str() |
| 208 | } |
| 209 | } |
| 210 | return error('too many redirects') |
| 211 | } |
| 212 | |
| 213 | fn net_download_body(req &http.Request, chunk []u8, received u64, total u64, status int) ! { |
| 214 | mut attempt := unsafe { &NetAttempt(req.user_ptr) } |
| 215 | if status < 200 || status >= 300 || chunk.len == 0 { return } |
| 216 | if status == 206 && (attempt.range_size < 0 || received > u64(attempt.range_size)) { |
| 217 | attempt.status = .range_error |
| 218 | return error('unexpected partial response') |
| 219 | } |
| 220 | if total > 0 && received > total { return error('body exceeds Content-Length') } |
| 221 | attempt.send_bytes(chunk, i64(total))! |
| 222 | } |
| 223 | |
| 224 | // Check the range before appending even one byte to a resumable partial. |
| 225 | fn net_download_headers(req &http.Request, chunk []u8, _ u64) ! { |
| 226 | mut attempt := unsafe { &NetAttempt(req.user_ptr) } |
| 227 | if attempt.headers_checked { return } |
| 228 | attempt.headers << chunk |
| 229 | head := attempt.headers.bytestr() |
| 230 | end := head.index('\r\n\r\n') or { |
| 231 | if head.len > 65536 { return error('oversized HTTP response headers') } |
| 232 | return |
| 233 | } |
| 234 | if end > 65536 { return error('oversized HTTP response headers') } |
| 235 | attempt.headers_checked = true |
| 236 | if attempt.offset == 0 { return } |
| 237 | lines := head[..end].split('\r\n') |
| 238 | code := lines[0].all_after(' ').all_before(' ').int() |
| 239 | if code < 200 || code >= 300 { return } |
| 240 | if code == 206 { |
| 241 | for line in lines[1..] { |
| 242 | if line.all_before(':').to_lower() != 'content-range' { continue } |
| 243 | field := line.all_after(':').trim_space() |
| 244 | if !field.starts_with('bytes ${attempt.offset}-') { break } |
| 245 | bounds := field.all_after('-').split('/') |
| 246 | if bounds.len != 2 { break } |
| 247 | last := strconv.parse_int(bounds[0], 10, 64) or { break } |
| 248 | size := strconv.parse_int(bounds[1], 10, 64) or { break } |
| 249 | if size <= attempt.offset || last != size - 1 { break } |
| 250 | attempt.range_size = size - attempt.offset |
| 251 | return |
| 252 | } |
| 253 | } |
| 254 | attempt.status = .range_error |
| 255 | return error('server did not return the requested byte range') |
| 256 | } |
| 257 | |
| 258 | fn (mut attempt NetAttempt) copy_file(url urllib.URL) !TransferResult { |
| 259 | if url.host.to_lower() !in ['', 'localhost', '127.0.0.1'] || !url.path.starts_with('/') || url.path.contains('\x00') { |
| 260 | return error('invalid local file URL') |
| 261 | } |
| 262 | mut file := os.open(url.path)! |
| 263 | defer { file.close() } |
| 264 | mut st := C.stat{} |
| 265 | if C.fstat(file.fd, &st) != 0 { return os.last_error() } |
| 266 | if st.st_mode & 0o170000 != 0o100000 { return error('download source is not a regular file') } |
| 267 | size := i64(st.st_size) |
| 268 | mtime := i64(st.st_mtime) |
| 269 | if attempt.offset == 0 && attempt.mtime != 0 && mtime <= attempt.mtime { |
| 270 | return TransferResult{ unmodified: true, effective_url: attempt.url } |
| 271 | } |
| 272 | if attempt.offset > 0 && attempt.offset >= size { |
| 273 | return TransferResult{ status: .range_error } |
| 274 | } |
| 275 | file.seek(attempt.offset, .start)! |
| 276 | remaining := size - attempt.offset |
| 277 | mut buf := []u8{len: 65536} |
| 278 | for attempt.written < remaining { |
| 279 | n := file.read(mut buf)! |
| 280 | if n == 0 || n > remaining - attempt.written { |
| 281 | return error('local file changed during download') |
| 282 | } |
| 283 | attempt.send_bytes(buf[..n], remaining)! |
| 284 | } |
| 285 | return TransferResult{ bytes: attempt.written, expected: remaining, effective_url: attempt.url, remote_time: mtime } |
| 286 | } |
| 287 | |