Fix: double free issue
[apps/agl-service-can-low-level.git] / low-can-binding / diagnostic / diagnostic-manager.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
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 #include <systemd/sd-event.h>
19 #include <algorithm>
20 #include <string.h>
21
22 #include "diagnostic-manager.hpp"
23
24 #include "../utils/openxc-utils.hpp"
25 #include "../utils/signals.hpp"
26 #include "../binding/application.hpp"
27
28 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
29 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
30 // There are only 8 slots of in flight diagnostic requests
31 #define MAX_SIMULTANEOUS_IN_FLIGHT_REQUESTS 8
32 #define TIMERFD_ACCURACY 0
33 #define MICRO 1000000
34
35 diagnostic_manager_t::diagnostic_manager_t()
36         : initialized_{false}
37 {}
38
39
40 diagnostic_manager_t::~diagnostic_manager_t()
41 {
42         for(auto r: recurring_requests_)
43         {
44                 delete(r);
45         }
46         for(auto r: non_recurring_requests_)
47         {
48                 delete(r);
49         }
50 }
51
52 /// @brief Diagnostic manager is not initialized at launch but after
53 ///  the initialization of CAN bus devices. For the moment, it is only possible
54 ///  to have 1 diagnostic bus which are the first bus declared in the JSON
55 ///  description file. Configuration instance will return it.
56 ///
57 /// this will initialize DiagnosticShims and cancel all active requests
58 ///  if there are any.
59 bool diagnostic_manager_t::initialize()
60 {
61         // Mandatory to set the bus before intialize shims.
62         bus_ = application_t::instance().get_diagnostic_bus();
63
64         init_diagnostic_shims();
65         reset();
66
67         initialized_ = true;
68         AFB_DEBUG("Diagnostic Manager initialized");
69         return initialized_;
70 }
71
72 /// @brief initialize shims used by UDS lib and set initialized_ to true.
73 ///  It is needed before used the diagnostic manager fully because shims are
74 ///  required by most member functions.
75 void diagnostic_manager_t::init_diagnostic_shims()
76 {
77         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
78         AFB_DEBUG("Shims initialized");
79 }
80
81 /// @brief Force cleanup all active requests.
82 void diagnostic_manager_t::reset()
83 {
84         AFB_DEBUG("Clearing existing diagnostic requests");
85         cleanup_active_requests(true);
86 }
87
88 /// @brief send function use by diagnostic library. It will open a BCM CAN socket TX_SETUP type.
89 /// That socket will send cyclic messages configured from a diagnostic request.
90 ///
91 /// @param[in] arbitration_id - CAN arbitration ID to use when send message. OBD2 broadcast ID
92 ///  is 0x7DF by example.
93 /// @param[in] data - The data payload for the message. NULL is valid if size is also 0.
94 /// @param[in] size - The size of the data payload, in bytes.
95 ///
96 /// @return true if the CAN message was sent successfully.
97 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
98 {
99         diagnostic_manager_t& dm = application_t::instance().get_diagnostic_manager();
100         active_diagnostic_request_t* current_adr = dm.get_last_recurring_requests();
101         utils::socketcan_bcm_t& tx_socket = current_adr->get_socket();
102
103         // Make sure that socket has been opened.
104         if(! tx_socket)
105                 tx_socket.open(dm.get_bus_device_name());
106
107         struct utils::bcm_msg bcm_msg;
108         struct can_frame cf;
109
110         struct timeval freq = current_adr->get_frequency_clock().get_timeval_from_period();
111
112         bcm_msg.msg_head.opcode  = TX_SETUP;
113         bcm_msg.msg_head.can_id  = arbitration_id;
114         bcm_msg.msg_head.flags = SETTIMER|STARTTIMER|TX_CP_CAN_ID;
115         bcm_msg.msg_head.count = 0;
116         bcm_msg.msg_head.ival2.tv_sec = freq.tv_sec;
117         bcm_msg.msg_head.ival2.tv_usec = freq.tv_usec;
118         bcm_msg.msg_head.nframes = 1;
119         cf.can_dlc = size;
120
121         ::memset(cf.data, 0, sizeof(cf.data));
122         ::memcpy(cf.data, data, size);
123
124         bcm_msg.frames[0] = cf;
125
126         tx_socket << bcm_msg;
127         if(tx_socket)
128                 return true;
129         return false;
130 }
131
132 /// @brief The type signature for an optional logging function, if the user
133 /// wishes to provide one. It should print, store or otherwise display the
134 /// message.
135 ///
136 /// message - A format string to log using the given parameters.
137 /// ... (vargs) - the parameters for the format string.
138 ///
139 void diagnostic_manager_t::shims_logger(const char* format, ...)
140 {
141         va_list args;
142         va_start(args, format);
143
144         char buffer[256];
145         vsnprintf(buffer, 256, format, args);
146
147         AFB_DEBUG("%s", buffer);
148         va_end(args);
149 }
150
151 const std::string diagnostic_manager_t::get_bus_name() const
152 {
153         return bus_;
154 }
155
156 const std::string diagnostic_manager_t::get_bus_device_name() const
157 {
158         return application_t::instance().get_can_bus_manager()
159                 .get_can_device_name(bus_);
160 }
161
162 active_diagnostic_request_t* diagnostic_manager_t::get_last_recurring_requests() const
163 {
164         return recurring_requests_.back();
165 }
166
167 /// @brief Return diagnostic manager shims member.
168 DiagnosticShims& diagnostic_manager_t::get_shims()
169 {
170         return shims_;
171 }
172
173 /// @brief Search for a specific active diagnostic request in the provided requests list
174 /// and erase it from the vector. This is useful at unsubscription to clean up the list otherwize
175 /// all received CAN messages will be passed to DiagnosticRequestHandle of all active diagnostic request
176 /// contained in the vector but no event if connected to, so we will decode uneeded request.
177 ///
178 /// @param[in] entry - a pointer of an active_diagnostic_request instance to clean up
179 /// @param[in] requests_list - a vector where to make the search and cleaning.
180 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
181 {
182         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
183         if ( i != requests_list.end())
184                 requests_list.erase(i);
185 }
186
187 /// @brief Free memory allocated on active_diagnostic_request_t object and close the socket.
188 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
189 {
190         entry->get_socket().close();
191         delete entry;
192         entry = nullptr;
193 }
194
195 /// @brief Cleanup a specific request if it isn't running and get complete. As it is almost
196 /// impossible to get that state for a recurring request without waiting for that, you can
197 /// force the cleaning operation.
198 ///
199 /// @param[in] entry - the request to clean
200 /// @param[in] force - Force the cleaning or not ?
201 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
202 {
203         if(entry != nullptr && (force || entry->response_received()))
204         {
205                 char request_string[128] = {0};
206                 diagnostic_request_to_string(&entry->get_handle()->request,
207                         request_string, sizeof(request_string));
208                 if(force && entry->get_recurring())
209                 {
210                         cancel_request(entry);
211                         find_and_erase(entry, recurring_requests_);
212                         AFB_DEBUG("Cancelling completed, recurring request: %s", request_string);
213                 }
214                 else if (!entry->get_recurring())
215                 {
216                         AFB_DEBUG("Cancelling completed, non-recurring request: %s", request_string);
217                         cancel_request(entry);
218                         find_and_erase(entry, non_recurring_requests_);
219                 }
220         }
221 }
222
223 /// @brief Clean up all requests lists, recurring and not recurring.
224 ///
225 /// @param[in] force - Force the cleaning or not ? If true, that will do
226 /// the same effect as a call to reset().
227 void diagnostic_manager_t::cleanup_active_requests(bool force)
228 {
229         for(auto& entry : non_recurring_requests_)
230         {
231                 if (entry != nullptr)
232                         cleanup_request(entry, force);
233         }
234
235         for(auto& entry : recurring_requests_)
236          {
237                 if (entry != nullptr)
238                         cleanup_request(entry, force);
239          }
240 }
241
242 /// @brief Will return the active_diagnostic_request_t pointer for theDiagnosticRequest or nullptr if
243 /// not found.
244 ///
245 /// @param[in] request - Search key, method will go through recurring list to see if it find that request
246 ///  holded by the DiagnosticHandle member.
247 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(DiagnosticRequest& request)
248 {
249         for (auto& entry : recurring_requests_)
250         {
251                 if(entry != nullptr)
252                 {
253                         if(diagnostic_request_equals(&entry->get_handle()->request, &request))
254                                 {return entry;}
255                 }
256         }
257         return nullptr;
258 }
259 /*
260 /// @brief Add and send a new one-time diagnostic request. DON'T USED AT THIS TIME
261 ///
262 /// A one-time (aka non-recurring) request can existing in parallel with a
263 /// recurring request for the same PID or mode, that's not a problem.
264 ///
265 /// For an example, see the docs for addRecurringRequest. This function is very
266 /// similar but leaves out the frequencyHz parameter.
267 ///
268 /// @param[in] request - The parameters for the request.
269 /// @param[in] name - Human readable name this response, to be used when
270 ///      publishing received responses.
271 /// @param[in] wait_for_multiple_responses - If false, When any response is received
272 ///      for this request it will be removed from the active list. If true, the
273 ///      request will remain active until the timeout clock expires, to allow it
274 ///      to receive multiple response. Functional broadcast requests will always
275 ///      waint for the timeout, regardless of this parameter.
276 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
277 ///      responses to this request. If the decoder is NULL, the output will
278 ///      include the raw payload instead of a parsed value.
279 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
280 ///      response is received for this request.
281 ///
282 /// @return true if the request was added successfully. Returns false if there
283 /// wasn't a free active request entry.
284 active_diagnostic_request_t* diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string& name,
285         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
286         const DiagnosticResponseCallback callback)
287 {
288         cleanup_active_requests(false);
289
290         active_diagnostic_request_t* entry = nullptr;
291
292         if (non_recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
293         {
294                 active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request->arbitration_id, name,
295                                 wait_for_multiple_responses, decoder, callback, 0, false);
296                 entry->set_handle(shims_, request);
297
298                 char request_string[128] = {0};
299                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
300                                 sizeof(request_string));
301
302                 // Erase any existing request not already cleaned.
303                 cleanup_request(entry, true);
304                 AFB_DEBUG("Added one-time diagnostic request on bus %s: %s",
305                                 bus_.c_str(), request_string);
306
307                 non_recurring_requests_.push_back(entry);
308         }
309         else
310         {
311                 AFB_WARNING("There isn't enough request entry. Vector exhausted %d/%d", (int)non_recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
312                 non_recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
313         }
314         return entry;
315 }
316 */
317 /// @brief Validate frequency asked don't get higher than the maximum of a classical
318 /// CAN bus OBD2 request.
319 ///
320 /// @param[in] frequencyHz - frequency asked for sending diagnostic requests.
321 ///
322 /// @return True if frequency is below the Maximum false if not.
323 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
324 {
325         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
326                 AFB_DEBUG("Requested recurring diagnostic frequency %lf is higher than maximum of %d",
327                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
328                 return false;
329         }
330         return true;
331 }
332
333 /// @brief Add and send a new recurring diagnostic request.
334 ///
335 /// At most one recurring request can be active for the same arbitration ID, mode
336 /// and (if set) PID on the same bus at one time. If you try and call
337 /// add_recurring_request with the same key, it will return an error.
338 ///
339 /// @param[in] request - The parameters for the request.
340 /// @param[in] name - An optional human readable name this response, to be used when
341 ///      publishing received responses. If the name is NULL, the published output
342 ///      will use the raw OBD-II response format.
343 /// @param[in] wait_for_multiple_responses - If false, When any response is received
344 ///      for this request it will be removed from the active list. If true, the
345 ///      request will remain active until the timeout clock expires, to allow it
346 ///      to receive multiple response. Functional broadcast requests will always
347 ///      waint for the timeout, regardless of this parameter.
348 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
349 ///      responses to this request. If the decoder is NULL, the output will
350 ///      include the raw payload instead of a parsed value.
351 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
352 ///      response is received for this request.
353 /// @param[in] frequencyHz - The frequency (in Hz) to send the request. A frequency above
354 ///      MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ is not allowed, and will make this
355 ///      function return false.
356 ///
357 /// @return true if the request was added successfully. Returns false if there
358 /// was too much already running requests, or if the frequency was too high.
359 active_diagnostic_request_t* diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
360                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
361                 const DiagnosticResponseCallback callback, float frequencyHz, bool permanent)
362 {
363         active_diagnostic_request_t* entry = nullptr;
364
365         if(!validate_optional_request_attributes(frequencyHz))
366                 return entry;
367
368         cleanup_active_requests(false);
369
370         if(find_recurring_request(*request) == nullptr)
371         {
372                 if(recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
373                 {
374                         entry = new active_diagnostic_request_t(bus_, request->arbitration_id, name,
375                                         wait_for_multiple_responses, decoder, callback, frequencyHz, permanent);
376                         recurring_requests_.push_back(entry);
377
378                         entry->set_handle(shims_, request);
379                         start_diagnostic_request(&shims_, entry->get_handle());
380                 }
381                 else
382                 {
383                         AFB_WARNING("There isn't enough request entry. Vector exhausted %d/%d", (int)recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
384                         recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
385                 }
386         }
387         else
388                 { AFB_DEBUG("Can't add request, one already exists with same key");}
389         return entry;
390 }
391
392 /// @brief Will decode the diagnostic response and build the final openxc_VehicleMessage to return.
393 ///
394 /// @param[in] adr - A pointer to an active diagnostic request holding a valid diagnostic handle
395 /// @param[in] response - The response to decode from which the Vehicle message will be built and returned
396 ///
397 /// @return A filled openxc_VehicleMessage or a zeroed struct if there is an error.
398 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response, const uint64_t timestamp)
399 {
400         openxc_VehicleMessage message = build_VehicleMessage();
401         float value = (float)diagnostic_payload_to_integer(&response);
402
403         struct utils::signals_found found_signals;
404         found_signals = utils::signals_manager_t::instance().find_signals(build_DynamicField((double) adr->get_pid()));
405
406         if(adr->get_decoder() != nullptr)
407         {
408                 value = adr->get_decoder()(&response, value);
409         }
410
411         if((response.success && adr->get_name().size()) > 0)
412         {
413                 // If name, include 'value' instead of payload, and leave of response
414                 // details.
415                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
416                 message.has_diagnostic_response = true;
417                 message.diagnostic_response = build_VehicleMessage(adr, response, value).diagnostic_response;
418         }
419         else
420         {
421                 // If no name, only send full details of response but still include 'value'
422                 // instead of 'payload' if they provided a decoder. The one case you
423                 // can't get is the full detailed response with 'value'. We could add
424                 // another parameter for that but it's onerous to carry that around.
425                 message = build_VehicleMessage(adr, response, value);
426         }
427
428         // If not success but completed then the pid isn't supported
429         if(!response.success)
430         {
431                 found_signals.diagnostic_messages.front()->set_supported(false);
432                 cleanup_request(adr, true);
433                 AFB_NOTICE("PID not supported or ill formed. Please unsubscribe from it. Error code : %d", response.negative_response_code);
434                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField("This PID isn't supported by your vehicle.")));
435         }
436
437         if(adr->get_callback() != nullptr)
438         {
439                 adr->get_callback()(adr, &response, value);
440         }
441
442         // Reset the completed flag handle to make sure that it will be reprocessed the next time.
443         adr->get_handle()->success = false;
444
445         // Save value and timestamp of diagnostic message
446         if(!found_signals.diagnostic_messages.empty())
447         {
448                 // Then, for each diag_message found
449                 for(const auto& diag_mess: found_signals.diagnostic_messages)
450                 {
451                         // Save value and timestamp for this message
452                         diag_mess->set_received(true);
453                         diag_mess->set_last_value(value);
454                         diag_mess->set_timestamp(timestamp);
455                 }
456         }
457
458         return message;
459 }
460
461 /// @brief Will take the CAN message and pass it to the receive functions that will process
462 /// diagnostic handle for each active diagnostic request then depending on the result we will
463 /// return pass the diagnostic response to decode it.
464 ///
465 /// @param[in] entry - A pointer to an active diagnostic request holding a valid diagnostic handle
466 /// @param[in] cm - A raw CAN message.
467 ///
468 /// @return A pointer to a filled openxc_VehicleMessage or a nullptr if nothing has been found.
469 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_handle(active_diagnostic_request_t* entry, const can_message_t& cm)
470 {
471         DiagnosticResponse response = diagnostic_receive_can_frame(&shims_, entry->get_handle(), cm.get_id(), cm.get_data(), cm.get_length());
472         if(response.completed && entry->get_handle()->completed)
473         {
474                 if(entry->get_handle()->success)
475                         return relay_diagnostic_response(entry, response, cm.get_timestamp());
476         }
477         else if(!response.completed && response.multi_frame)
478         {
479                 // Reset the timeout clock while completing the multi-frame receive
480                 entry->get_timeout_clock().tick(
481                         entry->get_timeout_clock().get_time_function()());
482         }
483
484         return build_VehicleMessage();
485 }
486
487 /// @brief Find the active diagnostic request with the correct DiagnosticRequestHandle
488 /// member that will understand the CAN message using diagnostic_receive_can_frame function
489 /// from UDS-C library. Then decode it with an ad-hoc method.
490 ///
491 /// @param[in] cm - Raw CAN message received
492 ///
493 /// @return VehicleMessage with decoded value.
494 openxc_VehicleMessage diagnostic_manager_t::find_and_decode_adr(const can_message_t& cm)
495 {
496         openxc_VehicleMessage vehicle_message = build_VehicleMessage();
497
498         for ( auto entry : non_recurring_requests_)
499         {
500                 vehicle_message = relay_diagnostic_handle(entry, cm);
501                 if (is_valid(vehicle_message))
502                         return vehicle_message;
503         }
504
505         for ( auto entry : recurring_requests_)
506         {
507                 vehicle_message = relay_diagnostic_handle(entry, cm);
508                 if (is_valid(vehicle_message))
509                         return vehicle_message;
510         }
511
512         return vehicle_message;
513 }
514
515 /// @brief Tell if the CAN message received is a diagnostic response.
516 /// Request broadcast ID use 0x7DF and assigned ID goes from 0x7E0 to Ox7E7. That allows up to 8 ECU to respond
517 /// at the same time. The response is the assigned ID + 0x8, so response ID can goes from 0x7E8 to 0x7EF.
518 ///
519 /// @param[in] cm - CAN message received from the socket.
520 ///
521 /// @return True if the active diagnostic request match the response.
522 bool diagnostic_manager_t::is_diagnostic_response(const can_message_t& cm)
523 {
524         if (cm.get_id() >= 0x7e8 && cm.get_id() <= 0x7ef)
525                         return true;
526         return false;
527 }