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