1 /*
2 * Copyright (C) 2011 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 <cutils/sockets.h>
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/socket.h>
23 #include <sys/uio.h>
24 #include <sys/un.h>
25 #include <time.h>
26 #include <unistd.h>
27
28 #include "android_get_control_env.h"
29
socket_close(int sock)30 int socket_close(int sock) {
31 return close(sock);
32 }
33
socket_send_buffers(cutils_socket_t sock,const cutils_socket_buffer_t * buffers,size_t num_buffers)34 ssize_t socket_send_buffers(cutils_socket_t sock,
35 const cutils_socket_buffer_t* buffers,
36 size_t num_buffers) {
37 if (num_buffers > SOCKET_SEND_BUFFERS_MAX_BUFFERS) {
38 return -1;
39 }
40
41 iovec iovec_buffers[SOCKET_SEND_BUFFERS_MAX_BUFFERS];
42 for (size_t i = 0; i < num_buffers; ++i) {
43 // It's safe to cast away const here; iovec declares non-const
44 // void* because it's used for both send and receive, but since
45 // we're only sending, the data won't be modified.
46 iovec_buffers[i].iov_base = const_cast<void*>(buffers[i].data);
47 iovec_buffers[i].iov_len = buffers[i].length;
48 }
49
50 return writev(sock, iovec_buffers, num_buffers);
51 }
52
53 #if defined(__ANDROID__)
android_get_control_socket(const char * name)54 int android_get_control_socket(const char* name) {
55 int fd = __android_get_control_from_env(ANDROID_SOCKET_ENV_PREFIX, name);
56
57 if (fd < 0) return fd;
58
59 // Compare to UNIX domain socket name, must match!
60 struct sockaddr_un addr;
61 socklen_t addrlen = sizeof(addr);
62 int ret = getsockname(fd, (struct sockaddr*)&addr, &addrlen);
63 if (ret < 0) return -1;
64
65 constexpr char prefix[] = ANDROID_SOCKET_DIR "/";
66 constexpr size_t prefix_size = sizeof(prefix) - sizeof('\0');
67 if ((strncmp(addr.sun_path, prefix, prefix_size) == 0) &&
68 (strcmp(addr.sun_path + prefix_size, name) == 0)) {
69 // It is what we think it is
70 return fd;
71 }
72 return -1;
73 }
74 #else
android_get_control_socket(const char *)75 int android_get_control_socket(const char*) {
76 return -1;
77 }
78 #endif
79