1 /* 2 * Copyright (C) 2017 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 requied 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 18 #ifndef DNS_TLS_FRONTEND_H 19 #define DNS_TLS_FRONTEND_H 20 21 #include <arpa/nameser.h> 22 23 #include <atomic> 24 #include <mutex> 25 #include <string> 26 #include <thread> 27 #include <unordered_map> 28 #include <vector> 29 30 #include <android-base/thread_annotations.h> 31 #include <openssl/ssl.h> 32 33 namespace test { 34 35 /* 36 * Simple DNS over TLS reverse proxy that forwards to a UDP backend. 37 * Only handles a single request at a time. 38 */ 39 class DnsTlsFrontend { 40 public: 41 DnsTlsFrontend(const std::string& listen_address, const std::string& listen_service, 42 const std::string& backend_address, const std::string& backend_service) : 43 listen_address_(listen_address), listen_service_(listen_service), 44 backend_address_(backend_address), backend_service_(backend_service), 45 queries_(0), terminate_(false) { } 46 ~DnsTlsFrontend() { 47 stopServer(); 48 } 49 const std::string& listen_address() const { 50 return listen_address_; 51 } 52 const std::string& listen_service() const { 53 return listen_service_; 54 } 55 bool running() const { 56 return socket_ != -1; 57 } 58 bool startServer(); 59 bool stopServer(); 60 int queries() const { return queries_; } 61 bool waitForQueries(int number, int timeoutMs) const; 62 const std::vector<uint8_t>& fingerprint() const { return fingerprint_; } 63 64 private: 65 void requestHandler(); 66 bool handleOneRequest(SSL* ssl); 67 68 std::string listen_address_; 69 std::string listen_service_; 70 std::string backend_address_; 71 std::string backend_service_; 72 bssl::UniquePtr<SSL_CTX> ctx_; 73 int socket_ = -1; 74 int backend_socket_ = -1; 75 std::atomic<int> queries_; 76 std::atomic<bool> terminate_ GUARDED_BY(update_mutex_); 77 std::thread handler_thread_ GUARDED_BY(update_mutex_); 78 std::mutex update_mutex_; 79 std::vector<uint8_t> fingerprint_; 80 }; 81 82 } // namespace test 83 84 #endif // DNS_TLS_FRONTEND_H 85