xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/sandbox2/examples/network/network_bin.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // This file is an example of a network sandboxed binary inside a network
16 // namespace. It can't connect with the server directly, but the executor can
17 // establish a connection and pass the connected socket to the sandboxee.
18 
19 #include <unistd.h>
20 
21 #include <cstdint>
22 #include <cstdio>
23 #include <cstring>
24 
25 #include "absl/log/log.h"
26 #include "absl/strings/str_format.h"
27 #include "sandboxed_api/sandbox2/client.h"
28 #include "sandboxed_api/sandbox2/comms.h"
29 
ReadFromFd(int fd,uint8_t * buf,size_t size)30 static ssize_t ReadFromFd(int fd, uint8_t* buf, size_t size) {
31   ssize_t received = 0;
32   while (received < size) {
33     ssize_t read_status =
34         TEMP_FAILURE_RETRY(read(fd, &buf[received], size - received));
35     if (read_status == 0) {
36       break;
37     }
38     if (read_status < 0) {
39       return -1;
40     }
41     received += read_status;
42   }
43   return received;
44 }
45 
CommunicationTest(int sock)46 static bool CommunicationTest(int sock) {
47   char received[1025] = {0};
48 
49   if (ReadFromFd(sock, reinterpret_cast<uint8_t*>(received),
50                  sizeof(received) - 1) <= 0) {
51     LOG(ERROR) << "Data receiving error";
52     return false;
53   }
54   absl::PrintF("Sandboxee received data from the server:\n\n%s\n", received);
55   if (strcmp(received, "Hello World\n")) {
56     LOG(ERROR) << "Data receiving error";
57     return false;
58   }
59 
60   return true;
61 }
62 
main(int argc,char * argv[])63 int main(int argc, char* argv[]) {
64   // Set-up the sandbox2::Client object, using a file descriptor (1023).
65   sandbox2::Comms comms(sandbox2::Comms::kDefaultConnection);
66   sandbox2::Client sandbox2_client(&comms);
67   // Enable sandboxing from here.
68   sandbox2_client.SandboxMeHere();
69 
70   int client;
71   if (!comms.RecvFD(&client)) {
72     fputs("sandboxee: !comms.RecvFD(&client) failed\n", stderr);
73     return 1;
74   }
75 
76   if (!CommunicationTest(client)) {
77     return 2;
78   }
79   return 0;
80 }
81