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 <fcntl.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <sys/stat.h>
22 #include <qemud.h>
23 #include <qemu_pipe_bp.h>
24 #include <unistd.h>
25 
qemud_channel_open(const char * name)26 int qemud_channel_open(const char*  name) {
27     return qemu_pipe_open_ns("qemud", name, O_RDWR);
28 }
29 
qemud_channel_send(int pipe,const void * msg,int size)30 int qemud_channel_send(int pipe, const void* msg, int size) {
31     char header[5];
32 
33     if (size < 0)
34         size = strlen((const char*)msg);
35 
36     if (size == 0)
37         return 0;
38 
39     snprintf(header, sizeof(header), "%04x", size);
40     if (qemu_pipe_write_fully(pipe, header, 4)) {
41         return -1;
42     }
43 
44     if (qemu_pipe_write_fully(pipe, msg, size)) {
45         return -1;
46     }
47 
48     return 0;
49 }
50 
qemud_channel_recv(int pipe,void * msg,int maxsize)51 int qemud_channel_recv(int pipe, void* msg, int maxsize) {
52     char header[5];
53     int  size;
54 
55     if (qemu_pipe_read_fully(pipe, header, 4)) {
56         return -1;
57     }
58     header[4] = 0;
59 
60     if (sscanf(header, "%04x", &size) != 1) {
61         return -1;
62     }
63     if (size > maxsize) {
64         return -1;
65     }
66 
67     if (qemu_pipe_read_fully(pipe, msg, size)) {
68         return -1;
69     }
70 
71     return size;
72 }
73