1 /* 2 * Copyright (C) 2020 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 #pragma once 18 19 #include <android-base/macros.h> 20 #include <android/hardware/automotive/can/1.0/ICanBus.h> 21 #include <libprotocan/MessageCounter.h> 22 #include <libprotocan/MessageDef.h> 23 #include <utils/Mutex.h> 24 25 #include <mutex> 26 #include <queue> 27 28 namespace android::hardware::automotive::protocan { 29 30 class MessageInjectorManager; 31 32 /** 33 * Injects CAN messages with a counter to an existing system. 34 * 35 * This class is NOT meant to use in production - there should be no need to inject counted CAN 36 * messages where the other sender is also broadcasting them. If this is the case, it may be a sign 37 * your CAN network needs a redesign. This tool is intended for use for testing and demo purposes. 38 */ 39 class MessageInjector { 40 public: 41 MessageInjector(MessageDef msgDef, std::optional<std::chrono::milliseconds> interMessageDelay); 42 43 void inject(const can::V1_0::CanMessage& msg); 44 void inject(const std::initializer_list<can::V1_0::CanMessage> msgs); 45 46 private: 47 const MessageDef kMsgDef; 48 const std::optional<std::chrono::milliseconds> kInterMessageDelay; 49 MessageCounter mCounter; 50 51 mutable std::mutex mMessagesGuard; 52 std::queue<can::V1_0::CanMessage> mMessages GUARDED_BY(mMessagesGuard); 53 54 void onReceive(can::V1_0::ICanBus& bus, const can::V1_0::CanMessage& msg); 55 void processQueueLocked(can::V1_0::ICanBus& bus); 56 57 friend class MessageInjectorManager; 58 59 DISALLOW_COPY_AND_ASSIGN(MessageInjector); 60 }; 61 62 /** 63 * Routes intercepted messages to MessageInjector instances configured to handle specific CAN 64 * message (CAN message ID). Intercepted messages from other nodes in CAN network are used to read 65 * current counter value in order to spoof the next packet. 66 */ 67 class MessageInjectorManager { 68 public: 69 MessageInjectorManager(std::initializer_list<std::shared_ptr<MessageInjector>> injectors); 70 71 void onReceive(sp<can::V1_0::ICanBus> bus, const can::V1_0::CanMessage& msg); 72 73 private: 74 std::map<can::V1_0::CanMessageId, std::shared_ptr<MessageInjector>> mInjectors; 75 76 DISALLOW_COPY_AND_ASSIGN(MessageInjectorManager); 77 }; 78 79 } // namespace android::hardware::automotive::protocan 80