summaryrefslogtreecommitdiff
path: root/src/components/connection_handler/include/connection_handler/connection_handler_impl.h
blob: 8ddc6e5a53c127d140d09e16bff333f022621b87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/*
 * Copyright (c) 2014, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SRC_COMPONENTS_CONNECTION_HANDLER_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_IMPL_H_
#define SRC_COMPONENTS_CONNECTION_HANDLER_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_IMPL_H_

#include <map>
#include <list>
#include <string>
#include <vector>

#include "transport_manager/transport_manager_listener_empty.h"
#include "protocol_handler/session_observer.h"
#include "protocol_handler/protocol_handler.h"
#include "connection_handler/connection_handler_observer.h"
#include "connection_handler/device.h"
#include "connection_handler/connection.h"
#include "connection_handler/devices_discovery_starter.h"
#include "connection_handler/connection_handler.h"
#include "utils/logger.h"
#include "utils/macro.h"
#include "utils/lock.h"
#include "utils/stl_utils.h"
#include "utils/singleton.h"

/**
 * \namespace connection_handler
 * \brief SmartDeviceLink connection_handler namespace.
 */
namespace connection_handler {
/**
 * \class ConnectionHandlerImpl
 * \brief SmartDeviceLink connection_handler main class
 * Observes TransportManager and ProtocolHandler,
 * stores information regarding connections
 * and sessions and provides it to AppManager.
 */
class ConnectionHandlerImpl : public ConnectionHandler,
  public transport_manager::TransportManagerListenerEmpty,
  public protocol_handler::SessionObserver,
  public DevicesDiscoveryStarter,
  public utils::Singleton<ConnectionHandlerImpl> {
 public:
  /**
   * \brief Destructor
   */
  virtual ~ConnectionHandlerImpl();

    void Stop();
  /**
   * \brief Sets observer pointer for connection_handler.
   * \param observer Pointer to observer object.
   */
  virtual void set_connection_handler_observer(
    ConnectionHandlerObserver *observer);

  /**
    * \brief Sets pointer to TransportManager.
    * \param transport_mngr Pointer to TransportManager object.
    **/
  virtual void set_transport_manager(
    transport_manager::TransportManager *transport_mngr);

  /**
   * \brief Sets pointer to ProtocolHandler.
   * \param protocol_handler Pointer to ProtocolHandler object.
   **/
  void set_protocol_handler(
    protocol_handler::ProtocolHandler *protocol_handler);

  /**
   * \brief Connects to all services of device
   * \param deviceHandle Handle of device to connect to
   */
  virtual void ConnectToDevice(connection_handler::DeviceHandle device_handle);

  virtual void ConnectToAllDevices();

  virtual void StartTransportManager();

  virtual void OnDeviceListUpdated(
    const std::vector<transport_manager::DeviceInfo> &);

  virtual void OnFindNewApplicationsRequest();

  /**
   * \brief Available devices list updated.
   *
   * Called when device scanning initiated with scanForNewDevices
   * is completed or devices connected via background procedures.
   *
   * \param DeviceList New list of available devices.
   **/
  virtual void OnDeviceFound(const transport_manager::DeviceInfo &device_info);
  virtual void OnDeviceAdded(const transport_manager::DeviceInfo &device_info);
  virtual void OnDeviceRemoved(const transport_manager::DeviceInfo &device_info);

  virtual void OnScanDevicesFinished();
  virtual void OnScanDevicesFailed(
    const transport_manager::SearchDeviceError &error);

  /**
   * \brief Notifies about established connection.
   *
   * \param connection_id ID of new connection.
   **/
  virtual void OnConnectionEstablished(
    const transport_manager::DeviceInfo &device_info,
    const transport_manager::ConnectionUID &connection_id);
  virtual void OnConnectionFailed(
    const transport_manager::DeviceInfo &device_info,
    const transport_manager::ConnectError &error);
  virtual void OnConnectionClosed(
    transport_manager::ConnectionUID connection_id);
  virtual void OnConnectionClosedFailure(
    transport_manager::ConnectionUID connection_id,
    const transport_manager::DisconnectError &error);
  virtual void OnUnexpectedDisconnect(
    transport_manager::ConnectionUID connection_id,
    const transport_manager::CommunicationError &error);
  virtual void OnDeviceConnectionLost(
    const connection_handler::DeviceHandle &device,
    const transport_manager::DisconnectDeviceError &error);
  /**
   * \brief Informs about failure during DisconnectDevice procedure of TM
   * \param device Information about disconnected device
   * \param error Information about possible reason of loosing connection
   */
  virtual void OnDisconnectFailed(
    const connection_handler::DeviceHandle &device,
    const transport_manager::DisconnectDeviceError &error);

  /**
   * \brief Callback function used by ProtocolHandler
   * when Mobile Application initiates start of new session.
   * \param connection_handle Connection identifier within which session has to be started.
   * \param session_id Identifier of the session to be started
   * \param service_type Type of service
   * \param is_protected would be service protected
   * \param hash_id pointer for session hash identifier
   * \return uint32_t Id (number) of new session if successful, otherwise 0.
   */
  virtual uint32_t OnSessionStartedCallback(const transport_manager::ConnectionUID &connection_handle,
    const uint8_t session_id,
    const protocol_handler::ServiceType &service_type,
    const bool is_protected, uint32_t* hash_id);

  /**
   * \brief Callback function used by ProtocolHandler
   * when Mobile Application initiates session ending.
   * \param connection_handle Connection identifier within which session exists
   * \param sessionId Identifier of the session to be ended
   * \param hashCode Hash used only in second version of SmartDeviceLink protocol.
   * If not equal to hash assigned to session on start then operation fails.
   * \return uint32_t 0 if operation fails, session key otherwise
   */
  virtual uint32_t OnSessionEndedCallback(
    const transport_manager::ConnectionUID &connection_handle,
    const uint8_t session_id, const uint32_t &hashCode,
    const protocol_handler::ServiceType &service_type);

  /**
   * \brief Callback function used by ProtocolHandler
   * when Mobile Application start message flood
   * \param connection_key  used by other components as application identifier
   */
  void OnApplicationFloodCallBack(const uint32_t &connection_key) OVERRIDE;

  /**
   * \brief Callback function used by ProtocolHandler
   * when Mobile Application sends malformed message
   * \param connection_key  used by other components as application identifier
   */
  void OnMalformedMessageCallback(const uint32_t &connection_key) OVERRIDE;

  /**
   * \brief Creates unique identifier of session (can be used as hash)
   * from given connection identifier
   * within which session exists and session number.
   * \param  connection_handle Connection identifier within which session exists
   * \param sessionId Identifier of the session
   * \return int32_t Unique key for session
   */
  virtual uint32_t KeyFromPair(
    transport_manager::ConnectionUID connection_handle,
    uint8_t session_id);

  /**
   * \brief Returns connection identifier and session number from given session key
   * \param key Unique key used by other components as session identifier
   * \param connection_handle Returned: Connection identifier within which session exists
   * \param sessionId Returned: Number of session
   */
  virtual void PairFromKey(uint32_t key,
                           transport_manager::ConnectionUID *connection_handle,
                           uint8_t *session_id);

  /**
   * \brief information about given Connection Key.
   * \param key Unique key used by other components as session identifier
   * \param app_id Returned: ApplicationID
   * \param sessions_list Returned: List of session keys
   * \param device_id Returned: DeviceID
   * \return int32_t -1 in case of error or 0 in case of success
   */
  virtual int32_t GetDataOnSessionKey(uint32_t key, uint32_t *app_id = 0,
                                      std::list<int32_t> *sessions_list = NULL,
                                      uint32_t *device_id = 0);

  /**
   * \brief information about device
   * \param device_handle
   * \param device_name Returned: name of device
   * \param applications_list Returned: applications on device
   * \param mac_address Returned: List of session keys
   * \param connection_type Returned: type of connection (USB, BT, etc.)
   * \return int32_t -1 in case of error or 0 in case of success
   */
  virtual int32_t GetDataOnDeviceID(connection_handler::DeviceHandle device_handle,
                                    std::string *device_name = NULL,
                                    std::list<uint32_t> *applications_list = NULL,
                                    std::string *mac_address = NULL,
                                    std::string* connection_type = NULL);
#ifdef ENABLE_SECURITY
  /**
   * \brief Sets crypto context of connection
   * \param key Unique key used by other components as session identifier
   * \param context SSLContext to be set
   * \return \c SecurityQuery::ProtectSessionResult value
   */
  int SetSSLContext(
    const uint32_t &key,
    security_manager::SSLContext *context) OVERRIDE;

  /**
   * \brief Gets crypto context of connection, use service_type to get NULL
   * SSLContext for not protected services or ControlService (0x0)
   * to get current SSLContext of connection
   * \param key Unique key used by other components as session identifier
   * \param service_type Type of service
   * \return \ref SSLContext of connection
   */
  security_manager::SSLContext *GetSSLContext(
    const uint32_t &key,
    const protocol_handler::ServiceType &service_type) OVERRIDE;
  /**
   * \brief Set protection flag to service in session by key
   * \param key Unique key used by other components as session identifier
   * \param service_type Type of service
   */
  void SetProtectionFlag(
    const uint32_t &key,
    const protocol_handler::ServiceType &service_type) OVERRIDE;
#endif  // ENABLE_SECURITY

  /**
   * \brief Get device handle by mac address
   * \param mac_address uniq address
   * \param device_handle
   * \return true on sucess otherwise false.
   */
  virtual bool GetDeviceID(const std::string &mac_address,
                           DeviceHandle *device_handle);

  /**
   * \brief Method which should start devices discovering
   */
  virtual void StartDevicesDiscovery();

  /**
   * @brief Close the connection revoked by Policy
   * @param connection_key pair of connection and session id
   */
  virtual void CloseRevokedConnection(uint32_t connection_key);

  /**
   * @brief Close the connection pointed by handle
   * @param connection_handle Connection unique id
   */
  virtual void CloseConnection(ConnectionHandle connection_handle) OVERRIDE;

  /**
   * \brief Close session associated with the key
   * \param key Unique key used by other components as session identifier
   */
  virtual void CloseSession(uint32_t key, CloseSessionReason close_reason);

  /**
   * \brief Function used by HearbeatMonitior to close session on HB timeout
   * \param connection_handle Connection handler within which session exists
   * \param session_id Identifier of the session to be ended
   */
  virtual void CloseSession(ConnectionHandle connection_handle,
                            uint8_t session_id,
                            CloseSessionReason close_reason);

  /**
   * \brief Function used by OnApplicationFloodCallback and
   * OnMalformedMessageCallback to close all connection sessions before
   * connection closing
   * \param connection_handle Connection identifier within which session exists
   * \param close_reason The reason of connection closing
   */
  virtual void CloseConnectionSessions(
      ConnectionHandle connection_handle, CloseSessionReason close_reason);

  /**
   * \brief Return count of session for specified connection
   * \param connection_key pair of connection handle and session id
   */
  virtual uint32_t GetConnectionSessionsCount(uint32_t connection_key);

  /**
   * \brief Send heartbeat message to mobile app
   */
  virtual void SendHeartBeat(ConnectionHandle connection_handle,
                             uint8_t session_id);

  /**
   * @brief SendEndService allows to end up specific service.
   *
   * @param key application identifier whose service should be closed.
   *
   * @param service_type the service that should be closed.
   */
  virtual void SendEndService(uint32_t key,
                              uint8_t service_type);

  /**
   * \brief Start heartbeat for specified session
   *
   * \param connection_key pair of connection and session id
   */
  virtual void StartSessionHeartBeat(uint32_t connection_key);

  /**
   * Sets heart beat timeout for specified session
   * @param connection_key pair of connection and session id
   * @param timeout in seconds
   */
  virtual void SetHeartBeatTimeout(uint32_t connection_key, int32_t timeout);

  /**
   * \brief Keep connection associated with the key from being closed by heartbeat monitor
   */
  void KeepConnectionAlive(uint32_t connection_key, uint8_t session_id);

  /**
   * \brief binds protocol version with session
   *
   * \param connection_key pair of connection and session id
   * \param protocol_version contains protocol version of
   * \registered application.
   */
  virtual void BindProtocolVersionWithSession(uint32_t connection_key,
      uint8_t protocol_version);

  /**
   * \brief returns TRUE if session supports sending HEART BEAT ACK to mobile side
   * \param  connection_handle Connection identifier whithin which session exists
   * \param sessionId Identifier of the session
   * \return TRUE if session has protocol version which supports heartbeat otherwise returns FALSE
   */
  virtual bool IsHeartBeatSupported(
    transport_manager::ConnectionUID connection_handle,
    uint8_t session_id);

  /**
   * @brief returns protocol version which application supports
   * @param connection_id id of connection
   * @param session_id id of session
   * @param method writes value protocol version to protocol_version
   * @return TRUE if session and connection exist otherwise returns FALSE
   */
  virtual bool ProtocolVersionUsed(uint32_t connection_id,
  		  uint8_t session_id, uint8_t& protocol_version);
  private:
  /**
   * \brief Default class constructor
   */
  ConnectionHandlerImpl();

  /**
   * \brief Disconnect application.
   *
   * \param device_handle DeviceHandle of disconnected device.
   * \param connection_handle Connection handle.
   **/
  void RemoveConnection(const ConnectionHandle connection_handle);

  void OnConnectionEnded(
    const transport_manager::ConnectionUID &connection_id);

  /**
   * \brief Pointer to observer
   */
  ConnectionHandlerObserver *connection_handler_observer_;

  /**
   * \brief Pointer to TransportManager
   */
  transport_manager::TransportManager *transport_manager_;

  protocol_handler::ProtocolHandler *protocol_handler_;

  /**
   * \brief List of devices
   */
  DeviceMap device_list_;

  /**
   * \brief List of connections
   */
  ConnectionList connection_list_;

  /**
   *  \brief Lock for applications list
   */
  mutable sync_primitives::Lock connection_list_lock_;
  mutable sync_primitives::Lock connection_handler_observer_lock_;

  /**
   * \brief Cleans connection list on destruction
   */
  utils::StlMapDeleter<ConnectionList> connection_list_deleter_;

#ifdef BUILD_TESTS
  // Methods for test usage
 public:
  ConnectionList &getConnectionList();
  void addDeviceConnection(
    const transport_manager::DeviceInfo &device_info,
    const transport_manager::ConnectionUID &connection_id);
#endif
 private:
  FRIEND_BASE_SINGLETON_CLASS(ConnectionHandlerImpl);
  DISALLOW_COPY_AND_ASSIGN(ConnectionHandlerImpl);
};
}  // namespace connection_handler
#endif  // SRC_COMPONENTS_CONNECTION_HANDLER_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_IMPL_H_