blob: 9d4cb1e269cfef6a5173667750740de73346bcb0 [file] [log] [blame]
Roman Kiryanovce321502020-04-10 15:36:21 -07001/*
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
Roman Kiryanovce321502020-04-10 15:36:21 -070017#include <errno.h>
18#include <fcntl.h>
19#include <stdio.h>
Roman Kiryanov774d31d2020-04-22 14:54:39 -070020#include <string.h>
Roman Kiryanovce321502020-04-10 15:36:21 -070021#include <sys/stat.h>
Roman Kiryanov774d31d2020-04-22 14:54:39 -070022#include <qemud.h>
Roman Kiryanov4ad4ff52020-04-30 20:26:16 -070023#include <qemu_pipe_bp.h>
Roman Kiryanov774d31d2020-04-22 14:54:39 -070024#include <unistd.h>
Roman Kiryanovce321502020-04-10 15:36:21 -070025
Roman Kiryanov774d31d2020-04-22 14:54:39 -070026int qemud_channel_open(const char* name) {
Roman Kiryanovce321502020-04-10 15:36:21 -070027 return qemu_pipe_open_ns("qemud", name, O_RDWR);
28}
29
Roman Kiryanov774d31d2020-04-22 14:54:39 -070030int qemud_channel_send(int pipe, const void* msg, int size) {
31 char header[5];
Roman Kiryanovce321502020-04-10 15:36:21 -070032
Roman Kiryanov774d31d2020-04-22 14:54:39 -070033 if (size < 0)
34 size = strlen((const char*)msg);
Roman Kiryanovce321502020-04-10 15:36:21 -070035
Roman Kiryanov774d31d2020-04-22 14:54:39 -070036 if (size == 0)
Roman Kiryanovce321502020-04-10 15:36:21 -070037 return 0;
38
Roman Kiryanov774d31d2020-04-22 14:54:39 -070039 snprintf(header, sizeof(header), "%04x", size);
Roman Kiryanovce321502020-04-10 15:36:21 -070040 if (qemu_pipe_write_fully(pipe, header, 4)) {
41 return -1;
42 }
43
Roman Kiryanov774d31d2020-04-22 14:54:39 -070044 if (qemu_pipe_write_fully(pipe, msg, size)) {
Roman Kiryanovce321502020-04-10 15:36:21 -070045 return -1;
46 }
47
48 return 0;
49}
50
Roman Kiryanov774d31d2020-04-22 14:54:39 -070051int qemud_channel_recv(int pipe, void* msg, int maxsize) {
52 char header[5];
53 int size;
Roman Kiryanovce321502020-04-10 15:36:21 -070054
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 }
Roman Kiryanov774d31d2020-04-22 14:54:39 -070063 if (size > maxsize) {
Roman Kiryanovce321502020-04-10 15:36:21 -070064 return -1;
Roman Kiryanov774d31d2020-04-22 14:54:39 -070065 }
Roman Kiryanovce321502020-04-10 15:36:21 -070066
67 if (qemu_pipe_read_fully(pipe, msg, size)) {
68 return -1;
69 }
70
71 return size;
72}