Source file opamDownload.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
open OpamTypes
open OpamProcess.Job.Op
let log fmt = OpamConsole.log "CURL" fmt
exception Download_fail of string option * string
let fail (s,l) = raise (Download_fail (s,l))
let user_agent =
CString (Printf.sprintf "opam/%s" (OpamVersion.(to_string current)))
let curl_args =
let main_args = [
CString "--retry", None; CIdent "retry", None;
CString "--retry-delay", None; CString "2", None;
CString "--compressed",
Some (FIdent (OpamFilter.ident_of_string "compress"));
CString "--user-agent", None; user_agent, None;
CString "-L", None;
CString "-o", None; CIdent "out", None;
CString "--", None;
CIdent "url", None;
] in
fun ~with_mitigation ->
if with_mitigation then
(CString "--fail", None) :: main_args
else
(CString "--write-out", None) ::
(CString "%%{http_code}\\n", None) ::
main_args
let wget_args = [
CString "--header=Accept: */*", None;
CString "-t", None; CIdent "retry", None;
CString "-O", None; CIdent "out", None;
CString "-U", None; user_agent, None;
CString "--", None;
CIdent "url", None;
]
let fetch_args = [
CString "-o", None; CIdent "out", None;
CString "--user-agent", None; user_agent, None;
CString "--", None;
CIdent "url", None;
]
let ftp_args = [
CString "-o", None; CIdent "out", None;
CString "-U", None; user_agent, None;
CString "--", None;
CIdent "url", None;
]
let download_args ~url ~out ~retry ?(with_curl_mitigation=false)
?checksum ~compress () =
let cmd, _ = Lazy.force OpamRepositoryConfig.(!r.download_tool) in
let cmd =
match cmd with
| [(CIdent "wget"), _] -> cmd @ wget_args
| [(CIdent "fetch"), _] -> cmd @ fetch_args
| [(CIdent "ftp"), _] -> cmd @ ftp_args
| [_] -> cmd @ curl_args ~with_mitigation:with_curl_mitigation
| _ -> cmd
in
OpamFilter.single_command (fun v ->
if not (OpamVariable.Full.is_global v) then None else
match OpamVariable.to_string (OpamVariable.Full.variable v) with
| ("curl" | "wget" | "fetch" | "ftp") as dl_tool-> Some (S dl_tool)
| "url" -> Some (S (OpamUrl.to_string url))
| "out" -> Some (S out)
| "retry" -> Some (S (string_of_int retry))
| "compress" -> Some (B compress)
| "opam-version" -> Some (S OpamVersion.(to_string current))
| "checksum" ->
Option.map (fun c -> S OpamHash.(to_string c)) checksum
| "hashalgo" ->
Option.map (fun c -> S OpamHash.(string_of_kind (kind c)))
checksum
| "hashpath" ->
Option.map
(fun c -> S (String.concat Filename.dir_sep OpamHash.(to_path c)))
checksum
| "hashvalue" ->
Option.map (fun c -> S OpamHash.(contents c)) checksum
| _ -> None)
cmd
let download_command_t ~with_curl_mitigation ~compress ?checksum ~url ~dst c =
let cmd, args =
match
download_args
~url
~out:dst
~retry:OpamRepositoryConfig.(!r.retries)
~with_curl_mitigation
?checksum
~compress
()
with
| cmd::args -> cmd, args
| [] ->
OpamConsole.error_and_exit `Configuration_error
"Empty custom download command"
in
let stdout = OpamSystem.temp_file ~auto_clean:false "dl" in
OpamProcess.Job.finally (fun () -> OpamSystem.remove_file stdout) @@ fun () ->
OpamSystem.make_command ~allow_stdin:false ~stdout cmd args @@> c
let tool_return redownload_command url ret =
match Lazy.force OpamRepositoryConfig.(!r.download_tool) with
| _, `Default ->
if OpamProcess.is_failure ret then
Done (`fail (Some "Download command failed",
Printf.sprintf "Download command failed: %s"
(OpamProcess.result_summary ret)))
else Done `ok
| _, `Curl ->
match ret with
| { r_code = 0 ; r_stdout = []; _ } ->
Done (`fail (Some "curl empty response",
Printf.sprintf "curl: empty response while downloading %s"
(OpamUrl.to_string url)))
| { r_code = 0 ; r_stdout = (_::_ as l); _ } ->
let code = List.hd (List.rev l) in
(try
let num = int_of_string code in
if num >= 400 then
Done (`http_error num)
else Done `ok
with Failure _ ->
Done (`fail (Some ("curl error " ^ code),
Printf.sprintf "curl: error %s while downloading %s"
code (OpamUrl.to_string url))))
| { r_code = 43; _ } ->
log "Attempting to mitigate curl/curl#13845";
(redownload_command ~with_curl_mitigation:true @@ function ret ->
if OpamProcess.is_failure ret then
if ret.r_code = 22 then
Done (`fail (Some "curl failed owing to a server-side issue",
Printf.sprintf "curl failed with server-side error: %s"
(OpamProcess.result_summary ret)))
else
Done (`fail (Some "curl failed",
Printf.sprintf "curl failed: %s"
(OpamProcess.result_summary ret)))
else Done `ok)
| _ ->
Done (`fail (Some "curl failed",
Printf.sprintf "curl failed: %s"
(OpamProcess.result_summary ret)))
let download_command_http_error ~compress ?checksum ~url ~dst () =
let download_command = download_command_t ~compress ?checksum ~url ~dst in
download_command ~with_curl_mitigation:false
@@ tool_return download_command url
let download_command ~compress ?checksum ~url ~dst () =
download_command_http_error ~compress ?checksum ~url ~dst ()
@@| function
| `ok -> ()
| `http_error code ->
fail (Some ("HTTP error code " ^ string_of_int code),
Printf.sprintf "code %d while downloading %s"
code (OpamUrl.to_string url))
| `fail (s,l) -> fail (s,l)
let really_download
?(quiet=false) ~overwrite ?(compress=false) ?checksum ?(validate=true)
~url ~dst () =
assert (url.OpamUrl.backend = `http);
let tmp_dst = dst ^ ".part" in
if Sys.file_exists tmp_dst then OpamSystem.remove tmp_dst;
OpamProcess.Job.catch
(function
| Failure s as e ->
OpamSystem.remove tmp_dst;
if not quiet then OpamConsole.error "%s" s;
raise e
| e ->
OpamSystem.remove tmp_dst;
OpamStd.Exn.fatal e;
log "Could not download file at %s." (OpamUrl.to_string url);
raise e)
@@ fun () ->
download_command ~compress ?checksum ~url ~dst:tmp_dst ()
@@+ fun () ->
if not (Sys.file_exists tmp_dst) then
fail (Some "Downloaded file not found",
"Download command succeeded, but resulting file not found")
else if Sys.file_exists dst && not overwrite then
OpamSystem.internal_error "The downloaded file will overwrite %s." dst;
if validate &&
OpamRepositoryConfig.(!r.force_checksums <> Some false) then
Option.iter (fun cksum ->
if not (OpamHash.check_file tmp_dst cksum) then
fail (Some "Bad checksum",
Printf.sprintf "Bad checksum, expected %s"
(OpamHash.to_string cksum)))
checksum;
OpamSystem.mv tmp_dst dst;
Done ()
let download_as ?quiet ?validate ~overwrite ?compress ?checksum url dst =
match OpamUrl.local_file url with
| Some src ->
if src = dst then Done () else
(if OpamFilename.exists dst then
if overwrite then OpamFilename.remove dst else
OpamSystem.internal_error "The downloaded file will overwrite %s."
(OpamFilename.to_string dst);
OpamFilename.copy ~src ~dst;
Done ())
| None ->
OpamFilename.(mkdir (dirname dst));
really_download ?quiet ~overwrite ?compress ?checksum ?validate
~url
~dst:(OpamFilename.to_string dst)
()
let download ?quiet ?validate ~overwrite ?compress ?checksum url dstdir =
let base =
let base = OpamUrl.basename url in
if Sys.win32 then
let f c =
if OpamStd.Sys.is_valid_basename_char c then c else '_'
in
String.map f base
else
base
in
let dst =
OpamFilename.(create dstdir (Base.of_string base))
in
download_as ?quiet ?validate ~overwrite ?compress ?checksum url dst @@|
fun () -> dst
(** Stdout output retrieval and post requests management *)
let get_output ~post ?(args=[]) url =
let cmd_args =
download_args ~url ~out:"-" ~retry:OpamRepositoryConfig.(!r.retries)
~compress:false ()
@ args
in
let cmd_args =
if post then
match cmd_args with
| ("curl" as cmd)::args -> Some (cmd :: ["--request"; "POST"] @ args)
| ("wget" as cmd)::args -> Some (cmd :: ["--method"; "POST"] @ args)
| _ -> None
else Some cmd_args
in
Done (Option.map
(OpamSystem.read_command_output ~ignore_stderr:true) cmd_args)
module SWHID = struct
(** SWHID retrieval functions *)
let log fmt = OpamConsole.log "CURL(SWHID)" fmt
let instance = OpamUrl.of_string "https://archive.softwareheritage.org"
let full_url middle hash =
OpamUrl.Op.(instance / "api" / "1" / middle / hash / "")
let vault_url kind hash =
full_url ("vault/" ^ kind) ("swh:1:dir:" ^ hash)
let fallback_err fmt = Printf.sprintf ("SWH fallback: "^^fmt)
let get_output ?(post=false) url =
get_output ~post url @@| function
| Some out -> out
| None ->
assert false
let get_value key s =
match OpamJson.of_string s with
| Some (`O elems) ->
(match OpamStd.List.assoc_opt String.equal key elems with
| Some (`String v) -> Some v
| _ -> None)
| _ -> None
let check_liveness () =
OpamProcess.Job.catch (fun _ -> Done false)
@@ fun () ->
get_output ~post:false OpamUrl.Op.(instance / "api" / "1" / "ping" / "")
@@| function
| pong::_ ->
OpamCompat.String.starts_with ~prefix:"\"pong\"" pong
| _ -> false
let parse_err json =
match get_value "exception" json with
| Some "NotFoundExc" ->
(match get_value "reason" json with
| Some reason ->
if OpamCompat.String.ends_with ~suffix:"was never requested." reason then
`Uncooked
else if OpamCompat.String.ends_with ~suffix:"not found." reason then
`Not_found
else `Error
| None -> `Error)
| Some "Resource not found" -> `Not_found
| Some _ | None -> `Error
let is_it_cooked url =
OpamSystem.with_tmp_file @@ fun dst ->
let download_cmd ~with_curl_mitigation return =
let cmd, args =
match
download_args ~url ~out:dst
~with_curl_mitigation
~retry:OpamRepositoryConfig.(!r.retries)
~compress:false ()
with
| cmd::args -> cmd, args
| _ -> assert false
in
let stdout = OpamSystem.temp_file ~auto_clean:false "dl" in
OpamProcess.Job.finally (fun () -> OpamSystem.remove_file stdout)
@@ fun () ->
OpamSystem.make_command ~allow_stdin:false ~stdout cmd args
@@> return
in
(download_cmd ~with_curl_mitigation:false
@@ tool_return download_cmd url)
@@| fun status ->
let read_last_line file =
let out = String.trim (OpamSystem.read file) in
match String.rindex_opt out '\n' with
| Some b ->
String.sub out (b + 1) (String.length out - b - 1)
| None -> out
in
let status =
match status with
| `ok ->
let json = read_last_line dst in
if String.equal json "" then `Error else `Cooked json
| `http_error 404 ->
let json = read_last_line dst in
parse_err json
| `http_error _ | `fail _ -> `Error
in
status
let read_flat_out json =
let status = get_value "status" json in
let fetch_url = get_value "fetch_url" json in
match status, fetch_url with
| None, _ | _, None ->
(match parse_err json with
| `Not_found -> `Not_found
| `Error | `Uncooked -> `Malformed)
| Some status, Some fetch_url ->
match status with
| "done" -> `Done (OpamUrl.of_string fetch_url)
| "pending" -> `Pending
| "new" -> `New
| "failed" -> `Failed
| _ -> `Unknown
let get_url ?(max_tries=6) swhid =
let request_cooking ?(post=false) url =
get_output ~post url @@| fun out -> String.concat "" out
in
let hash = OpamSWHID.hash swhid in
let url = vault_url "flat" hash in
let rec loop attempt json =
match read_flat_out json with
| `Done fetch_url -> Done (Result fetch_url)
| `Pending | `New ->
log "%s is cooking (%d/%d)..."
(OpamSWHID.to_string swhid) attempt max_tries;
if (attempt : int) >= (max_tries : int) then
Done (Not_available
(Some (fallback_err "attempt"),
fallback_err "%d attempts tried; aborting" max_tries))
else
(Unix.sleep 10;
request_cooking ~post:false url
@@+ loop (attempt + 1))
| `Malformed ->
Done (Not_available (None, fallback_err "Malformed request answer"))
| `Failed | `Unknown | `Not_found ->
Done (Not_available (None, fallback_err "Unknown swhid"))
in
let retrieve_url json = loop 1 json in
is_it_cooked url
@@+ function
| `Error -> Done (Not_available (None, fallback_err "Request error"))
| `Not_found -> Done (Not_available (None, fallback_err "Unknown swhid"))
| `Cooked json ->
log "%s is cooked or cooking, requesting url" (OpamSWHID.to_string swhid);
retrieve_url json
| `Uncooked ->
log "%s is uncooked, request cooking" (OpamSWHID.to_string swhid);
request_cooking ~post:true url
@@+ retrieve_url
let archive_fallback ?max_tries urlf dirnames =
match OpamFile.URL.swhid urlf with
| None -> Done (Result None)
| Some swhid ->
match Lazy.force OpamRepositoryConfig.(!r.download_tool) with
| _, `Curl ->
check_liveness () @@+ fun alive ->
if alive then
(log "API is working";
if OpamConsole.confirm ~default:false
"Source %s is not available. Do you want to try to retrieve it \
from Software Heritage cache (https://www.softwareheritage.org)? \
It may take few minutes."
(OpamConsole.colorise `underline
(OpamUrl.to_string (OpamFile.URL.url urlf))) then
(log "SWH fallback for %s with %s"
(OpamStd.Format.pretty_list
(List.map (fun (nv,_,_) -> nv) dirnames))
(OpamSWHID.to_string swhid);
get_url ?max_tries swhid @@+ function
| Not_available _ as error -> Done error
| Up_to_date _ -> assert false
| Result url ->
log "Downloading %s for %s" (OpamSWHID.to_string swhid)
(OpamStd.Format.pretty_list
(List.map (fun (nv,_,_) -> nv) dirnames));
let hash = OpamSWHID.hash swhid in
OpamFilename.with_tmp_dir_job @@ fun dir ->
let archive = OpamFilename.Op.(dir // hash) in
download_as ~overwrite:true url archive @@+ fun () ->
let sources = OpamFilename.Op.(dir / "src") in
OpamFilename.extract_job archive sources @@| function
| Some e ->
Not_available (
Some (fallback_err "archive extraction failure"),
fallback_err "archive extraction failure %s"
(match e with
| Failure s -> s
| OpamSystem.Process_error pe ->
OpamProcess.string_of_result pe
| e -> Printexc.to_string e))
| None ->
(match OpamSWHID.compute sources with
| None ->
Not_available (
Some (fallback_err "can't check archive validity"),
fallback_err
"error on swhid computation, can't check its validity")
| Some computed ->
if String.equal computed hash then
(List.iter (fun (_nv, dst, _sp) ->
OpamFilename.copy_dir ~src:sources ~dst)
dirnames;
Result (Some "SWH fallback"))
else
Not_available (
Some (fallback_err "archive not valid"),
fallback_err
"archive corrupted, opam file swhid %S vs computed %S"
hash computed)))
else
Done (Not_available
(Some (fallback_err "skip retrieval"),
fallback_err "retrieval refused by user")))
else
Done (Not_available
(Some (fallback_err "unreachable"),
fallback_err "network failure or API down"))
| _ ->
Done (Not_available
(Some (fallback_err "no retrieval"),
fallback_err "curl is required for Software Heritage fallback"))
end