• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <sys/uio.h>
20 
21 #include <log/log.h>
22 
23 #if defined(__ANDROID__)
24 /* For the socket trust (credentials) check */
25 #include <private/android_filesystem_config.h>
26 #define __android_unused
27 #else
28 #define __android_unused __attribute__((__unused__))
29 #endif
30 
socket_peer_is_trusted(int fd __android_unused)31 bool socket_peer_is_trusted(int fd __android_unused) {
32 #if defined(__ANDROID__)
33     ucred cr;
34     socklen_t len = sizeof(cr);
35     int n = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
36 
37     if (n != 0) {
38         ALOGE("could not get socket credentials: %s\n", strerror(errno));
39         return false;
40     }
41 
42     if ((cr.uid != AID_ROOT) && (cr.uid != AID_SHELL)) {
43         ALOGE("untrusted userid on other end of socket: userid %d\n", cr.uid);
44         return false;
45     }
46 #endif
47 
48     return true;
49 }
50 
socket_close(int sock)51 int socket_close(int sock) {
52     return close(sock);
53 }
54 
socket_set_receive_timeout(cutils_socket_t sock,int timeout_ms)55 int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms) {
56     timeval tv;
57     tv.tv_sec = timeout_ms / 1000;
58     tv.tv_usec = (timeout_ms % 1000) * 1000;
59     return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
60 }
61 
socket_send_buffers(cutils_socket_t sock,const cutils_socket_buffer_t * buffers,size_t num_buffers)62 ssize_t socket_send_buffers(cutils_socket_t sock,
63                             const cutils_socket_buffer_t* buffers,
64                             size_t num_buffers) {
65     if (num_buffers > SOCKET_SEND_BUFFERS_MAX_BUFFERS) {
66         return -1;
67     }
68 
69     iovec iovec_buffers[SOCKET_SEND_BUFFERS_MAX_BUFFERS];
70     for (size_t i = 0; i < num_buffers; ++i) {
71         // It's safe to cast away const here; iovec declares non-const
72         // void* because it's used for both send and receive, but since
73         // we're only sending, the data won't be modified.
74         iovec_buffers[i].iov_base = const_cast<void*>(buffers[i].data);
75         iovec_buffers[i].iov_len = buffers[i].length;
76     }
77 
78     return writev(sock, iovec_buffers, num_buffers);
79 }
80