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 
26 #include <arpa/inet.h>
27 
qemud_channel_open(const char * name)28 int qemud_channel_open(const char*  name) {
29     return qemu_pipe_open_ns("qemud", name, O_RDWR);
30 }
31 
qemud_channel_send(int pipe,const void * msg,int size)32 int qemud_channel_send(int pipe, const void* msg, int size) {
33     char header[5];
34 
35     if (size < 0)
36         size = strlen((const char*)msg);
37 
38     if (size == 0)
39         return 0;
40 
41     if(size >= 64 * 1024) { // use binary encoding
42         uint32_t length32be = htonl(size | (1U << 31));
43         memcpy(header, &length32be, 4);
44     } else { // use hex digit encoding
45         snprintf(header, sizeof(header), "%04x", size);
46     }
47 
48     if (qemu_pipe_write_fully(pipe, header, 4)) {
49         return -1;
50     }
51 
52     if (qemu_pipe_write_fully(pipe, msg, size)) {
53         return -1;
54     }
55 
56     return 0;
57 }
58 
qemud_channel_recv(int pipe,void * msg,int maxsize)59 int qemud_channel_recv(int pipe, void* msg, int maxsize) {
60     char header[5];
61     int  size;
62 
63     if (qemu_pipe_read_fully(pipe, header, 4)) {
64         return -1;
65     }
66     header[4] = 0;
67 
68     if (sscanf(header, "%04x", &size) != 1) {
69         return -1;
70     }
71     if (size > maxsize) {
72         return -1;
73     }
74 
75     if (qemu_pipe_read_fully(pipe, msg, size)) {
76         return -1;
77     }
78 
79     return size;
80 }
81