1 /*
2  * Copyright (C) 2020 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 <log/log.h>
19 #include <sys/types.h>
20 #include <fcntl.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <qemu_pipe_bp.h>
26 
27 namespace {
open_verbose(const char * name,int flags)28 int open_verbose(const char* name, int flags) {
29     const int fd = QEMU_PIPE_RETRY(open(name, flags));
30     if (fd < 0) {
31         ALOGE("%s:%d: Could not open '%s': %s",
32               __func__, __LINE__, name, strerror(errno));
33     }
34     return fd;
35 }
36 
37 }  // namespace
38 
39 extern "C" {
40 
qemu_pipe_open_ns(const char * ns,const char * pipeName,int flags)41 int qemu_pipe_open_ns(const char* ns, const char* pipeName, int flags) {
42     if (pipeName == NULL || pipeName[0] == '\0') {
43         errno = EINVAL;
44         return -1;
45     }
46 
47     const int fd = open_verbose("/dev/goldfish_pipe", flags);
48     if (fd < 0) {
49         return fd;
50     }
51 
52     char buf[256];
53     int bufLen;
54     if (ns) {
55         bufLen = snprintf(buf, sizeof(buf), "pipe:%s:%s", ns, pipeName);
56     } else {
57         bufLen = snprintf(buf, sizeof(buf), "pipe:%s", pipeName);
58     }
59 
60     if (qemu_pipe_write_fully(fd, buf, bufLen + 1)) {
61         ALOGE("%s:%d: Could not connect to the '%s' service: %s",
62               __func__, __LINE__, buf, strerror(errno));
63         return -1;
64     }
65 
66     return fd;
67 }
68 
qemu_pipe_open(const char * pipeName)69 int qemu_pipe_open(const char* pipeName) {
70     return qemu_pipe_open_ns(NULL, pipeName, O_RDWR | O_NONBLOCK);
71 }
72 
qemu_pipe_close(int pipe)73 void qemu_pipe_close(int pipe) {
74     close(pipe);
75 }
76 
qemu_pipe_read(int pipe,void * buffer,int size)77 int qemu_pipe_read(int pipe, void* buffer, int size) {
78     return read(pipe, buffer, size);
79 }
80 
qemu_pipe_write(int pipe,const void * buffer,int size)81 int qemu_pipe_write(int pipe, const void* buffer, int size) {
82     return write(pipe, buffer, size);
83 }
84 
qemu_pipe_try_again(int ret)85 int qemu_pipe_try_again(int ret) {
86     return (ret < 0) && (errno == EINTR || errno == EAGAIN);
87 }
88 
qemu_pipe_print_error(int pipe)89 void qemu_pipe_print_error(int pipe) {
90     ALOGE("pipe error: fd %d errno %d", pipe, errno);
91 }
92 
93 }  // extern "C"
94