1 /****************************************************************************** 2 * 3 * Copyright (C) 2022 Google, Inc. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at: 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 ******************************************************************************/ 18 19 #pragma once 20 21 #include <condition_variable> 22 #include <memory> 23 #include <mutex> 24 #include <thread> 25 26 #include "hal/snoop_logger_socket_interface.h" 27 #include "hal/syscall_wrapper_interface.h" 28 29 namespace bluetooth { 30 namespace hal { 31 32 class SnoopLoggerSocket { 33 public: 34 static constexpr int DEFAULT_LOCALHOST_ = 0x7F000001; 35 static constexpr int DEFAULT_LISTEN_PORT_ = 8872; 36 37 SnoopLoggerSocket( 38 SyscallWrapperInterface* syscall_if, int address = DEFAULT_LOCALHOST_, int port = DEFAULT_LISTEN_PORT_); 39 SnoopLoggerSocket(const SnoopLoggerSocket&) = delete; 40 SnoopLoggerSocket& operator=(const SnoopLoggerSocket&) = delete; 41 virtual ~SnoopLoggerSocket(); 42 43 int InitializeCommunications(); 44 bool ProcessIncomingRequest(); 45 void Cleanup(); 46 bool IsClientSocketConnected() const; 47 bool WaitForClientSocketConnected(); 48 int NotifySocketListener(); 49 void Write(const void* data, size_t length); 50 51 int AcceptIncomingConnection(int listen_socket, int& client_socket); 52 int CreateSocket(); 53 void ClientSocketConnected(int client_socket); 54 void InitializeClientSocket(int client_socket); 55 void SafeCloseSocket(int& fd); 56 void Write(int& client_socket, const void* data, size_t length); 57 58 SyscallWrapperInterface* GetSyscallWrapperInterface() const; 59 60 private: 61 // Pointer to syscall interface 62 SyscallWrapperInterface* syscall_if_; 63 64 // Server socket address and port. 65 int socket_address_; 66 int socket_port_; 67 68 // A pair of FD to send information to the listen thread. 69 int notification_listen_fd_; 70 int notification_write_fd_; 71 72 // Server socket 73 int listen_socket_; 74 75 // Socket FDs for listening for connections 76 // and for communitcation with listener thread. 77 fd_set save_sock_fds_; 78 int fd_max_; 79 80 // Reference to connected client socket. 81 std::mutex client_socket_mutex_; 82 int client_socket_; 83 std::condition_variable client_socket_cv_; 84 }; 85 86 } // namespace hal 87 } // namespace bluetooth 88