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