]> git.ipfire.org Git - thirdparty/curl.git/commitdiff
cf-socket: optimize curlx_nonblock() and check its return error
authorAndy Pan <i@andypan.me>
Thu, 13 Jun 2024 13:28:01 +0000 (21:28 +0800)
committerDaniel Stenberg <daniel@haxx.se>
Sat, 22 Jun 2024 09:56:37 +0000 (11:56 +0200)
Reviewed-by: Stefan Eissing
Closes #13942

lib/cf-socket.c
lib/nonblock.c

index f608fbe0bad2f70e2a2ca54ef5878655ab5896b1..9554b4904aa4f1e445d47cc3a28263ae69da8e4c 100644 (file)
@@ -1234,12 +1234,25 @@ static CURLcode cf_socket_open(struct Curl_cfilter *cf,
 #endif
 
 #ifndef SOCK_NONBLOCK
-  /* set socket non-blocking */
-  (void)curlx_nonblock(ctx->sock, TRUE);
+  /* Set socket non-blocking, must be a non-blocking socket for
+   * a non-blocking connect. */
+  error = curlx_nonblock(ctx->sock, TRUE);
+  if(error < 0) {
+    result = CURLE_UNSUPPORTED_PROTOCOL;
+    ctx->error = SOCKERRNO;
+    goto out;
+  }
 #else
-  if(data->set.fopensocket)
-    /* set socket non-blocking */
-    (void)curlx_nonblock(ctx->sock, TRUE);
+  if(data->set.fopensocket) {
+    /* Set socket non-blocking, must be a non-blocking socket for
+     * a non-blocking connect. */
+    error = curlx_nonblock(ctx->sock, TRUE);
+    if(error < 0) {
+      result = CURLE_UNSUPPORTED_PROTOCOL;
+      ctx->error = SOCKERRNO;
+      goto out;
+    }
+  }
 #endif
   ctx->sock_connected = (ctx->addr.socktype != SOCK_DGRAM);
 out:
index 4902fce1118a5579b641fb372e9009ca8fdcdfe0..5e7db68f03fb29f9ae9a31ff73524b6f23348167 100644 (file)
@@ -50,9 +50,18 @@ int curlx_nonblock(curl_socket_t sockfd,    /* operate on this */
   /* most recent unix versions */
   int flags;
   flags = sfcntl(sockfd, F_GETFL, 0);
+  if(flags < 0)
+    return -1;
+  /* Check if the current file status flags have already satisfied
+   * the request, if so, it's no need to call fcntl() to replicate it.
+   */
+  if(!!(flags & O_NONBLOCK) == !!nonblock)
+    return 0;
   if(nonblock)
-    return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
-  return sfcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
+    flags |= O_NONBLOCK;
+  else
+    flags &= ~O_NONBLOCK;
+  return sfcntl(sockfd, F_SETFL, flags);
 
 #elif defined(HAVE_IOCTL_FIONBIO)