1 /* 2 * Copyright (C) 2021 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 18 #pragma once 19 20 #include <memory> 21 #include <queue> 22 #include <string> 23 24 #include <android-base/macros.h> 25 26 #include "socket.h" 27 28 class SocketMockFuzz : public Socket { 29 public: 30 SocketMockFuzz(); 31 ~SocketMockFuzz() override; 32 33 bool Send(const void* data, size_t length) override; 34 bool Send(std::vector<cutils_socket_buffer_t> buffers) override; 35 ssize_t Receive(void* data, size_t length, int timeout_ms) override; 36 int Close() override; 37 virtual std::unique_ptr<Socket> Accept(); 38 39 // Adds an expectation for Send(). 40 void ExpectSend(std::string message); 41 42 // Adds an expectation for Send() that returns false. 43 void ExpectSendFailure(std::string message); 44 45 // Adds data to provide for Receive(). 46 void AddReceive(std::string message); 47 48 // Adds a Receive() timeout after which ReceiveTimedOut() will return true. 49 void AddReceiveTimeout(); 50 51 // Adds a Receive() failure after which ReceiveTimedOut() will return false. 52 void AddReceiveFailure(); 53 54 // Adds a Socket to return from Accept(). 55 void AddAccept(std::unique_ptr<Socket> sock); 56 57 private: 58 enum class EventType { kSend, kReceive, kAccept }; 59 60 struct Event { 61 Event(EventType _type, std::string _message, ssize_t _status, 62 std::unique_ptr<Socket> _sock); 63 64 EventType type; 65 std::string message; 66 bool status; // Return value for Send() or timeout status for Receive(). 67 std::unique_ptr<Socket> sock; 68 }; 69 70 std::queue<Event> events_; 71 72 DISALLOW_COPY_AND_ASSIGN(SocketMockFuzz); 73 }; 74