1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 
23 #include "curl_setup.h"
24 
25 #ifdef HAVE_SYS_IOCTL_H
26 #include <sys/ioctl.h>
27 #endif
28 #ifdef HAVE_FCNTL_H
29 #include <fcntl.h>
30 #endif
31 
32 #if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
33 #include <sys/filio.h>
34 #endif
35 #ifdef __VMS
36 #include <in.h>
37 #include <inet.h>
38 #endif
39 
40 #include "nonblock.h"
41 
42 /*
43  * curlx_nonblock() set the given socket to either blocking or non-blocking
44  * mode based on the 'nonblock' boolean argument. This function is highly
45  * portable.
46  */
curlx_nonblock(curl_socket_t sockfd,int nonblock)47 int curlx_nonblock(curl_socket_t sockfd,    /* operate on this */
48                    int nonblock   /* TRUE or FALSE */)
49 {
50 #if defined(HAVE_FCNTL_O_NONBLOCK)
51   /* most recent unix versions */
52   int flags;
53   flags = sfcntl(sockfd, F_GETFL, 0);
54   if(nonblock)
55     return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
56   return sfcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
57 
58 #elif defined(HAVE_IOCTL_FIONBIO)
59 
60   /* older unix versions */
61   int flags = nonblock ? 1 : 0;
62   return ioctl(sockfd, FIONBIO, &flags);
63 
64 #elif defined(HAVE_IOCTLSOCKET_FIONBIO)
65 
66   /* Windows */
67   unsigned long flags = nonblock ? 1UL : 0UL;
68   return ioctlsocket(sockfd, FIONBIO, &flags);
69 
70 #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
71 
72   /* Amiga */
73   long flags = nonblock ? 1L : 0L;
74   return IoctlSocket(sockfd, FIONBIO, (char *)&flags);
75 
76 #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
77 
78   /* BeOS */
79   long b = nonblock ? 1L : 0L;
80   return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
81 
82 #else
83 #  error "no non-blocking method was found/used/set"
84 #endif
85 }
86