1 // Copyright 2022 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 #ifndef CONTRIB_LIBIDN2_LIBIDN2_SAPI_H_ 16 #define CONTRIB_LIBIDN2_LIBIDN2_SAPI_H_ 17 18 #include <idn2.h> 19 #include <syscall.h> 20 21 #include <cstdlib> 22 23 #include "libidn2_sapi.sapi.h" // NOLINT(build/include) 24 #include "absl/log/die_if_null.h" 25 #include "sandboxed_api/util/fileops.h" 26 27 class Idn2SapiSandbox : public IDN2Sandbox { 28 public: ModifyPolicy(sandbox2::PolicyBuilder *)29 std::unique_ptr<sandbox2::Policy> ModifyPolicy( 30 sandbox2::PolicyBuilder*) override { 31 return sandbox2::PolicyBuilder() 32 .AllowSystemMalloc() 33 .AllowRead() 34 .AllowStat() 35 .AllowWrite() 36 .AllowExit() 37 .AllowGetPIDs() 38 .AllowSyscalls({ 39 __NR_futex, 40 __NR_close, 41 __NR_lseek, 42 }) 43 .BlockSyscallWithErrno(__NR_openat, ENOENT) 44 .BuildOrDie(); 45 } 46 }; 47 48 class IDN2Lib { 49 public: IDN2Lib(Idn2SapiSandbox * sandbox)50 explicit IDN2Lib(Idn2SapiSandbox* sandbox) 51 : sandbox_(ABSL_DIE_IF_NULL(sandbox)), api_(sandbox_) {} 52 absl::StatusOr<std::string> idn2_register_u8(const char* ulabel, 53 const char* alabel); 54 absl::StatusOr<std::string> idn2_lookup_u8(const char* data); 55 absl::StatusOr<std::string> idn2_to_ascii_8z(const char* ulabel); 56 absl::StatusOr<std::string> idn2_to_unicode_8z8z(const char* ulabel); 57 58 private: 59 absl::StatusOr<std::string> SapiGeneric( 60 const char* data, 61 absl::StatusOr<int> (IDN2Api::*cb)(sapi::v::Ptr* input, 62 sapi::v::Ptr* output, int flags)); 63 absl::StatusOr<std::string> ProcessErrors(const absl::StatusOr<int>& status, 64 sapi::v::GenericPtr& ptr); 65 Idn2SapiSandbox* sandbox_; 66 IDN2Api api_; 67 }; 68 69 #endif // CONTRIB_LIBIDN2_LIBIDN2_SAPI_H_ 70