1 /*
2  * Copyright (C) 2016 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 #include <stdio.h>
18 #include <stdlib.h>
19 #include <sys/socket.h>
20 #include <sys/types.h>
21 #include <sys/un.h>
22 #include <time.h>
23 
24 #include <cutils/sockets.h>
25 #include <gtest/gtest.h>
26 
27 #ifndef SOCK_NONBLOCK
28 #define SOCK_NONBLOCK 0
29 #endif
30 
31 #ifndef SOCK_CLOEXEC
32 #define SOCK_CLOEXEC 0
33 #endif
34 
TEST(SocketsTest,android_get_control_socket)35 TEST(SocketsTest, android_get_control_socket) {
36     static const char key[] = ANDROID_SOCKET_ENV_PREFIX "SocketsTest_android_get_control_socket";
37     static const char* name = key + strlen(ANDROID_SOCKET_ENV_PREFIX);
38 
39     EXPECT_EQ(unsetenv(key), 0);
40     EXPECT_EQ(android_get_control_socket(name), -1);
41 
42     int fd;
43     ASSERT_GE(fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0), 0);
44 #ifdef F_GETFL
45     int flags;
46     ASSERT_GE(flags = fcntl(fd, F_GETFL), 0);
47     ASSERT_GE(fcntl(fd, F_SETFL, flags | O_NONBLOCK), 0);
48 #endif
49     EXPECT_EQ(android_get_control_socket(name), -1);
50 
51     struct sockaddr_un addr;
52     memset(&addr, 0, sizeof(addr));
53     addr.sun_family = AF_UNIX;
54     snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s", name);
55     unlink(addr.sun_path);
56 
57     EXPECT_EQ(bind(fd, (struct sockaddr*)&addr, sizeof(addr)), 0);
58     EXPECT_EQ(android_get_control_socket(name), -1);
59 
60     char val[32];
61     snprintf(val, sizeof(val), "%d", fd);
62     EXPECT_EQ(setenv(key, val, true), 0);
63 
64     EXPECT_EQ(android_get_control_socket(name), fd);
65     socket_close(fd);
66     EXPECT_EQ(android_get_control_socket(name), -1);
67     EXPECT_EQ(unlink(addr.sun_path), 0);
68     EXPECT_EQ(android_get_control_socket(name), -1);
69     EXPECT_EQ(unsetenv(key), 0);
70     EXPECT_EQ(android_get_control_socket(name), -1);
71 }
72