1 /*
2 * Copyright (C) 2021 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 <lib/storage/storage.h>
18 #include <stddef.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <time.h>
23 #include <trusty_ipc.h>
24 #include <trusty_log.h>
25 #include <uapi/err.h>
26
27 #define TLOG_TAG "storagetest-app"
28 #define TEST_CTRL_PORT "com.android.trusty.storagetest"
29
30 static const char* kFilePath = "storage_test_file";
31
write_file(size_t size)32 static int write_file(size_t size) {
33 uint8_t data[1024];
34
35 if (size > sizeof(data)) {
36 size = sizeof(data);
37 }
38
39 TLOGI("writing size %zu\n", size);
40 storage_session_t session;
41 int rc = storage_open_session(&session, STORAGE_CLIENT_TP_PORT);
42 if (rc < 0) {
43 TLOGE("couldn't open storage session\n");
44 return -1;
45 }
46
47 file_handle_t handle;
48 rc = storage_open_file(
49 session, &handle, kFilePath,
50 STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE, 0);
51
52 if (rc < 0) {
53 TLOGE("failed to create file: %d\n", rc);
54 goto error;
55 }
56
57 memset(data, 0, size);
58 rc = storage_write(handle, 0, data, size, STORAGE_OP_COMPLETE);
59 storage_close_file(handle);
60
61 error:
62 storage_close_session(session);
63 return 0;
64 }
65
main(void)66 int main(void) {
67 int rc;
68 handle_t hport;
69 uuid_t peer_uuid;
70
71 TLOGI("Starting storage test app!!!\n");
72
73 /* create control port and wait on it */
74 rc = port_create(TEST_CTRL_PORT, 1, 1024, IPC_PORT_ALLOW_NS_CONNECT);
75 if (rc < 0) {
76 TLOGE("failed (%d) to create ctrl port\n", rc);
77 return rc;
78 }
79 hport = (handle_t)rc;
80
81 /* and just wait forever on control port */
82 for (;;) {
83 uevent_t uevt;
84 int rc = wait(hport, &uevt, INFINITE_TIME);
85 if (rc == NO_ERROR) {
86 if (uevt.event & IPC_HANDLE_POLL_READY) {
87 /* got connection request */
88 rc = accept(uevt.handle, &peer_uuid);
89 if (rc >= 0) {
90 handle_t ctrl_chan = (handle_t)rc;
91
92 for (;;) {
93 rc = write_file(256);
94 if (rc < 0)
95 break;
96
97 rc = wait(ctrl_chan, &uevt, 0);
98 if (rc == ERR_CHANNEL_CLOSED) {
99 TLOGD("channel closed\n");
100 break;
101 }
102 if (uevt.event & IPC_HANDLE_POLL_HUP) {
103 TLOGD("POLL_HUP\n");
104 break;
105 }
106 }
107 close(ctrl_chan);
108 continue;
109 } else {
110 TLOGE("accept() failed\n");
111 }
112 }
113 }
114 if (rc < 0)
115 break;
116 }
117 TLOGD("exiting with exit code %d\n", rc);
118 return rc;
119 }
120