From 07750492dd8fbd92ac7836c6216bac677d5ea3cf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?David=20B=C3=BChler?= <david.buhler@cea.fr>
Date: Thu, 31 Mar 2022 11:11:23 +0200
Subject: [PATCH] [server] Improves the stopping condition of functions
 [send_bytes].

---
 src/plugins/server/server_socket.ml | 64 ++++++++++++++---------------
 1 file changed, 31 insertions(+), 33 deletions(-)

diff --git a/src/plugins/server/server_socket.ml b/src/plugins/server/server_socket.ml
index 43a0f34e289..1ad5262ccea 100644
--- a/src/plugins/server/server_socket.ml
+++ b/src/plugins/server/server_socket.ml
@@ -67,43 +67,41 @@ type channel = {
 }
 
 let read_bytes { sock ; rcv ; brcv } =
-  begin
-    (* rcv buffer is only used locally *)
-    let s = Bytes.length rcv in
-    let rec scan p =
-      (* try to fill RCV buffer *)
-      if p < s then
-        let n =
-          try Unix.read sock rcv p (s-p)
-          with Unix.Unix_error((EAGAIN|EWOULDBLOCK),_,_) -> 0
-        in if n > 0 then scan (p+n) else p
-      else p
+  (* rcv buffer is only used locally *)
+  let s = Bytes.length rcv in
+  let rec scan p =
+    (* try to fill RCV buffer *)
+    let n =
+      try Unix.read sock rcv p (s-p)
+      with Unix.Unix_error((EAGAIN|EWOULDBLOCK),_,_) -> 0
     in
-    let n = scan 0 in
-    if n > 0 then Buffer.add_subbytes brcv rcv 0 n
-  end
+    let p = p + n in
+    if n > 0 && p < s then scan p else p
+  in
+  let n = scan 0 in
+  if n > 0 then Buffer.add_subbytes brcv rcv 0 n
 
 let send_bytes { sock ; snd ; bsnd } =
-  begin
-    (* snd buffer is only used locally *)
-    let n = Buffer.length bsnd in
-    if n > 0 then
-      let s = Bytes.length snd in
-      let rec send p =
-        (* try to flush BSND buffer *)
-        let w = min (n-p) s in
-        Buffer.blit bsnd p snd 0 w ;
-        let r =
-          try Unix.single_write sock snd 0 w
-          with Unix.Unix_error((EAGAIN|EWOULDBLOCK),_,_) -> 0
-        in if r > 0 then send (p+r) else p
+  (* snd buffer is only used locally *)
+  let n = Buffer.length bsnd in
+  if n > 0 then
+    let s = Bytes.length snd in
+    let rec send p =
+      (* try to flush BSND buffer *)
+      let w = min (n-p) s in
+      Buffer.blit bsnd p snd 0 w ;
+      let r =
+        try Unix.single_write sock snd 0 w
+        with Unix.Unix_error((EAGAIN|EWOULDBLOCK),_,_) -> 0
       in
-      let p = send 0 in
-      if p > 0 then
-        let tail = Buffer.sub bsnd p (n-p) in
-        Buffer.reset bsnd ;
-        Buffer.add_string bsnd tail
-  end
+      let p = p + r in
+      if r > 0 && p < n then send p else p
+    in
+    let p = send 0 in
+    if p > 0 then
+      let tail = Buffer.sub bsnd p (n-p) in
+      Buffer.reset bsnd ;
+      Buffer.add_string bsnd tail
 
 (* -------------------------------------------------------------------------- *)
 (* --- Data Chunks Encoding                                               --- *)
-- 
GitLab