blob: b68209ef367181acd182da11aef6427e07c1aa2d [file] [log] [blame]
Andres Moralesb33c9b82015-09-08 17:56:07 -07001/*
2 * Copyright (C) 2015 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// TODO: make this generic in libtrusty
18
19#include <errno.h>
20#include <stdlib.h>
21#include <string.h>
22
23#define LOG_TAG "TrustyKeymaster"
24#include <cutils/log.h>
25
26#include <trusty/tipc.h>
27
28#include "trusty_keymaster_ipc.h"
29#include "keymaster_ipc.h"
30
31#define TRUSTY_DEVICE_NAME "/dev/trusty-ipc-dev0"
32
33static int handle_ = 0;
34
35int trusty_keymaster_connect() {
36 int rc = tipc_connect(TRUSTY_DEVICE_NAME, KEYMASTER_PORT);
37 if (rc < 0) {
38 return rc;
39 }
40
41 handle_ = rc;
42 return 0;
43}
44
45int trusty_keymaster_call(uint32_t cmd, void *in, uint32_t in_size, uint8_t *out,
46 uint32_t *out_size) {
47 if (handle_ == 0) {
48 ALOGE("not connected\n");
49 return -EINVAL;
50 }
51
52 size_t msg_size = in_size + sizeof(struct keymaster_message);
53 struct keymaster_message *msg = malloc(msg_size);
54 msg->cmd = cmd;
55 memcpy(msg->payload, in, in_size);
56
57 ssize_t rc = write(handle_, msg, msg_size);
58 free(msg);
59
60 if (rc < 0) {
61 ALOGE("failed to send cmd (%d) to %s: %s\n", cmd,
62 KEYMASTER_PORT, strerror(errno));
63 return -errno;
64 }
65
66 rc = read(handle_, out, *out_size);
67 if (rc < 0) {
68 ALOGE("failed to retrieve response for cmd (%d) to %s: %s\n",
69 cmd, KEYMASTER_PORT, strerror(errno));
70 return -errno;
71 }
72
73 if ((size_t) rc < sizeof(struct keymaster_message)) {
74 ALOGE("invalid response size (%d)\n", (int) rc);
75 return -EINVAL;
76 }
77
78 msg = (struct keymaster_message *) out;
79
80 if ((cmd | KEYMASTER_RESP_BIT) != msg->cmd) {
81 ALOGE("invalid command (%d)", msg->cmd);
82 return -EINVAL;
83 }
84
85 *out_size = ((size_t) rc) - sizeof(struct keymaster_message);
86 return rc;
87}
88
89void trusty_keymaster_disconnect() {
90 if (handle_ != 0) {
91 tipc_close(handle_);
92 }
93}
94