/
iSCSIDaemon.c
2190 lines (1720 loc) · 78.9 KB
/
iSCSIDaemon.c
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2016, Nareg Sinenian
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 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.
*/
// BSD includes
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/event.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <asl.h>
#include <assert.h>
#include <pthread.h>
// Foundation includes
#include <launch.h>
#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>
// Mach kernel includes
#include <mach/mach_port.h>
#include <mach/mach_init.h>
#include <mach/mach_interface.h>
// I/O Kit includes
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
// iSCSI includes
#include "iSCSISession.h"
#include "iSCSIDaemonInterfaceShared.h"
#include "iSCSIPreferences.h"
#include "iSCSIDA.h"
#include "iSCSIAuthRights.h"
// Used to notify daemon of power state changes
io_connect_t powerPlaneRoot;
io_object_t powerNotifier;
IONotificationPortRef powerNotifyPortRef;
// Used to fire discovery timer at specified intervals
CFRunLoopTimerRef discoveryTimer = NULL;
// Used by discovery to notify the main daemon thread that data is ready
CFRunLoopSourceRef discoverySource = NULL;
// Used to point to discovery records
CFDictionaryRef discoveryRecords = NULL;
// Mutex lock when discovery is running
pthread_mutex_t discoveryMutex = PTHREAD_MUTEX_INITIALIZER;
/*! Server-side timeouts (in milliseconds) for send()/recv(). */
static const int kiSCSIDaemonTimeoutMilliSec = 250;
/*! Dictionary used to keep track of portals and targets that
* were active when the system goes to sleep. */
CFMutableDictionaryRef activeTargets = NULL;
// Mutex lock used when preferences are being synchronized
pthread_mutex_t preferencesMutex = PTHREAD_MUTEX_INITIALIZER;
/*! Preferences object used to syncrhonize iSCSI preferences. */
iSCSIPreferencesRef preferences = NULL;
/*! Incoming request information struct. */
struct iSCSIDIncomingRequestInfo * reqInfo = NULL;
/*! Used to manage iSCSI sessions. */
iSCSISessionManagerRef sessionManager = NULL;
struct iSCSIDIncomingRequestInfo {
CFSocketRef socket;
CFRunLoopSourceRef socketSourceRead;
int fd;
};
struct iSCSIDQueueLoginForTargetPortal {
iSCSITargetRef target;
iSCSIPortalRef portal;
};
const iSCSIDMsgLoginRsp iSCSIDMsgLoginRspInit = {
.funcCode = kiSCSIDLogin,
.errorCode = 0,
.statusCode = (UInt8)kiSCSILoginInvalidStatusCode
};
const iSCSIDMsgLogoutRsp iSCSIDMsgLogoutRspInit = {
.funcCode = kiSCSIDLogout,
.errorCode = 0,
.statusCode = (UInt8)kiSCSILogoutInvalidStatusCode
};
const iSCSIDMsgCreateArrayOfActiveTargetsRsp iSCSIDMsgCreateArrayOfActiveTargetsRspInit = {
.funcCode = kiSCSIDCreateArrayOfActiveTargets,
.errorCode = 0,
.dataLength = 0
};
const iSCSIDMsgCreateArrayOfActivePortalsForTargetRsp iSCSIDMsgCreateArrayOfActivePortalsForTargetRspInit = {
.funcCode = kiSCSIDCreateArrayOfActivePortalsForTarget,
.errorCode = 0,
.dataLength = 0
};
const iSCSIDMsgIsTargetActiveRsp iSCSIDMsgIsTargetActiveRspInit = {
.funcCode = kiSCSIDIsTargetActive,
.active = false
};
const iSCSIDMsgIsPortalActiveRsp iSCSIDMsgIsPortalActiveRspInit = {
.funcCode = kiSCSIDIsPortalActive,
.active = false
};
const iSCSIDMsgQueryTargetForAuthMethodRsp iSCSIDMsgQueryTargetForAuthMethodRspInit = {
.funcCode = kiSCSIDQueryTargetForAuthMethod,
.errorCode = 0,
.statusCode = 0,
.authMethod = 0
};
const iSCSIDMsgCreateCFPropertiesForSessionRsp iSCSIDMsgCreateCFPropertiesForSessionRspInit = {
.funcCode = kiSCSIDCreateCFPropertiesForSession,
.errorCode = 0,
.dataLength = 0
};
const iSCSIDMsgCreateCFPropertiesForConnectionRsp iSCSIDMsgCreateCFPropertiesForConnectionRspInit = {
.funcCode = kiSCSIDCreateCFPropertiesForConnection,
.errorCode = 0,
.dataLength = 0
};
const iSCSIDMsgUpdateDiscoveryRsp iSCSIDMsgUpdateDiscoveryRspInit = {
.funcCode = kiSCSIDUpdateDiscovery,
.errorCode = 0,
};
const iSCSIDMsgPreferencesIOLockAndSyncRsp iSCSIDMsgPreferencesIOLockAndSyncRspInit = {
.funcCode = kiSCSIDPreferencesIOLockAndSync,
.errorCode = 0,
};
const iSCSIDMsgPreferencesIOUnlockAndSyncRsp iSCSIDMsgPreferencesIOUnlockAndSyncRspInit = {
.funcCode = kiSCSIDPreferencesIOUnlockAndSync,
.errorCode = 0,
};
const iSCSIDMsgSetSharedSecretRsp iSCSIDMsgSetSharedSecretRspInit = {
.funcCode = kiSCSIDSetSharedSecret,
.errorCode = 0,
};
const iSCSIDMsgRemoveSharedSecretRsp iSCSIDMsgRemoveSharedSecretRspInit = {
.funcCode = kiSCSIDRemoveSharedSecret,
.errorCode = 0,
};
/*! Used for the logout process. */
typedef struct iSCSIDLogoutContext {
int fd;
DASessionRef diskSession;
iSCSIPortalRef portal;
errno_t errorCode;
} iSCSIDLogoutContext;
/*! Helper function. Updates the preferences object using application values. */
void iSCSIDUpdatePreferencesFromAppValues()
{
if(preferences != NULL)
iSCSIPreferencesRelease(preferences);
preferences = iSCSIPreferencesCreateFromAppValues(CFSTR(CF_PREFERENCES_APP_ID));
}
iSCSISessionConfigRef iSCSIDCreateSessionConfig(CFStringRef targetIQN)
{
iSCSIMutableSessionConfigRef config = iSCSISessionConfigCreateMutable();
iSCSISessionConfigSetErrorRecoveryLevel(config,iSCSIPreferencesGetErrorRecoveryLevelForTarget(preferences,targetIQN));
iSCSISessionConfigSetMaxConnections(config,iSCSIPreferencesGetMaxConnectionsForTarget(preferences,targetIQN));
return config;
}
iSCSIConnectionConfigRef iSCSIDCreateConnectionConfig(CFStringRef targetIQN,
CFStringRef portalAddress)
{
iSCSIMutableConnectionConfigRef config = iSCSIConnectionConfigCreateMutable();
enum iSCSIDigestTypes digestType;
digestType = iSCSIPreferencesGetDataDigestForTarget(preferences,targetIQN);
if(digestType == kiSCSIDigestInvalid)
digestType = kiSCSIDigestNone;
iSCSIConnectionConfigSetDataDigest(config,digestType);
digestType = iSCSIPreferencesGetHeaderDigestForTarget(preferences,targetIQN);
if(digestType == kiSCSIDigestInvalid)
digestType = kiSCSIDigestNone;
iSCSIConnectionConfigSetHeaderDigest(config,digestType);
return config;
}
iSCSIAuthRef iSCSIDCreateAuthenticationForTarget(CFStringRef targetIQN)
{
iSCSIAuthRef auth;
enum iSCSIAuthMethods authMethod = iSCSIPreferencesGetTargetAuthenticationMethod(preferences,targetIQN);
if(authMethod == kiSCSIAuthMethodCHAP)
{
CFStringRef name = iSCSIPreferencesCopyTargetCHAPName(preferences,targetIQN);
CFStringRef sharedSecret = iSCSIKeychainCopyCHAPSecretForNode(targetIQN);
if(!name) {
asl_log(NULL,NULL,ASL_LEVEL_WARNING,"target CHAP name for target has not been set, reverting to no authentication");
auth = iSCSIAuthCreateNone();
}
else if(!sharedSecret) {
asl_log(NULL,NULL,ASL_LEVEL_WARNING,"target CHAP secret is missing or insufficient privileges to system keychain, reverting to no authentication");
auth = iSCSIAuthCreateNone();
}
else {
auth = iSCSIAuthCreateCHAP(name,sharedSecret);
}
if(name)
CFRelease(name);
if(sharedSecret)
CFRelease(sharedSecret);
}
else
auth = iSCSIAuthCreateNone();
return auth;
}
iSCSIAuthRef iSCSIDCreateAuthenticationForInitiator()
{
iSCSIAuthRef auth;
enum iSCSIAuthMethods authMethod = iSCSIPreferencesGetInitiatorAuthenticationMethod(preferences);
if(authMethod == kiSCSIAuthMethodCHAP)
{
CFStringRef name = iSCSIPreferencesCopyInitiatorCHAPName(preferences);
CFStringRef initiatorIQN = iSCSIPreferencesCopyInitiatorIQN(preferences);
CFStringRef sharedSecret = iSCSIKeychainCopyCHAPSecretForNode(initiatorIQN);
CFRelease(initiatorIQN);
if(!name) {
asl_log(NULL,NULL,ASL_LEVEL_WARNING,"initiator CHAP name for target has not been set, reverting to no authentication.");
auth = iSCSIAuthCreateNone();
}
else if(!sharedSecret) {
asl_log(NULL,NULL,ASL_LEVEL_WARNING,"initiator CHAP secret is missing or insufficient privileges to system keychain, reverting to no authentication.");
auth = iSCSIAuthCreateNone();
}
else {
auth = iSCSIAuthCreateCHAP(name,sharedSecret);
}
if(name)
CFRelease(name);
if(sharedSecret)
CFRelease(sharedSecret);
}
else
auth = iSCSIAuthCreateNone();
return auth;
}
errno_t iSCSIDLoginCommon(SessionIdentifier sessionId,
iSCSIMutableTargetRef target,
iSCSIPortalRef portal,
enum iSCSILoginStatusCode * statusCode)
{
errno_t error = 0;
iSCSISessionConfigRef sessCfg = NULL;
iSCSIConnectionConfigRef connCfg = NULL;
iSCSIAuthRef initiatorAuth = NULL, targetAuth = NULL;
ConnectionIdentifier connectionId = kiSCSIInvalidConnectionId;
*statusCode = kiSCSILoginInvalidStatusCode;
CFStringRef targetIQN = iSCSITargetGetIQN(target);
// If session needs to be logged in, copy session config from property list
if(sessionId == kiSCSIInvalidSessionId)
if(!(sessCfg = iSCSIDCreateSessionConfig(targetIQN)))
sessCfg = iSCSISessionConfigCreateMutable();
// Get connection configuration from property list, create one if needed
if(!(connCfg = iSCSIDCreateConnectionConfig(targetIQN,iSCSIPortalGetAddress(portal))))
connCfg = iSCSIConnectionConfigCreateMutable();
// Get authentication configuration from property list, create one if needed
if(!(targetAuth = iSCSIDCreateAuthenticationForTarget(targetIQN)))
targetAuth = iSCSIAuthCreateNone();
if(!(initiatorAuth = iSCSIDCreateAuthenticationForInitiator()))
initiatorAuth = iSCSIAuthCreateNone();
// Do either session or connection login
if(sessionId == kiSCSIInvalidSessionId)
error = iSCSISessionLogin(sessionManager,target,portal,initiatorAuth,targetAuth,sessCfg,connCfg,&sessionId,&connectionId,statusCode);
else
error = iSCSISessionAddConnection(sessionManager,sessionId,portal,initiatorAuth,targetAuth,connCfg,&connectionId,statusCode);
// Log error message
if(error) {
CFStringRef errorString = CFStringCreateWithFormat(
kCFAllocatorDefault,0,
CFSTR("login to %@,%@:%@ failed: %s\n"),
targetIQN,
iSCSIPortalGetAddress(portal),
iSCSIPortalGetPort(portal),
strerror(error));
CFIndex errorStringLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(errorString),kCFStringEncodingASCII) + sizeof('\0');
char errorStringBuffer[errorStringLength];
CFStringGetCString(errorString,errorStringBuffer,errorStringLength,kCFStringEncodingASCII);
asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", errorStringBuffer);
CFRelease(errorString);
}
// Update target alias in preferences (if one was furnished)
else
{
iSCSIPreferencesSetTargetAlias(preferences,targetIQN,iSCSITargetGetAlias(target));
iSCSIPreferencesSynchronzeAppValues(preferences);
}
if(sessCfg)
iSCSISessionConfigRelease(sessCfg);
if(connCfg)
iSCSIConnectionConfigRelease(connCfg);
if(targetAuth)
iSCSIAuthRelease(targetAuth);
if(initiatorAuth)
iSCSIAuthRelease(initiatorAuth);
return error;
}
errno_t iSCSIDLoginAllPortals(iSCSIMutableTargetRef target,
enum iSCSILoginStatusCode * statusCode)
{
CFIndex activeConnections = 0;
CFIndex maxConnections = 0;
// Error code to return to daemon's client
errno_t errorCode = 0;
*statusCode = kiSCSILoginInvalidStatusCode;
CFStringRef targetIQN = iSCSITargetGetIQN(target);
SessionIdentifier sessionId = iSCSISessionGetSessionIdForTarget(sessionManager,targetIQN);
// Set initial values for maxConnections and activeConnections
if(sessionId == kiSCSIInvalidSessionId)
//TODO: change to the maximum value that will be supported by this initiator
maxConnections = 1;
else {
// If session exists, get the max connections and active connections
CFDictionaryRef properties = iSCSISessionCopyCFPropertiesForTarget(sessionManager,target);
if(properties) {
// Get max connections from property list
CFNumberRef number = CFDictionaryGetValue(properties,kRFC3720_Key_MaxConnections);
CFNumberGetValue(number,kCFNumberSInt32Type,&maxConnections);
CFRelease(properties);
CFArrayRef connections = iSCSISessionCopyArrayOfConnectionIds(sessionManager,sessionId);
if(connections) {
activeConnections = CFArrayGetCount(connections);
CFRelease(connections);
}
}
}
// Add portals to the session until we've run out of portals to add or
// reached the maximum connection limit
CFStringRef portalAddress = NULL;
CFArrayRef portals = iSCSIPreferencesCreateArrayOfPortalsForTarget(preferences,targetIQN);
CFIndex portalIdx = 0;
CFIndex portalCount = CFArrayGetCount(portals);
while( (activeConnections < maxConnections) && portalIdx < portalCount )
{
portalAddress = CFArrayGetValueAtIndex(portals,portalIdx);
// Get portal object and login
iSCSIPortalRef portal = iSCSIPreferencesCopyPortalForTarget(preferences,targetIQN,portalAddress);
errorCode = iSCSIDLoginCommon(sessionId,target,portal,statusCode);
iSCSIPortalRelease(portal);
// Quit if there was an error communicating with the daemon
if(errorCode)
break;
activeConnections++;
portalIdx++;
// Determine how many connections this session supports
sessionId = iSCSISessionGetSessionIdForTarget(sessionManager,iSCSITargetGetIQN(target));
// If this was the first connection of the session, get the number of
// allowed maximum connections
if(activeConnections == 1) {
CFDictionaryRef properties = iSCSISessionCopyCFPropertiesForTarget(sessionManager,target);
if(properties) {
// Get max connections from property list
CFNumberRef number = CFDictionaryGetValue(properties,kRFC3720_Key_MaxConnections);
CFNumberGetValue(number,kCFNumberSInt32Type,&maxConnections);
CFRelease(properties);
}
}
};
if(portals)
CFRelease(portals);
return errorCode;
}
errno_t iSCSIDLoginWithPortal(iSCSIMutableTargetRef target,
iSCSIPortalRef portal,
enum iSCSILoginStatusCode * statusCode)
{
// Check for active sessions before attempting loginb
SessionIdentifier sessionId = kiSCSIInvalidSessionId;
ConnectionIdentifier connectionId = kiSCSIInvalidConnectionId;
*statusCode = kiSCSILoginInvalidStatusCode;
errno_t errorCode = 0;
CFStringRef targetIQN = iSCSITargetGetIQN(target);
sessionId = iSCSISessionGetSessionIdForTarget(sessionManager,targetIQN);
// Existing session, add a connection
if(sessionId != kiSCSIInvalidSessionId) {
connectionId = iSCSISessionGetConnectionIdForPortal(sessionManager,sessionId,portal);
// If there's an active session display error otherwise login
if(connectionId != kiSCSIInvalidConnectionId)
{} //iSCSICtlDisplayError("The specified target has an active session over the specified portal.");
else {
// See if the session can support an additional connection
CFDictionaryRef properties = iSCSISessionCopyCFPropertiesForTarget(sessionManager,target);
if(properties) {
// Get max connections from property list
UInt32 maxConnections;
CFNumberRef number = CFDictionaryGetValue(properties,kRFC3720_Key_MaxConnections);
CFNumberGetValue(number,kCFNumberSInt32Type,&maxConnections);
CFRelease(properties);
CFArrayRef connections = iSCSISessionCopyArrayOfConnectionIds(sessionManager,sessionId);
if(connections)
{
CFIndex activeConnections = CFArrayGetCount(connections);
if(activeConnections == maxConnections)
{} //iSCSICtlDisplayError("The active session cannot support additional connections.");
else
errorCode = iSCSIDLoginCommon(sessionId,target,portal,statusCode);
CFRelease(connections);
}
}
}
}
else // Leading login
errorCode = iSCSIDLoginCommon(sessionId,target,portal,statusCode);
return errorCode;
}
errno_t iSCSIDLogin(int fd,iSCSIDMsgLoginCmd * cmd)
{
CFDataRef targetData = NULL, portalData = NULL, authorizationData = NULL;
iSCSIDaemonRecvMsg(fd,0,&authorizationData,cmd->authLength,&targetData,cmd->targetLength,&portalData,cmd->portalLength,NULL);
iSCSIMutableTargetRef target = NULL;
errno_t errorCode = 0;
if(targetData) {
iSCSITargetRef targetTemp = iSCSITargetCreateWithData(targetData);
target = iSCSITargetCreateMutableCopy(targetTemp);
iSCSITargetRelease(targetTemp);
CFRelease(targetData);
}
iSCSIPortalRef portal = NULL;
if(portalData) {
portal = iSCSIPortalCreateWithData(portalData);
CFRelease(portalData);
}
AuthorizationRef authorization = NULL;
// If authorization data is valid, create authorization object
if(authorizationData) {
AuthorizationExternalForm authorizationExtForm;
CFDataGetBytes(authorizationData,
CFRangeMake(0,kAuthorizationExternalFormLength),
(UInt8 *)&authorizationExtForm.bytes);
AuthorizationCreateFromExternalForm(&authorizationExtForm,&authorization);
CFRelease(authorizationData);
}
// If authorization object is valid, get the necessary rights
if(authorization) {
if(iSCSIAuthRightsAcquire(authorization,kiSCSIAuthLoginRight) != errAuthorizationSuccess)
errorCode = EAUTH;
AuthorizationFree(authorization,kAuthorizationFlagDefaults);
}
else
errorCode = EINVAL;
// If portal and target are valid, login with portal. Otherwise login to
// target using all defined portals.
enum iSCSILoginStatusCode statusCode = kiSCSILoginInvalidStatusCode;
// Synchronize property list
iSCSIDUpdatePreferencesFromAppValues();
if(!errorCode) {
if(target && portal)
errorCode = iSCSIDLoginWithPortal(target,portal,&statusCode);
else if(target)
errorCode = iSCSIDLoginAllPortals(target,&statusCode);
else
errorCode = EINVAL;
}
// Compose a response to send back to the client
iSCSIDMsgLoginRsp rsp = iSCSIDMsgLoginRspInit;
rsp.errorCode = errorCode;
rsp.statusCode = statusCode;
if(target)
iSCSITargetRelease(target);
if(portal)
iSCSIPortalRelease(portal);
if(send(fd,&rsp,sizeof(rsp),0) != sizeof(rsp))
return EAGAIN;
return 0;
}
void iSCSIDLogoutComplete(iSCSITargetRef target,enum iSCSIDAOperationResult result,void * context)
{
// At this point either the we logout the session or just the connection
// associated with the specified portal, if one was specified
iSCSIDLogoutContext * ctx = (iSCSIDLogoutContext*)context;
// Store local copies and free structure
int fd = ctx->fd;
errno_t errorCode = ctx->errorCode;
iSCSIPortalRef portal = ctx->portal;
if(ctx->diskSession)
CFRelease(ctx->diskSession);
free(ctx);
enum iSCSILogoutStatusCode statusCode = kiSCSILogoutInvalidStatusCode;
if(!errorCode)
{
SessionIdentifier sessionId = iSCSISessionGetSessionIdForTarget(sessionManager,iSCSITargetGetIQN(target));
// For session logout, ensure that disk unmount was successful...
if(!portal) {
if(result == kiSCSIDAOperationSuccess)
errorCode = iSCSISessionLogout(sessionManager,sessionId,&statusCode);
else
errorCode = EBUSY;
}
else {
ConnectionIdentifier connectionId = iSCSISessionGetConnectionIdForPortal(sessionManager,sessionId,portal);
errorCode = iSCSISessionRemoveConnection(sessionManager,sessionId,connectionId,&statusCode);
}
}
// Log error message
if(errorCode) {
CFStringRef errorString;
if(!portal) {
errorString = CFStringCreateWithFormat(
kCFAllocatorDefault,0,
CFSTR("logout of %@ failed: %s\n"),
iSCSITargetGetIQN(target),
strerror(errorCode));
}
else {
errorString = CFStringCreateWithFormat(
kCFAllocatorDefault,0,
CFSTR("logout of %@,%@:%@ failed: %s\n"),
iSCSITargetGetIQN(target),
iSCSIPortalGetAddress(portal),
iSCSIPortalGetPort(portal),
strerror(errorCode));
}
CFIndex errorStringLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(errorString),kCFStringEncodingASCII) + sizeof('\0');
char errorStringBuffer[errorStringLength];
CFStringGetCString(errorString,errorStringBuffer,errorStringLength,kCFStringEncodingASCII);
asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", errorStringBuffer);
CFRelease(errorString);
}
if(portal)
iSCSIPortalRelease(portal);
iSCSITargetRelease(target);
// Compose a response to send back to the client
iSCSIDMsgLogoutRsp rsp = iSCSIDMsgLogoutRspInit;
rsp.errorCode = errorCode;
rsp.statusCode = statusCode;
send(fd,&rsp,sizeof(rsp),0);
}
errno_t iSCSIDLogout(int fd,iSCSIDMsgLogoutCmd * cmd)
{
CFDataRef targetData = NULL, portalData = NULL, authorizationData = NULL;
iSCSIDaemonRecvMsg(fd,0,&authorizationData,cmd->authLength,&targetData,cmd->targetLength,&portalData,cmd->portalLength,NULL);
errno_t errorCode = 0;
iSCSITargetRef target = NULL;
if(targetData) {
target = iSCSITargetCreateWithData(targetData);
CFRelease(targetData);
}
iSCSIPortalRef portal = NULL;
if(portalData) {
portal = iSCSIPortalCreateWithData(portalData);
CFRelease(portalData);
}
AuthorizationRef authorization = NULL;
// If authorization data is valid, create authorization object
if(authorizationData) {
AuthorizationExternalForm authorizationExtForm;
CFDataGetBytes(authorizationData,
CFRangeMake(0,kAuthorizationExternalFormLength),
(UInt8 *)&authorizationExtForm.bytes);
AuthorizationCreateFromExternalForm(&authorizationExtForm,&authorization);
CFRelease(authorizationData);
}
// If authorization object is valid, get the necessary rights
if(authorization) {
if(iSCSIAuthRightsAcquire(authorization,kiSCSIAuthLoginRight) != errAuthorizationSuccess)
errorCode = EAUTH;
AuthorizationFree(authorization,kAuthorizationFlagDefaults);
}
else
errorCode = EINVAL;
// See if there exists an active session for this target
SessionIdentifier sessionId = iSCSISessionGetSessionIdForTarget(sessionManager,iSCSITargetGetIQN(target));
if(!errorCode && sessionId == kiSCSIInvalidSessionId)
{
CFStringRef errorString = CFStringCreateWithFormat(
kCFAllocatorDefault,0,
CFSTR("logout of %@ failed: the target has no active sessions"),
iSCSITargetGetIQN(target));
CFIndex errorStringLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(errorString),kCFStringEncodingASCII) + sizeof('\0');
char errorStringBuffer[errorStringLength];
CFStringGetCString(errorString,errorStringBuffer,errorStringLength,kCFStringEncodingASCII);
asl_log(NULL, NULL, ASL_LEVEL_CRIT, "%s", errorStringBuffer);
CFRelease(errorString);
errorCode = EINVAL;
}
// See if there exists an active connection for this portal
ConnectionIdentifier connectionId = kiSCSIInvalidConnectionId;
CFIndex connectionCount = 0;
if(!errorCode && portal) {
connectionId = iSCSISessionGetConnectionIdForPortal(sessionManager,sessionId,portal);
if(connectionId == kiSCSIInvalidConnectionId) {
CFStringRef errorString = CFStringCreateWithFormat(
kCFAllocatorDefault,0,
CFSTR("logout of %@,%@:%@ failed: the portal has no active connections"),
iSCSITargetGetIQN(target),iSCSIPortalGetAddress(portal),iSCSIPortalGetPort(portal));
CFIndex errorStringLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(errorString),kCFStringEncodingASCII) + sizeof('\0');
char errorStringBuffer[errorStringLength];
CFStringGetCString(errorString,errorStringBuffer,errorStringLength,kCFStringEncodingASCII);
asl_log(NULL, NULL, ASL_LEVEL_CRIT, "%s", errorStringBuffer);
CFRelease(errorString);
errorCode = EINVAL;
}
else {
// Determine the number of connections
CFArrayRef connectionIds = iSCSISessionCopyArrayOfConnectionIds(sessionManager,sessionId);
connectionCount = CFArrayGetCount(connectionIds);
CFRelease(connectionIds);
}
}
// Unmount volumes if portal not specified (session logout)
// or if portal is specified and is only connection...
iSCSIDLogoutContext * context;
context = (iSCSIDLogoutContext*)malloc(sizeof(iSCSIDLogoutContext));
context->fd = fd;
context->portal = NULL;
context->errorCode = errorCode;
context->diskSession = NULL;
// Unmount and session logout
if(!errorCode && (!portal || connectionCount == 1))
{
context->diskSession = DASessionCreate(kCFAllocatorDefault);
DASessionScheduleWithRunLoop(context->diskSession,CFRunLoopGetMain(),kCFRunLoopDefaultMode);
iSCSIDAUnmountForTarget(context->diskSession,kDADiskUnmountOptionWhole,target,&iSCSIDLogoutComplete,context);
}
// Portal logout only (or no logout and just a response to client if error)
else {
context->portal = portal;
iSCSIDLogoutComplete(target,kiSCSIDAOperationSuccess,context);
}
return 0;
}
errno_t iSCSIDCreateArrayOfActiveTargets(int fd,iSCSIDMsgCreateArrayOfActiveTargetsCmd * cmd)
{
CFArrayRef sessionIds = iSCSISessionCopyArrayOfSessionIds(sessionManager);
CFIndex sessionCount = CFArrayGetCount(sessionIds);
// Prepare an array to hold our targets
CFMutableArrayRef activeTargets = CFArrayCreateMutable(kCFAllocatorDefault,
sessionCount,
&kCFTypeArrayCallBacks);
// Get target object for each active session and add to array
for(CFIndex idx = 0; idx < sessionCount; idx++)
{
iSCSITargetRef target = iSCSISessionCopyTargetForId(sessionManager,(SessionIdentifier)CFArrayGetValueAtIndex(sessionIds,idx));
CFArrayAppendValue(activeTargets,target);
iSCSITargetRelease(target);
}
// Serialize and send array
CFDataRef data = CFPropertyListCreateData(kCFAllocatorDefault,
(CFPropertyListRef) activeTargets,
kCFPropertyListBinaryFormat_v1_0,0,NULL);
CFRelease(activeTargets);
// Send response header
iSCSIDMsgCreateArrayOfActiveTargetsRsp rsp = iSCSIDMsgCreateArrayOfActiveTargetsRspInit;
if(data)
rsp.dataLength = (UInt32)CFDataGetLength(data);
else
rsp.dataLength = 0;
iSCSIDaemonSendMsg(fd,(iSCSIDMsgGeneric*)&rsp,data,NULL);
if(data)
CFRelease(data);
return 0;
}
errno_t iSCSIDCreateArrayofActivePortalsForTarget(int fd,
iSCSIDMsgCreateArrayOfActivePortalsForTargetCmd * cmd)
{
// TODO: null check
CFArrayRef sessionIds = iSCSISessionCopyArrayOfSessionIds(sessionManager);
CFIndex sessionCount = CFArrayGetCount(sessionIds);
// Prepare an array to hold our targets
CFMutableArrayRef activeTargets = CFArrayCreateMutable(kCFAllocatorDefault,
sessionCount,
&kCFTypeArrayCallBacks);
// Get target object for each active session and add to array
for(CFIndex idx = 0; idx < sessionCount; idx++)
{
iSCSITargetRef target = iSCSISessionCopyTargetForId(sessionManager,(SessionIdentifier)CFArrayGetValueAtIndex(sessionIds,idx));
CFArrayAppendValue(activeTargets,target);
iSCSITargetRelease(target);
}
// Serialize and send array
CFDataRef data = CFPropertyListCreateData(kCFAllocatorDefault,
(CFPropertyListRef) activeTargets,
kCFPropertyListBinaryFormat_v1_0,0,NULL);
CFRelease(activeTargets);
// Send response header
iSCSIDMsgCreateArrayOfActivePortalsForTargetRsp rsp = iSCSIDMsgCreateArrayOfActivePortalsForTargetRspInit;
if(data)
rsp.dataLength = (UInt32)CFDataGetLength(data);
else
rsp.dataLength = 0;
iSCSIDaemonSendMsg(fd,(iSCSIDMsgGeneric*)&rsp,data,NULL);
if(data)
CFRelease(data);
if(sessionIds)
CFRelease(sessionIds);
return 0;
}
errno_t iSCSIDIsTargetActive(int fd,iSCSIDMsgIsTargetActiveCmd *cmd)
{
CFDataRef targetData = NULL;
iSCSIDaemonRecvMsg(fd,0,&targetData,cmd->targetLength,NULL);
iSCSITargetRef target = NULL;
if(targetData) {
target = iSCSITargetCreateWithData(targetData);
CFRelease(targetData);
}
if(target) {
iSCSIDMsgIsTargetActiveRsp rsp = iSCSIDMsgIsTargetActiveRspInit;
rsp.active = (iSCSISessionGetSessionIdForTarget(sessionManager,iSCSITargetGetIQN(target)) != kiSCSIInvalidSessionId);
iSCSITargetRelease(target);
if(send(fd,&rsp,sizeof(rsp),0) != sizeof(rsp))
return EAGAIN;
}
return 0;
}
errno_t iSCSIDIsPortalActive(int fd,iSCSIDMsgIsPortalActiveCmd *cmd)
{
CFDataRef targetData = NULL, portalData = NULL;
iSCSIDaemonRecvMsg(fd,0,&targetData,cmd->targetLength,&portalData,cmd->portalLength,NULL);
iSCSITargetRef target = NULL;
if(targetData) {
target = iSCSITargetCreateWithData(targetData);
CFRelease(targetData);
}
iSCSIPortalRef portal = NULL;
if(portalData) {
portal = iSCSIPortalCreateWithData(portalData);
CFRelease(portalData);
}
iSCSIDMsgIsPortalActiveRsp rsp = iSCSIDMsgIsPortalActiveRspInit;
SessionIdentifier sessionId = (iSCSISessionGetSessionIdForTarget(sessionManager,iSCSITargetGetIQN(target)));
if(sessionId == kiSCSIInvalidSessionId)
rsp.active = false;
else
rsp.active = (iSCSISessionGetConnectionIdForPortal(sessionManager,sessionId,portal) != kiSCSIInvalidConnectionId);
if(target)
iSCSITargetRelease(target);
if(portal)
iSCSIPortalRelease(portal);
if(send(fd,&rsp,sizeof(rsp),0) != sizeof(rsp))
return EAGAIN;
return 0;
}
errno_t iSCSIDQueryTargetForAuthMethod(int fd,iSCSIDMsgQueryTargetForAuthMethodCmd * cmd)
{
CFDataRef targetData = NULL, portalData = NULL;
iSCSIDaemonRecvMsg(fd,0,&targetData,cmd->targetLength,&portalData,cmd->portalLength,NULL);
iSCSITargetRef target = NULL;
if(targetData) {
target = iSCSITargetCreateWithData(targetData);
CFRelease(targetData);
}
iSCSIPortalRef portal = NULL;
if(portalData) {
portal = iSCSIPortalCreateWithData(portalData);
CFRelease(portalData);
}
enum iSCSIAuthMethods authMethod = kiSCSIAuthMethodInvalid;
enum iSCSILoginStatusCode statusCode = kiSCSILoginInvalidStatusCode;
errno_t error = iSCSIQueryTargetForAuthMethod(sessionManager,portal,iSCSITargetGetIQN(target),&authMethod,&statusCode);
// Compose a response to send back to the client
iSCSIDMsgQueryTargetForAuthMethodRsp rsp = iSCSIDMsgQueryTargetForAuthMethodRspInit;
rsp.errorCode = error;
rsp.statusCode = statusCode;
rsp.authMethod = authMethod;
if(send(fd,&rsp,sizeof(rsp),0) != sizeof(rsp))
return EAGAIN;
return 0;
}
errno_t iSCSIDCreateCFPropertiesForSession(int fd,
iSCSIDMsgCreateCFPropertiesForSessionCmd * cmd)
{
CFMutableDataRef targetData = NULL;
errno_t error = iSCSIDaemonRecvMsg(fd,0,&targetData,cmd->targetLength,NULL);
iSCSITargetRef target = NULL;
if(!error) {
if(targetData) {
target = iSCSITargetCreateWithData(targetData);
CFRelease(targetData);