]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/apr/network_io/unix/socket_util.c
Copy head (r256279) to stable/10 as part of the 10.0-RELEASE cycle.
[FreeBSD/stable/10.git] / contrib / apr / network_io / unix / socket_util.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "apr_network_io.h"
18 #include "apr_poll.h"
19
20 APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, int *atreadeof)
21 {
22     apr_pollfd_t pfds[1];
23     apr_status_t rv;
24     apr_int32_t  nfds;
25
26     /* The purpose here is to return APR_SUCCESS only in cases in
27      * which it can be unambiguously determined whether or not the
28      * socket will return EOF on next read.  In case of an unexpected
29      * error, return that. */
30
31     pfds[0].reqevents = APR_POLLIN;
32     pfds[0].desc_type = APR_POLL_SOCKET;
33     pfds[0].desc.s = sock;
34
35     do {
36         rv = apr_poll(&pfds[0], 1, &nfds, 0);
37     } while (APR_STATUS_IS_EINTR(rv));
38
39     if (APR_STATUS_IS_TIMEUP(rv)) {
40         /* Read buffer empty -> subsequent reads would block, so,
41          * definitely not at EOF. */
42         *atreadeof = 0;
43         return APR_SUCCESS;
44     }
45     else if (rv) {
46         /* Some other error -> unexpected error. */
47         return rv;
48     }
49     else if (nfds == 1 && pfds[0].rtnevents == APR_POLLIN) {
50         apr_sockaddr_t unused;
51         apr_size_t len = 1;
52         char buf;
53
54         /* The socket is readable - peek to see whether it returns EOF
55          * without consuming bytes from the socket buffer. */
56         rv = apr_socket_recvfrom(&unused, sock, MSG_PEEK, &buf, &len);
57         if (rv == APR_EOF) {
58             *atreadeof = 1;
59             return APR_SUCCESS;
60         }
61         else if (rv) {
62             /* Read error -> unexpected error. */
63             return rv;
64         }
65         else {
66             *atreadeof = 0;
67             return APR_SUCCESS;
68         }
69     }
70
71     /* Should not fall through here. */
72     return APR_EGENERAL;
73 }
74