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 #include <netinet/in.h>
18 #include <stddef.h>
19 #include <stdlib.h>
20 #include <sys/select.h>
21 #include <sys/socket.h>
22 #include <sys/types.h>
23 #include <sys/un.h>
24 #include <unistd.h>
25
26 #include "osi/include/socket_utils/socket_local.h"
27 #include "osi/include/socket_utils/sockets.h"
28
29 #define LISTEN_BACKLOG 4
30
31 /* Only the bottom bits are really the socket type; there are flags too. */
32 #define SOCK_TYPE_MASK 0xf
33
34 /**
35 * Binds a pre-created socket(AF_LOCAL) 's' to 'name'
36 * returns 's' on success, -1 on fail
37 *
38 * Does not call listen()
39 */
osi_socket_local_server_bind(int s,const char * name,int namespaceId)40 int osi_socket_local_server_bind(int s, const char* name, int namespaceId) {
41 struct sockaddr_un addr;
42 socklen_t alen;
43 int n;
44 int err;
45
46 err = osi_socket_make_sockaddr_un(name, namespaceId, &addr, &alen);
47
48 if (err < 0) {
49 return -1;
50 }
51
52 /* basically: if this is a filesystem path, unlink first */
53 #if !defined(__linux__)
54 if (1) {
55 #else
56 if (namespaceId == ANDROID_SOCKET_NAMESPACE_RESERVED ||
57 namespaceId == ANDROID_SOCKET_NAMESPACE_FILESYSTEM) {
58 #endif
59 /*ignore ENOENT*/
60 unlink(addr.sun_path);
61 }
62
63 n = 1;
64 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));
65
66 if (bind(s, (struct sockaddr*)&addr, alen) < 0) {
67 return -1;
68 }
69
70 return s;
71 }
72
73 /** Open a server-side UNIX domain datagram socket in the Linux non-filesystem
74 * namespace
75 *
76 * Returns fd on success, -1 on fail
77 */
78 int osi_socket_local_server(const char* name, int namespaceId, int type) {
79 int err;
80 int s;
81
82 s = socket(AF_LOCAL, type, 0);
83 if (s < 0) return -1;
84
85 err = osi_socket_local_server_bind(s, name, namespaceId);
86
87 if (err < 0) {
88 close(s);
89 return -1;
90 }
91
92 if ((type & SOCK_TYPE_MASK) == SOCK_STREAM) {
93 int ret;
94
95 ret = listen(s, LISTEN_BACKLOG);
96
97 if (ret < 0) {
98 close(s);
99 return -1;
100 }
101 }
102
103 return s;
104 }
105