1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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 #ifndef NETFD_H_
18 #define NETFD_H_
19 
20 #include <conscrypt/jniutil.h>
21 
22 /**
23  * Wraps access to the int inside a java.io.FileDescriptor, taking care of throwing exceptions.
24  */
25 class NetFd {
26  public:
27     NetFd(JNIEnv* env, jobject fileDescriptor)
28         : mEnv(env), mFileDescriptor(fileDescriptor), mFd(-1) {}
29 
30     bool isClosed() {
31         mFd = conscrypt::jniutil::jniGetFDFromFileDescriptor(mEnv, mFileDescriptor);
32         bool closed = (mFd == -1);
33         if (closed) {
34             conscrypt::jniutil::throwException(mEnv, "java/net/SocketException",
35                                                   "Socket closed");
36         }
37         return closed;
38     }
39 
40     int get() const {
41         return mFd;
42     }
43 
44  private:
45     JNIEnv* mEnv;
46     jobject mFileDescriptor;
47     int mFd;
48 
49     // Disallow copy and assignment.
50     NetFd(const NetFd&);
51     void operator=(const NetFd&);
52 };
53 
54 /**
55  * Used to retry syscalls that can return EINTR. This differs from TEMP_FAILURE_RETRY in that
56  * it also considers the case where the reason for failure is that another thread called
57  * Socket.close.
58  */
59 #define NET_FAILURE_RETRY(fd, exp)                     \
60     ({                                                 \
61         typeof(exp) _rc;                               \
62         do {                                           \
63             _rc = (exp);                               \
64             if (_rc == -1) {                           \
65                 if (fd.isClosed() || errno != EINTR) { \
66                     break;                             \
67                 }                                      \
68             }                                          \
69         } while (_rc == -1);                           \
70         _rc;                                           \
71     })
72 
73 #endif  // NETFD_H_
74