Skip to content

Commit 0600afa

Browse files
authored
Merge pull request #225 from krizex/CA-289145
CA-289145: Close socket if error occurs when connecting
2 parents cbe3ac2 + 65d985d commit 0600afa

File tree

2 files changed

+27
-14
lines changed

2 files changed

+27
-14
lines changed

lib/open_uri.ml

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,36 +15,43 @@
1515
*
1616
*)
1717

18+
open Xapi_stdext_pervasives.Pervasiveext
19+
1820
let handle_socket f s =
1921
try
20-
let result = f s in
21-
Unix.close s;
22-
result
22+
f s
2323
with e ->
2424
Backtrace.is_important e;
25-
Unix.close s;
2625
raise e
2726

2827
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 () ->
3232
Unix.connect s sockaddr;
3333
handle_socket f s
34+
) (fun () ->
35+
Unix.close s
36+
)
3437

3538
let with_open_uri uri f =
3639
match Uri.scheme uri with
3740
| Some "http" ->
3841
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))
4245
end
4346
| Some "file" ->
4447
let filename = Uri.path_and_query uri in
4548
let sockaddr = Unix.ADDR_UNIX filename in
4649
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+
)
4956
| Some x -> failwith (Printf.sprintf "Unsupported URI scheme: %s" x)
5057
| None -> failwith (Printf.sprintf "Failed to parse URI: %s" (Uri.to_string uri))

lib/posix_channel.ml

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,8 +190,14 @@ let receive protocols =
190190
| V4V_proxy(_, _) -> assert false (* weight is 0 above *)
191191
| TCP_proxy(ip, port) ->
192192
let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
193-
Unix.connect s (Unix.ADDR_INET(Unix.inet_addr_of_string ip, port));
194-
s
193+
begin
194+
try
195+
Unix.connect s (Unix.ADDR_INET(Unix.inet_addr_of_string ip, port));
196+
s
197+
with e ->
198+
Unix.close s;
199+
raise e
200+
end
195201
| Unix_sendmsg(_, path, token) ->
196202
let s = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in
197203
finally

0 commit comments

Comments
 (0)