1 /*
2  * Copyright (C) 2019 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 <errno.h>
18 #include <netinet/in.h>
19 #include <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/socket.h>
24 #include <sys/un.h>
25 #include <unistd.h>
26 
27 const char* kDomainSocketName = "@RunasConnectAppSocket";
28 
SetUnixSocketAddr(const char * name,struct sockaddr_un * addr_un,socklen_t * addr_len)29 void SetUnixSocketAddr(const char* name, struct sockaddr_un* addr_un,
30                        socklen_t* addr_len) {
31   memset(addr_un, 0, sizeof(*addr_un));
32   addr_un->sun_family = AF_UNIX;
33   strcpy(addr_un->sun_path, name);
34   *addr_len = offsetof(struct sockaddr_un, sun_path) + strlen(name);
35 
36   if (addr_un->sun_path[0] == '@') {
37     addr_un->sun_path[0] = '\0';
38   }
39 }
40 
main()41 int main() {
42   int fd;
43   struct sockaddr_un addr_un;
44   socklen_t addr_len;
45 
46   if ((fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
47     perror("socket error");
48   }
49 
50   SetUnixSocketAddr(kDomainSocketName, &addr_un, &addr_len);
51   if (connect(fd, (struct sockaddr*)&addr_un, addr_len) == -1) {
52     perror("connect error");
53     return EXIT_FAILURE;
54   }
55 
56   const int kBufferSize = 128;
57   char buf[kBufferSize];
58   memset(buf, 0, kBufferSize);
59   ssize_t result = TEMP_FAILURE_RETRY(read(fd, buf, kBufferSize - 1));
60   if (result >= 0) {
61     printf("%s\n", buf);
62   } else {
63     printf("[connector] read() failed");
64     return EXIT_FAILURE;
65   }
66   return EXIT_SUCCESS;
67 }
68