1 /*
2  * Copyright 2006 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 #pragma once
18 
19 #include <stdbool.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/socket.h>
24 
25 #include <cerrno>
26 
27 #define ANDROID_SOCKET_ENV_PREFIX "ANDROID_SOCKET_"
28 #define ANDROID_SOCKET_DIR "/dev/socket"
29 
30 /*
31  * osi_android_get_control_socket - simple helper function to get the file
32  * descriptor of our init-managed Unix domain socket. `name' is the name of the
33  * socket, as given in init.rc. Returns -1 on error.
34  *
35  * This is inline and not in libcutils proper because we want to use this in
36  * third-party daemons with minimal modification.
37  */
osi_android_get_control_socket(const char * name)38 static inline int osi_android_get_control_socket(const char* name) {
39   char key[64];
40   snprintf(key, sizeof(key), ANDROID_SOCKET_ENV_PREFIX "%s", name);
41 
42   const char* val = getenv(key);
43   if (!val) {
44     return -1;
45   }
46 
47   errno = 0;
48   int fd = strtol(val, NULL, 10);
49   if (errno) {
50     return -1;
51   }
52 
53   return fd;
54 }
55 
56 /*
57  * See also android.os.LocalSocketAddress.Namespace
58  */
59 // Linux "abstract" (non-filesystem) namespace
60 #define ANDROID_SOCKET_NAMESPACE_ABSTRACT 0
61 // Android "reserved" (/dev/socket) namespace
62 #define ANDROID_SOCKET_NAMESPACE_RESERVED 1
63 // Normal filesystem namespace
64 #define ANDROID_SOCKET_NAMESPACE_FILESYSTEM 2
65 
66 int osi_socket_local_server(const char* name, int namespaceId, int type);
67 int osi_socket_local_server_bind(int s, const char* name, int namespaceId);
68 int osi_socket_local_client_connect(int fd, const char* name, int namespaceId,
69                                     int type);
70 int osi_socket_local_client(const char* name, int namespaceId, int type);
71