1 /*
2 * Copyright (C) 2016 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 "common/libs/fs/shared_fd.h"
18 #include "common/libs/fs/shared_select.h"
19
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <gtest/gtest.h>
23
24 #include <string>
25
26 using cvd::InbandMessageHeader;
27 using cvd::SharedFD;
28
29 char hello[] = "Hello, world!";
30 char pipe_message[] = "Testing the pipe";
31
TEST(SendFD,Basic)32 TEST(SendFD, Basic) {
33 char dirname[] = "/tmp/sfdtestXXXXXX";
34 char* socket = mkdtemp(dirname);
35 EXPECT_TRUE(socket != NULL);
36 std::string path(dirname);
37 path += "/s";
38 SharedFD server = SharedFD::SocketSeqPacketServer(path.c_str(), 0700);
39 EXPECT_TRUE(server->IsOpen());
40 int rval = fork();
41 EXPECT_NE(-1, rval);
42 if (!rval) {
43 struct iovec iov { hello, sizeof(hello) };
44 SharedFD client = SharedFD::SocketSeqPacketClient(path.c_str());
45 InbandMessageHeader hdr{};
46 hdr.msg_iov = &iov;
47 hdr.msg_iovlen = 1;
48 SharedFD fds[2];
49 SharedFD::Pipe(fds, fds + 1);
50 ssize_t rval = client->SendMsgAndFDs(hdr, 0, fds);
51 printf("SendMsg sent %zd (%s)\n", rval, client->StrError());
52 exit(0);
53 }
54 server->Listen(2);
55 SharedFD peer = SharedFD::Accept(*server);
56 EXPECT_TRUE(peer->IsOpen());
57 char buf[80];
58 struct iovec iov { buf, sizeof(buf) };
59 InbandMessageHeader hdr{};
60 hdr.msg_iov = &iov;
61 hdr.msg_iovlen = 1;
62 SharedFD fds[2];
63 peer->RecvMsgAndFDs(hdr, 0, &fds);
64 EXPECT_EQ(0, strcmp(buf, hello));
65 EXPECT_TRUE(fds[0]->IsOpen());
66 EXPECT_TRUE(fds[1]->IsOpen());
67 EXPECT_EQ(sizeof(pipe_message), fds[1]->Write(pipe_message, sizeof(pipe_message)));
68 EXPECT_EQ(sizeof(pipe_message), fds[0]->Read(buf, sizeof(buf)));
69 EXPECT_EQ(0, strcmp(buf, pipe_message));
70 }
71