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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
|
// SDLProtocol.m
//
#import "SDLFunctionID.h"
#import "SDLAbstractTransport.h"
#import "SDLMacros.h"
#import "SDLGlobals.h"
#import "SDLPrioritizedObjectCollection.h"
#import "SDLProtocol.h"
#import "SDLProtocolHeader.h"
#import "SDLProtocolMessage.h"
#import "SDLProtocolMessageDisassembler.h"
#import "SDLProtocolReceivedMessageRouter.h"
#import "SDLRPCNotification.h"
#import "SDLRPCPayload.h"
#import "SDLRPCRequest.h"
#import "SDLRPCResponse.h"
#import "SDLSecurityType.h"
#import "SDLTimer.h"
#import "SDLV2ProtocolHeader.h"
NSString *const SDLProtocolSecurityErrorDomain = @"com.sdl.protocol.security";
#pragma mark - SDLProtocol Private Interface
typedef NSNumber SDLServiceTypeBox;
NS_ASSUME_NONNULL_BEGIN
@interface SDLProtocol () {
UInt32 _messageID;
dispatch_queue_t _receiveQueue;
dispatch_queue_t _sendQueue;
SDLPrioritizedObjectCollection *_prioritizedCollection;
}
@property (strong, nonatomic) NSMutableData *receiveBuffer;
@property (nullable, strong, nonatomic) SDLProtocolReceivedMessageRouter *messageRouter;
@property (strong, nonatomic) NSMutableDictionary<SDLServiceTypeBox *, SDLProtocolHeader *> *serviceHeaders;
@end
#pragma mark - SDLProtocol Implementation
@implementation SDLProtocol
#pragma mark - Lifecycle
- (instancetype)init {
if (self = [super init]) {
_messageID = 0;
_receiveQueue = dispatch_queue_create("com.sdl.protocol.receive", DISPATCH_QUEUE_SERIAL);
_sendQueue = dispatch_queue_create("com.sdl.protocol.transmit", DISPATCH_QUEUE_SERIAL);
_prioritizedCollection = [[SDLPrioritizedObjectCollection alloc] init];
_serviceHeaders = [[NSMutableDictionary alloc] init];
_messageRouter = [[SDLProtocolReceivedMessageRouter alloc] init];
_messageRouter.delegate = self;
}
return self;
}
- (void)dealloc {
[SDLDebugTool logInfo:@"SDLProtocol Dealloc" withType:SDLDebugType_Transport_iAP toOutput:SDLDebugOutput_All toGroup:self.debugConsoleGroupName];
}
#pragma mark - Service metadata
- (UInt8)sdl_retrieveSessionIDforServiceType:(SDLServiceType)serviceType {
SDLProtocolHeader *header = self.serviceHeaders[@(serviceType)];
if (header == nil) {
NSString *logMessage = [NSString stringWithFormat:@"Warning: Tried to retrieve sessionID for serviceType %i, but no header is saved for that service type", serviceType];
[SDLDebugTool logInfo:logMessage withType:SDLDebugType_Protocol toOutput:SDLDebugOutput_File | SDLDebugOutput_DeviceConsole toGroup:self.debugConsoleGroupName];
}
return header.sessionID;
}
- (void)sendStartSessionWithType:(SDLServiceType)serviceType {
[self startServiceWithType:serviceType];
}
#pragma mark - Start Service
- (void)startServiceWithType:(SDLServiceType)serviceType {
// No encryption, just build and send the message synchronously
SDLProtocolMessage *message = [self sdl_createStartServiceMessageWithType:serviceType encrypted:NO];
[self sdl_sendDataToTransport:message.data onService:serviceType];
}
- (void)startSecureServiceWithType:(SDLServiceType)serviceType completionHandler:(void (^)(BOOL success, NSError *error))completionHandler {
[self sdl_initializeTLSEncryptionWithCompletionHandler:^(BOOL success, NSError *error) {
if (!success) {
// We can't start the service because we don't have encryption, return the error
completionHandler(success, error);
return; // from block
}
// TLS initialization succeeded. Build and send the message.
SDLProtocolMessage *message = [self sdl_createStartServiceMessageWithType:serviceType encrypted:YES];
[self sdl_sendDataToTransport:message.data onService:serviceType];
}];
}
- (SDLProtocolMessage *)sdl_createStartServiceMessageWithType:(SDLServiceType)serviceType encrypted:(BOOL)encryption {
SDLProtocolHeader *header = [SDLProtocolHeader headerForVersion:[SDLGlobals sharedGlobals].protocolVersion];
switch (serviceType) {
case SDLServiceTypeRPC: {
// Need a different header for starting the RPC service, we get the session Id from the HU, or its the same as the RPC service's
header = [SDLProtocolHeader headerForVersion:1];
if ([self sdl_retrieveSessionIDforServiceType:SDLServiceTypeRPC]) {
header.sessionID = [self sdl_retrieveSessionIDforServiceType:SDLServiceTypeRPC];
} else {
header.sessionID = 0;
}
} break;
default: {
header.sessionID = [self sdl_retrieveSessionIDforServiceType:SDLServiceTypeRPC];
} break;
}
header.frameType = SDLFrameTypeControl;
header.serviceType = serviceType;
header.frameData = SDLFrameInfoStartService;
// Sending a StartSession with the encrypted bit set causes module to initiate SSL Handshake with a ClientHello message, which should be handled by the 'processControlService' method.
header.encrypted = encryption;
return [SDLProtocolMessage messageWithHeader:header andPayload:nil];
}
- (void)sdl_initializeTLSEncryptionWithCompletionHandler:(void (^)(BOOL success, NSError *_Nullable error))completionHandler {
if (self.securityManager == nil) {
[SDLDebugTool logInfo:@"Could not start service, encryption was requested but failed because no security manager has been set."];
if (completionHandler != nil) {
completionHandler(NO, [NSError errorWithDomain:SDLProtocolSecurityErrorDomain code:SDLProtocolErrorNoSecurityManager userInfo:nil]);
}
return;
}
[self.securityManager initializeWithAppId:self.appId
completionHandler:^(NSError *_Nullable error) {
if (error) {
NSString *logString = [NSString stringWithFormat:@"Security Manager failed to initialize with error: %@", error];
[SDLDebugTool logInfo:logString];
if (completionHandler != nil) {
completionHandler(NO, error);
}
} else {
if (completionHandler != nil) {
completionHandler(YES, nil);
}
}
}];
}
#pragma mark - End Service
- (void)sendEndSessionWithType:(SDLServiceType)serviceType {
[self endServiceWithType:serviceType];
}
- (void)endServiceWithType:(SDLServiceType)serviceType {
SDLProtocolHeader *header = [SDLProtocolHeader headerForVersion:[SDLGlobals sharedGlobals].protocolVersion];
header.frameType = SDLFrameTypeControl;
header.serviceType = serviceType;
header.frameData = SDLFrameInfoEndService;
header.sessionID = [self sdl_retrieveSessionIDforServiceType:serviceType];
SDLProtocolMessage *message = [SDLProtocolMessage messageWithHeader:header andPayload:nil];
[self sdl_sendDataToTransport:message.data onService:serviceType];
}
#pragma mark - Send Data
- (void)sendRPC:(SDLRPCMessage *)message {
[self sendRPC:message encrypted:NO error:nil];
}
- (BOOL)sendRPC:(SDLRPCMessage *)message encrypted:(BOOL)encryption error:(NSError *__autoreleasing *)error {
NSParameterAssert(message != nil);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[message serializeAsDictionary:[SDLGlobals sharedGlobals].protocolVersion] options:kNilOptions error:error];
if (error != nil) {
[SDLDebugTool logInfo:[NSString stringWithFormat:@"Error encoding JSON data: %@", *error] withType:SDLDebugType_Protocol];
}
NSData *messagePayload = nil;
NSString *logMessage = [NSString stringWithFormat:@"%@", message];
[SDLDebugTool logInfo:logMessage withType:SDLDebugType_RPC toOutput:SDLDebugOutput_All toGroup:self.debugConsoleGroupName];
// Build the message payload. Include the binary header if necessary
// VERSION DEPENDENT CODE
switch ([SDLGlobals sharedGlobals].protocolVersion) {
case 1: {
// No binary header in version 1
messagePayload = jsonData;
} break;
case 2: // Fallthrough
case 3: // Fallthrough
case 4: {
// Build a binary header
// Serialize the RPC data into an NSData
SDLRPCPayload *rpcPayload = [[SDLRPCPayload alloc] init];
rpcPayload.functionID = [[[SDLFunctionID sharedInstance] functionIdForName:[message getFunctionName]] intValue];
rpcPayload.jsonData = jsonData;
rpcPayload.binaryData = message.bulkData;
// If it's a request or a response, we need to pull out the correlation ID, so we'll downcast
if ([message isKindOfClass:SDLRPCRequest.class]) {
rpcPayload.rpcType = SDLRPCMessageTypeRequest;
rpcPayload.correlationID = [((SDLRPCRequest *)message).correlationID intValue];
} else if ([message isKindOfClass:SDLRPCResponse.class]) {
rpcPayload.rpcType = SDLRPCMessageTypeResponse;
rpcPayload.correlationID = [((SDLRPCResponse *)message).correlationID intValue];
} else if ([message isKindOfClass:[SDLRPCNotification class]]) {
rpcPayload.rpcType = SDLRPCMessageTypeNotification;
} else {
NSAssert(NO, @"Unknown message type attempted to send. Type: %@", [message class]);
return NO;
}
// If we're trying to encrypt, try to have the security manager encrypt it. Return if it fails.
// TODO: (Joel F.)[2016-02-09] We should assert if the service isn't setup for encryption. See [#350](https://github.com/smartdevicelink/sdl_ios/issues/350)
messagePayload = encryption ? [self.securityManager encryptData:rpcPayload.data withError:error] : rpcPayload.data;
if (!messagePayload) {
return NO;
}
} break;
default: {
NSAssert(NO, @"Attempting to send an RPC based on an unknown version number: %@, message: %@", @([SDLGlobals sharedGlobals].protocolVersion), message);
} break;
}
// Build the protocol level header & message
SDLProtocolHeader *header = [SDLProtocolHeader headerForVersion:[SDLGlobals sharedGlobals].protocolVersion];
header.encrypted = encryption;
header.frameType = SDLFrameTypeSingle;
header.serviceType = (message.bulkData.length <= 0) ? SDLServiceTypeRPC : SDLServiceTypeBulkData;
header.frameData = SDLFrameInfoSingleFrame;
header.sessionID = [self sdl_retrieveSessionIDforServiceType:SDLServiceTypeRPC];
header.bytesInPayload = (UInt32)messagePayload.length;
// V2+ messages need to have message ID property set.
if ([SDLGlobals sharedGlobals].protocolVersion >= 2) {
[((SDLV2ProtocolHeader *)header) setMessageID:++_messageID];
}
SDLProtocolMessage *protocolMessage = [SDLProtocolMessage messageWithHeader:header andPayload:messagePayload];
// See if the message is small enough to send in one transmission. If not, break it up into smaller messages and send.
if (protocolMessage.size < [SDLGlobals sharedGlobals].maxMTUSize) {
[self sdl_logRPCSend:protocolMessage];
[self sdl_sendDataToTransport:protocolMessage.data onService:SDLServiceTypeRPC];
} else {
NSArray<SDLProtocolMessage *> *messages = [SDLProtocolMessageDisassembler disassemble:protocolMessage withLimit:[SDLGlobals sharedGlobals].maxMTUSize];
for (SDLProtocolMessage *smallerMessage in messages) {
[self sdl_logRPCSend:smallerMessage];
[self sdl_sendDataToTransport:smallerMessage.data onService:SDLServiceTypeRPC];
}
}
return YES;
}
// SDLRPCRequest in from app -> SDLProtocolMessage out to transport layer.
- (void)sendRPCRequest:(SDLRPCRequest *)rpcRequest {
[self sendRPC:rpcRequest];
}
- (void)sdl_logRPCSend:(SDLProtocolMessage *)message {
NSString *logMessage = [NSString stringWithFormat:@"Sending : %@", message];
[SDLDebugTool logInfo:logMessage withType:SDLDebugType_Protocol toOutput:SDLDebugOutput_File | SDLDebugOutput_DeviceConsole toGroup:self.debugConsoleGroupName];
}
// Use for normal messages
- (void)sdl_sendDataToTransport:(NSData *)data onService:(NSInteger)priority {
[_prioritizedCollection addObject:data withPriority:priority];
// TODO: (Joel F.)[2016-02-11] Autoreleasepool?
dispatch_async(_sendQueue, ^{
NSData *dataToTransmit = nil;
while (dataToTransmit = (NSData *)[_prioritizedCollection nextObject]) {
[self.transport sendData:dataToTransmit];
};
});
}
- (void)sendRawData:(NSData *)data withServiceType:(SDLServiceType)serviceType {
[self sdl_sendRawData:data onService:serviceType encryption:NO];
}
- (void)sendEncryptedRawData:(NSData *)data onService:(SDLServiceType)serviceType {
[self sdl_sendRawData:data onService:serviceType encryption:YES];
}
- (void)sdl_sendRawData:(NSData *)data onService:(SDLServiceType)service encryption:(BOOL)encryption {
SDLV2ProtocolHeader *header = [[SDLV2ProtocolHeader alloc] initWithVersion:[SDLGlobals sharedGlobals].protocolVersion];
header.encrypted = encryption;
header.frameType = SDLFrameTypeSingle;
header.serviceType = service;
header.sessionID = [self sdl_retrieveSessionIDforServiceType:service];
header.messageID = ++_messageID;
if (encryption && data.length) {
NSError *encryptError = nil;
data = [self.securityManager encryptData:data withError:&encryptError];
if (encryptError) {
NSString *encryptLogString = [NSString stringWithFormat:@"Error attempting to encrypt raw data for service: %@, error: %@", @(service), encryptError];
[SDLDebugTool logInfo:encryptLogString];
}
}
header.bytesInPayload = (UInt32)data.length;
SDLProtocolMessage *message = [SDLProtocolMessage messageWithHeader:header andPayload:data];
if (message.size < [SDLGlobals sharedGlobals].maxMTUSize) {
[self sdl_logRPCSend:message];
[self sdl_sendDataToTransport:message.data onService:header.serviceType];
} else {
NSArray<SDLProtocolMessage *> *messages = [SDLProtocolMessageDisassembler disassemble:message withLimit:[SDLGlobals sharedGlobals].maxMTUSize];
for (SDLProtocolMessage *smallerMessage in messages) {
[self sdl_logRPCSend:smallerMessage];
[self sdl_sendDataToTransport:smallerMessage.data onService:header.serviceType];
}
}
}
#pragma mark - Receive and Process Data
// Turn received bytes into message objects.
- (void)handleBytesFromTransport:(NSData *)receivedData {
// Initialize the receive buffer which will contain bytes while messages are constructed.
if (self.receiveBuffer == nil) {
self.receiveBuffer = [NSMutableData dataWithCapacity:(4 * [SDLGlobals sharedGlobals].maxMTUSize)];
}
// Save the data
[self.receiveBuffer appendData:receivedData];
[self processMessages];
}
- (void)processMessages {
NSMutableString *logMessage = [[NSMutableString alloc] init];
UInt8 incomingVersion = [SDLProtocolMessage determineVersion:self.receiveBuffer];
// If we have enough bytes, create the header.
SDLProtocolHeader *header = [SDLProtocolHeader headerForVersion:incomingVersion];
NSUInteger headerSize = header.size;
if (self.receiveBuffer.length >= headerSize) {
[header parse:self.receiveBuffer];
} else {
return;
}
// If we have enough bytes, finish building the message.
SDLProtocolMessage *message = nil;
NSUInteger payloadSize = header.bytesInPayload;
NSUInteger messageSize = headerSize + payloadSize;
if (self.receiveBuffer.length >= messageSize) {
NSUInteger payloadOffset = headerSize;
NSUInteger payloadLength = payloadSize;
NSData *payload = [self.receiveBuffer subdataWithRange:NSMakeRange(payloadOffset, payloadLength)];
// If the message in encrypted and there is payload, try to decrypt it
if (header.encrypted && payload.length) {
NSError *decryptError = nil;
payload = [self.securityManager decryptData:payload withError:&decryptError];
if (decryptError) {
NSString *decryptLogMessage = [NSString stringWithFormat:@"Error attempting to decrypt a payload with error: %@", decryptError];
[SDLDebugTool logInfo:decryptLogMessage];
return;
}
}
message = [SDLProtocolMessage messageWithHeader:header andPayload:payload];
[logMessage appendFormat:@"message complete. %@", message];
[SDLDebugTool logInfo:logMessage withType:SDLDebugType_Protocol toOutput:SDLDebugOutput_File | SDLDebugOutput_DeviceConsole toGroup:self.debugConsoleGroupName];
} else {
// Need to wait for more bytes.
[logMessage appendFormat:@"header complete. message incomplete, waiting for %ld more bytes. Header:%@", (long)(messageSize - self.receiveBuffer.length), header];
[SDLDebugTool logInfo:logMessage withType:SDLDebugType_Protocol toOutput:SDLDebugOutput_File | SDLDebugOutput_DeviceConsole toGroup:self.debugConsoleGroupName];
return;
}
// Need to maintain the receiveBuffer, remove the bytes from it which we just processed.
self.receiveBuffer = [[self.receiveBuffer subdataWithRange:NSMakeRange(messageSize, self.receiveBuffer.length - messageSize)] mutableCopy];
// Pass on the message to the message router.
dispatch_async(_receiveQueue, ^{
[self.messageRouter handleReceivedMessage:message];
});
// Call recursively until the buffer is empty or incomplete message is encountered
if (self.receiveBuffer.length > 0) {
[self processMessages];
}
}
- (void)handleProtocolStartSessionACK:(SDLProtocolHeader *)header {
switch (header.serviceType) {
case SDLServiceTypeRPC: {
[SDLGlobals sharedGlobals].maxHeadUnitVersion = header.version;
} break;
default:
break;
}
// Store the header of this service away for future use
self.serviceHeaders[@(header.serviceType)] = [header copy];
// Pass along to all the listeners
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(handleProtocolStartSessionACK:)]) {
[listener handleProtocolStartSessionACK:header];
}
if ([listener respondsToSelector:@selector(handleProtocolStartSessionACK:sessionID:version:)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[listener handleProtocolStartSessionACK:header.serviceType
sessionID:header.sessionID
version:header.version];
#pragma clang diagnostic pop
}
}
}
- (void)handleProtocolStartSessionNACK:(SDLServiceType)serviceType {
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(handleProtocolStartSessionNACK:)]) {
[listener handleProtocolStartSessionNACK:serviceType];
}
}
}
- (void)handleProtocolEndSessionACK:(SDLServiceType)serviceType {
// Remove the session id
[self.serviceHeaders removeObjectForKey:@(serviceType)];
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(handleProtocolEndSessionACK:)]) {
[listener handleProtocolEndSessionACK:serviceType];
}
}
}
- (void)handleProtocolEndSessionNACK:(SDLServiceType)serviceType {
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(handleProtocolEndSessionNACK:)]) {
[listener handleProtocolEndSessionNACK:serviceType];
}
}
}
- (void)handleHeartbeatForSession:(Byte)session {
// Respond with a heartbeat ACK
SDLProtocolHeader *header = [SDLProtocolHeader headerForVersion:[SDLGlobals sharedGlobals].protocolVersion];
header.frameType = SDLFrameTypeControl;
header.serviceType = SDLServiceTypeControl;
header.frameData = SDLFrameInfoHeartbeatACK;
header.sessionID = session;
SDLProtocolMessage *message = [SDLProtocolMessage messageWithHeader:header andPayload:nil];
[self sdl_sendDataToTransport:message.data onService:header.serviceType];
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(handleHeartbeatForSession:)]) {
[listener handleHeartbeatForSession:session];
}
}
}
- (void)handleHeartbeatACK {
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(handleHeartbeatACK)]) {
[listener handleHeartbeatACK];
}
}
}
- (void)onProtocolMessageReceived:(SDLProtocolMessage *)msg {
// Control service (but not control frame type) messages are TLS handshake messages
if (msg.header.serviceType == SDLServiceTypeControl) {
[self sdl_processSecurityMessage:msg];
return;
}
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(onProtocolMessageReceived:)]) {
[listener onProtocolMessageReceived:msg];
}
}
}
- (void)onProtocolOpened {
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(onProtocolOpened)]) {
[listener onProtocolOpened];
}
}
}
- (void)onProtocolClosed {
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(onProtocolClosed)]) {
[listener onProtocolClosed];
}
}
}
- (void)onError:(NSString *)info exception:(NSException *)e {
for (id<SDLProtocolListener> listener in self.protocolDelegateTable.allObjects) {
if ([listener respondsToSelector:@selector(onError:exception:)]) {
[listener onError:info exception:e];
}
}
}
#pragma mark - TLS Handshake
// TODO: These should be split out to a separate class to be tested properly
- (void)sdl_processSecurityMessage:(SDLProtocolMessage *)clientHandshakeMessage {
if (self.securityManager == nil) {
NSString *logString = [NSString stringWithFormat:@"Failed to process security message because no security manager is set. Message: %@", clientHandshakeMessage];
[SDLDebugTool logInfo:logString];
return;
}
// Misformatted handshake message, something went wrong
if (clientHandshakeMessage.payload.length <= 12) {
NSString *logString = [NSString stringWithFormat:@"Security message is malformed, less than 12 bytes. It does not have a protocol header. Message: %@", clientHandshakeMessage];
[SDLDebugTool logInfo:logString];
}
// Tear off the binary header of the client protocol message to get at the actual TLS handshake
// TODO: (Joel F.)[2016-02-15] Should check for errors
NSData *clientHandshakeData = [clientHandshakeMessage.payload subdataWithRange:NSMakeRange(12, (clientHandshakeMessage.payload.length - 12))];
// Ask the security manager for server data based on the client data sent
NSError *handshakeError = nil;
NSData *serverHandshakeData = [self.securityManager runHandshakeWithClientData:clientHandshakeData error:&handshakeError];
// If the handshake went bad and the security library ain't happy, send over the failure to the module. This should result in an ACK with encryption off.
SDLProtocolMessage *serverSecurityMessage = nil;
if (serverHandshakeData == nil) {
NSString *logString = [NSString stringWithFormat:@"Error running TLS handshake procedure. Sending error to module. Error: %@", handshakeError];
[SDLDebugTool logInfo:logString];
serverSecurityMessage = [self.class sdl_serverSecurityFailedMessageWithClientMessageHeader:clientHandshakeMessage.header messageId:++_messageID];
} else {
// The handshake went fine, send the module the remaining handshake data
serverSecurityMessage = [self.class sdl_serverSecurityHandshakeMessageWithData:serverHandshakeData clientMessageHeader:clientHandshakeMessage.header messageId:++_messageID];
}
// Send the response or error message. If it's an error message, the module will ACK the Start Service without encryption. If it's a TLS handshake message, the module will ACK with encryption
[self sdl_sendDataToTransport:serverSecurityMessage.data onService:SDLServiceTypeControl];
}
+ (SDLProtocolMessage *)sdl_serverSecurityHandshakeMessageWithData:(NSData *)data clientMessageHeader:(SDLProtocolHeader *)clientHeader messageId:(UInt32)messageId {
// This can't possibly be a v1 header because v1 does not have control protocol messages
SDLV2ProtocolHeader *serverMessageHeader = [SDLProtocolHeader headerForVersion:clientHeader.version];
serverMessageHeader.encrypted = NO;
serverMessageHeader.frameType = SDLFrameTypeSingle;
serverMessageHeader.serviceType = SDLServiceTypeControl;
serverMessageHeader.frameData = SDLFrameInfoSingleFrame;
serverMessageHeader.sessionID = clientHeader.sessionID;
serverMessageHeader.messageID = messageId;
// For a control service packet, we need a binary header with a function ID corresponding to what type of packet we're sending.
SDLRPCPayload *serverTLSPayload = [[SDLRPCPayload alloc] init];
serverTLSPayload.functionID = 0x01; // TLS Handshake message
serverTLSPayload.rpcType = 0x00;
serverTLSPayload.correlationID = 0x00;
serverTLSPayload.binaryData = data;
NSData *binaryData = serverTLSPayload.data;
serverMessageHeader.bytesInPayload = (UInt32)binaryData.length;
return [SDLProtocolMessage messageWithHeader:serverMessageHeader andPayload:binaryData];
}
+ (SDLProtocolMessage *)sdl_serverSecurityFailedMessageWithClientMessageHeader:(SDLProtocolHeader *)clientHeader messageId:(UInt32)messageId {
// This can't possibly be a v1 header because v1 does not have control protocol messages
SDLV2ProtocolHeader *serverMessageHeader = [SDLProtocolHeader headerForVersion:clientHeader.version];
serverMessageHeader.encrypted = NO;
serverMessageHeader.frameType = SDLFrameTypeSingle;
serverMessageHeader.serviceType = SDLServiceTypeControl;
serverMessageHeader.frameData = SDLFrameInfoSingleFrame;
serverMessageHeader.sessionID = clientHeader.sessionID;
serverMessageHeader.messageID = messageId;
// For a control service packet, we need a binary header with a function ID corresponding to what type of packet we're sending.
SDLRPCPayload *serverTLSPayload = [[SDLRPCPayload alloc] init];
serverTLSPayload.functionID = 0x02; // TLS Error message
serverTLSPayload.rpcType = 0x02;
serverTLSPayload.correlationID = 0x00;
NSData *binaryData = serverTLSPayload.data;
serverMessageHeader.bytesInPayload = (UInt32)binaryData.length;
// TODO: (Joel F.)[2016-02-15] This is supposed to have some JSON data and json data size
return [SDLProtocolMessage messageWithHeader:serverMessageHeader andPayload:binaryData];
}
@end
NS_ASSUME_NONNULL_END
|