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