|
15 | 15 | * |
16 | 16 | *) |
17 | 17 |
|
| 18 | +open Xapi_stdext_pervasives.Pervasiveext |
| 19 | + |
18 | 20 | let handle_socket f s = |
19 | 21 | try |
20 | | - let result = f s in |
21 | | - Unix.close s; |
22 | | - result |
| 22 | + f s |
23 | 23 | with e -> |
24 | 24 | Backtrace.is_important e; |
25 | | - Unix.close s; |
26 | 25 | raise e |
27 | 26 |
|
28 | 27 | let open_tcp f host port = |
29 | | - let host_entry = Unix.gethostbyname host in |
30 | | - let sockaddr = Unix.ADDR_INET(host_entry.Unix.h_addr_list.(0), port) in |
31 | | - let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in |
| 28 | + let host_entry = Unix.gethostbyname host in |
| 29 | + let sockaddr = Unix.ADDR_INET(host_entry.Unix.h_addr_list.(0), port) in |
| 30 | + let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in |
| 31 | + finally (fun () -> |
32 | 32 | Unix.connect s sockaddr; |
33 | 33 | handle_socket f s |
| 34 | + ) (fun () -> |
| 35 | + Unix.close s |
| 36 | + ) |
34 | 37 |
|
35 | 38 | let with_open_uri uri f = |
36 | 39 | match Uri.scheme uri with |
37 | 40 | | Some "http" -> |
38 | 41 | begin match Uri.host uri, Uri.port uri with |
39 | | - | Some host, Some port -> open_tcp f host port |
40 | | - | Some host, None -> open_tcp f host 80 |
41 | | - | _, _ -> failwith (Printf.sprintf "Failed to parse host and port from URI: %s" (Uri.to_string uri)) |
| 42 | + | Some host, Some port -> open_tcp f host port |
| 43 | + | Some host, None -> open_tcp f host 80 |
| 44 | + | _, _ -> failwith (Printf.sprintf "Failed to parse host and port from URI: %s" (Uri.to_string uri)) |
42 | 45 | end |
43 | 46 | | Some "file" -> |
44 | 47 | let filename = Uri.path_and_query uri in |
45 | 48 | let sockaddr = Unix.ADDR_UNIX filename in |
46 | 49 | let s = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in |
47 | | - Unix.connect s sockaddr; |
48 | | - handle_socket f s |
| 50 | + finally (fun () -> |
| 51 | + Unix.connect s sockaddr; |
| 52 | + handle_socket f s |
| 53 | + ) (fun () -> |
| 54 | + Unix.close s |
| 55 | + ) |
49 | 56 | | Some x -> failwith (Printf.sprintf "Unsupported URI scheme: %s" x) |
50 | 57 | | None -> failwith (Printf.sprintf "Failed to parse URI: %s" (Uri.to_string uri)) |
0 commit comments