-
Notifications
You must be signed in to change notification settings - Fork 7
/
MobileDeviceAccess.m
3381 lines (2986 loc) · 97.3 KB
/
MobileDeviceAccess.m
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
//
// MobileDeviceAccess.m
// MobileDeviceAccess
//
// Created by Jeff Laing on 6/08/09.
// Copyright 2009 Tristero Computer Systems. All rights reserved.
//
#import "MobileDeviceAccess.h"
#include <unistd.h>
#include <stdlib.h>
#include <syslog.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <mach/error.h>
#include <AppKit/NSApplication.h>
#pragma mark MobileDevice.framework internals
// opaque structures
typedef struct _afc_directory *afc_directory;
typedef struct _afc_dictionary *afc_dictionary;
typedef struct _afc_operation *afc_operation;
// some functions use different size longs on the different architectures
#if __x86_64__
typedef uint64_t am_long;
#else
typedef uint32_t am_long;
#endif
// Messages passed to device notification callbacks: passed as part of
// am_device_notification_callback_info.
typedef enum {
ADNCI_MSG_CONNECTED = 1,
ADNCI_MSG_DISCONNECTED = 2,
ADNCI_MSG_UNSUBSCRIBED = 3
} adnci_msg;
struct am_device_notification_callback_info {
am_device dev; // 0 device
uint32_t msg; // 4 one of adnci_msg
} __attribute__ ((packed));
// The type of the device notification callback function.
typedef void (*am_device_notification_callback)(struct am_device_notification_callback_info *,void* callback_data);
// notification related functions
mach_error_t AMDeviceNotificationSubscribe(
am_device_notification_callback callback,
uint32_t unused0,
uint32_t unused1,
void *callback_data,
am_device_notification *notification);
mach_error_t AMDeviceNotificationUnsubscribe(
am_device_notification subscription);
// device related functions
mach_error_t AMDeviceConnect(am_device device);
mach_error_t AMDeviceDisconnect(am_device device);
uint32_t AMDeviceGetInterfaceType(am_device device);
enum {
AMDeviceInterfaceTypeUSB = 1,
AMDeviceInterfaceTypeWifi = 2
};
//uint32_t AMDeviceGetInterfaceSpeed(am_device device);
//uint32_t AMDeviceGetConnectionID(am_device device);
//CFStringRef AMDeviceCopyDeviceIdentifier(am_device device);
CFStringRef AMDeviceCopyValue(am_device device,CFStringRef domain,CFStringRef key);
mach_error_t AMDeviceRetain(am_device device);
mach_error_t AMDeviceRelease(am_device device);
// I can see these in the framework, but they don't seem to be exported
// in a way that lets us link directly against them
//?notexp? CFStringRef AMDeviceCopyDeviceLocation(am_device device);
// looks to just return dword[device+28]
//?notexp? uint32_t AMDeviceUSBDeviceID(am_device device);
//?notexp? uint32_t AMDeviceUSBLocationID(am_device device);
//?notexp? uint32_t AMDeviceUSBProductID(am_device device);
// int AMDeviceIsPaired(am_device device);
// 000039f5 T _AMDevicePair (am_device)
// mach_error_t AMDeviceValidatePairing(am_device device);
// 000037e6 T _AMDeviceUnpair (am_device)
mach_error_t AMDeviceLookupApplications(am_device device, CFDictionaryRef options, CFDictionaryRef *result);
// 0000251f T _AMDeviceActivate (am_device, int32 )
// 000088ad T _AMDeviceArchiveApplication (am_device, int32, int32, int32, int32)
// 0000891e T _AMDeviceBrowseApplications (am_device, int32)
// 00008ecd T _AMDeviceCheckCapabilitiesMatch
// 0000179b T _AMDeviceConvertError
// 00009063 T _AMDeviceCopyProvisioningProfiles
// 00004133 T _AMDeviceCreate
// 000041d7 T _AMDeviceCreateFromProperties
// 0000243d T _AMDeviceDeactivate (am_device)
// 0000235b T _AMDeviceEnterRecovery (am_device)
// 00008c74 T _AMDeviceInstallApplication
// 0000a598 T _AMDeviceInstallPackage
// 00008f59 T _AMDeviceInstallProvisioningProfile
// 0000159a T _AMDeviceIsValid
// 00008710 T _AMDeviceLookupApplicationArchives
// 00008990 T _AMDeviceLookupApplications (am_device, int32, int32)
// 00009353 T _AMDeviceMountImage
// 000087cb T _AMDeviceRemoveApplicationArchive
// 00008fde T _AMDeviceRemoveProvisioningProfile
// 00002608 T _AMDeviceRemoveValue
// 0000883c T _AMDeviceRestoreApplication
// 0000121a T _AMDeviceSerialize
// 0000280f T _AMDeviceSetValue
// 00005ec5 T _AMDeviceSoftwareUpdate
// 0000794b T _AMDeviceTransferApplication
// 00008a91 T _AMDeviceUninstallApplication
// 0000a232 T _AMDeviceUninstallPackage
// 00003e21 T _AMDeviceUnserialize
// 00008b02 T _AMDeviceUpgradeApplication
// 000035d3 T _AMDeviceValidatePairing
// session related functions
mach_error_t AMDeviceStartSession(am_device device);
mach_error_t AMDeviceStopSession(am_device device);
// service related functions
mach_error_t AMDeviceStartService(am_device device, CFStringRef service_name, am_service *handle);
mach_error_t AMDeviceStartServiceWithOptions(am_device device,CFStringRef service_name,CFDictionaryRef options,am_service *handle);
// 000067f9 T _AMDeviceStartHouseArrestService
// AFC connection functions
afc_error_t AFCConnectionOpen(am_service handle,uint32_t io_timeout,afc_connection *conn);
afc_error_t AFCConnectionClose(afc_connection conn);
// int _AFCConnectionIsValid(afc_connection *conn)
am_long AFCConnectionGetContext(afc_connection conn);
am_long AFCConnectionSetContext(afc_connection conn, am_long ctx);
am_long AFCConnectionGetFSBlockSize(afc_connection conn);
am_long AFCConnectionSetFSBlockSize(afc_connection conn, am_long size);
am_long AFCConnectionGetIOTimeout(afc_connection conn);
am_long AFCConnectionSetIOTimeout(afc_connection conn, am_long timeout);
am_long AFCConnectionGetSocketBlockSize(afc_connection conn);
am_long AFCConnectionSetSocketBlockSize(afc_connection conn, am_long size);
CFStringRef AFCCopyErrorString(afc_connection a);
CFTypeRef AFCConnectionCopyLastErrorInfo(afc_connection a);
// 0001b8e6 T _AFCConnectionCopyLastErrorInfo
// 0001a8b6 T _AFCConnectionCreate
// 0001b8ca T _AFCConnectionGetStatus
// 0001a867 T _AFCConnectionGetTypeID
// 0001ae99 T _AFCConnectionInvalidate
// 0001b8c1 T _AFCConnectionProcessOperations
// 0001abdc T _AFCConnectionScheduleWithRunLoop
// 0001b623 T _AFCConnectionSubmitOperation
// 0001ad5a T _AFCConnectionUnscheduleFromRunLoop
// 000000000000603e T _AFCConnectionProcessOperations
// 0000000000005df8 T _AFCConnectionSetCallBack
// 00000000000064cc T _AFCConnectionSubmitOperation
// 0000000000008512 t _AFCLockCreate
// 0000000000007a83 t _AFCLockFree
// 00000000000084db t _AFCLockGetTypeID
// 0000000000007e69 t _AFCLockLock
// 00000000000083f2 t _AFCLockTryLock
// 000000000000810c t _AFCLockUnlock
const char * AFCGetClientVersionString(void); // "@(#)PROGRAM:afc PROJECT:afc-80"
// directory related functions
afc_error_t AFCDirectoryOpen(afc_connection conn,const char *path,afc_directory *dir);
afc_error_t AFCDirectoryRead(afc_connection conn,afc_directory dir,char **dirent);
afc_error_t AFCDirectoryClose(afc_connection conn,afc_directory dir);
afc_error_t AFCDirectoryCreate(afc_connection conn,const char *dirname);
afc_error_t AFCRemovePath(afc_connection conn,const char *dirname);
afc_error_t AFCRenamePath(afc_connection conn,const char *from,const char *to);
afc_error_t AFCLinkPath(afc_connection conn,uint64_t mode, const char *target,const char *link);
// NSLog(@"linkpath returned %#lx",AFCLinkPath(_afc,(1=hard,2=sym)"/tmp/aaa","/tmp/bbb"));
// file i/o functions
afc_error_t AFCFileRefOpen(afc_connection conn, const char *path, uint64_t mode,afc_file_ref *ref);
afc_error_t AFCFileRefClose(afc_connection conn,afc_file_ref ref);
afc_error_t AFCFileRefSeek(afc_connection conn, afc_file_ref ref, int64_t offset, uint64_t mode);
afc_error_t AFCFileRefTell(afc_connection conn, afc_file_ref ref, uint64_t *offset);
afc_error_t AFCFileRefRead(afc_connection conn,afc_file_ref ref,void *buf, afc_long *len);
afc_error_t AFCFileRefSetFileSize(afc_connection conn,afc_file_ref ref, afc_long offset);
afc_error_t AFCFileRefWrite(afc_connection conn,afc_file_ref ref, const void *buf, uint32_t len);
// afc_error_t AFCFileRefLock(afc_connection *conn, afc_file_ref ref, ...);
// 00019747 T _AFCFileRefUnlock
// device/file information functions
afc_error_t AFCDeviceInfoOpen(afc_connection conn, afc_dictionary *info);
afc_error_t AFCFileInfoOpen(afc_connection conn, const char *path, afc_dictionary *info);
afc_error_t AFCKeyValueRead(afc_dictionary dict, const char **key, const char **val);
afc_error_t AFCKeyValueClose(afc_dictionary dict);
// Notification stuff - only call these on "com.apple.mobile.notification_proxy" (AMSVC_NOTIFICATION_PROXY)
mach_error_t AMDPostNotification(am_service socket, CFStringRef notification, CFStringRef userinfo);
mach_error_t AMDShutdownNotificationProxy(am_service socket);
mach_error_t AMDObserveNotification(am_service socket, CFStringRef notification);
typedef void (*NOTIFY_CALLBACK)(CFStringRef notification, void* data);
mach_error_t AMDListenForNotifications(am_service socket, NOTIFY_CALLBACK cb, void* data);
// New style - seems to formalise the creation of the "request packet" seperately
// from the execution.
afc_error_t AFCConnectionProcessOperation(afc_connection a1, afc_operation op, double timeout);
afc_error_t AFCOperationGetResultStatus(afc_operation op);
CFTypeRef AFCOperationGetResultObject(afc_operation op);
CFTypeID AFCOperationGetTypeID(afc_operation op);
// 0000000000002dd3 T _AFCOperationGetState
// 00000000000030c5 T _AFCOperationCopyPacketData
afc_error_t AFCOperationSetContext(afc_operation op, void *ctx);
void *AFCOperationGetContext(afc_operation op);
// each of these returns an op, with the appropriate request encoded. The value of ctx is
// available via AFCOperationGetContext()
afc_operation AFCOperationCreateGetConnectionInfo(CFAllocatorRef allocator, void *ctx);
afc_operation AFCOperationCreateGetDeviceInfo(CFAllocatorRef allocator, void *ctx);
afc_operation AFCOperationCreateGetFileHash(CFAllocatorRef allocator, CFStringRef filename, void *ctx);
afc_operation AFCOperationCreateGetFileInfo(CFAllocatorRef allocator, CFStringRef filename, void *ctx);
afc_operation AFCOperationCreateLinkPath(CFAllocatorRef allocator, uint32_t mode, CFStringRef filename1, CFStringRef filename2, void *ctx);
afc_operation AFCOperationCreateMakeDirectory(CFAllocatorRef allocator, CFStringRef filename, void *ctx);
afc_operation AFCOperationCreateOpenFile(CFAllocatorRef allocator, CFStringRef filename, void *ctx);
afc_operation AFCOperationCreateReadDirectory(CFAllocatorRef allocator, CFStringRef filename, void *ctx);
afc_operation AFCOperationCreateRemovePath(CFAllocatorRef allocator, CFStringRef filename, void *ctx);
afc_operation AFCOperationCreateRenamePath(CFAllocatorRef allocator, CFStringRef oldname, CFStringRef newname, void *ctx);
afc_operation AFCOperationCreateSetConnectionOptions(CFAllocatorRef allocator, CFDictionaryRef dict, void *ctx);
afc_operation AFCOperationCreateSetModTime(CFAllocatorRef allocator, CFStringRef filename, uint64_t mtm, void *ctx);
@interface AMDevice(Private)
- (am_service)_startService:(NSString*)name;
@property (readwrite,retain) NSString *lasterror; // externally readonly, internally we can write to it
@end
@interface AMService(Private)
@property (readwrite,retain) NSString *lasterror; // externally readonly, internally we can write to it
@end
@interface AFCFileReference(Private)
@property (readwrite,retain) NSString *lasterror; // externally readonly, internally we can write to it
@end
@implementation AMService
@synthesize delegate = _delegate;
-(NSString*)lasterror {
return _lasterror;
}
-(void)setLasterror:(NSString*)newval
{
[newval retain];
[_lasterror release];
_lasterror = newval;
}
- (void)performDelegateSelector:(SEL)sel
withObject:(id)info
{
if (_delegate) {
if ([_delegate respondsToSelector:sel]) {
[_delegate performSelector:sel withObject:info];
}
}
}
- (void)dealloc
{
[_lasterror release];
[super dealloc];
}
- (id)initWithName:(NSString*)name onDevice:(AMDevice*)device
{
if (self = [super init]) {
_delegate = nil;
_service = [device _startService:name];
if (_service == 0) {
[self release];
return nil;
}
}
return self;
}
+ (AMService*)serviceWithName:(NSString *)name onDevice:(AMDevice*)device
{
return [[[AMService alloc] initWithName:name onDevice:device] autorelease];
}
- (bool)sendXMLRequest:(id)message
{
bool result = NO;
CFErrorRef failed = nil;
CFDataRef messageAsXML = CFPropertyListCreateData ( NULL, message, kCFPropertyListXMLFormat_v1_0, 0, &failed );
if (messageAsXML) {
CFIndex xmlLength = CFDataGetLength(messageAsXML);
uint32_t sz;
int sock = (int)_service;
sz = htonl(xmlLength);
if (send(sock, &sz, sizeof(sz), 0) != sizeof(sz)) {
self.lasterror = @"Can't send message size";
} else {
if (send(sock, CFDataGetBytePtr(messageAsXML), xmlLength,0) != xmlLength) {
self.lasterror = @"Can't send message text";
} else {
self.lasterror = nil;
result = YES;
}
}
CFRelease(messageAsXML);
} else {
if (failed) {
self.lasterror = [(NSError*)failed localizedDescription];
CFRelease(failed);
} else {
self.lasterror = @"Can't convert request to XML";
}
}
return(result);
}
- (id)readXMLReply
{
id result = nil;
int sock = (int)((uint32_t)_service);
uint32_t sz;
/* now wait for the reply */
if (sizeof(uint32_t) != recv(sock, &sz, sizeof(sz), 0)) {
self.lasterror = @"Can't receive reply size";
} else {
sz = ntohl(sz);
if (sz) {
// we need to be careful in here, because there is a fixed buffer size in the
// socket, and it may be smaller than the message we are going to recieve. we
// need to allocate a buffer big enough for the final result, but loop calling
// recv() until we recieve the complete reply.
unsigned char *buff = malloc(sz);
unsigned char *p = buff;
uint32_t left = sz;
while (left) {
uint32_t rc =recv(sock, p, left,0);
if (rc==0) {
self.lasterror = [NSString stringWithFormat:@"Reply was truncated, expected %d more bytes",left];
free(buff);
return(nil);
}
left -= rc;
p += rc;
}
CFDataRef r = CFDataCreateWithBytesNoCopy(0,buff,sz,kCFAllocatorNull);
CFErrorRef failed = nil;
CFPropertyListRef reply = CFPropertyListCreateWithData(NULL,r, kCFPropertyListImmutable, NULL, &failed);
CFRelease(r);
free(buff);
if (reply) {
result = [[(id)reply copy] autorelease];
CFRelease(reply);
self.lasterror = nil;
} else {
if (failed) {
self.lasterror = [(NSError*)failed localizedDescription];
CFRelease(failed);
} else {
self.lasterror = @"Failed to decode XML reply";
}
}
}
}
return(result);
}
- (id)sendRequestAndWaitForSingleReply:(id)message
{
if ([self sendXMLRequest:message]) {
return [self readXMLReply];
}
return nil;
}
// common method to send a request, then loop waiting for final reply to a lengthy operation
// this is only appropriate for messages that return NSDictionary replies
- (BOOL)sendRequestAndWaitUntilDone:(NSDictionary*)message
{
[self performDelegateSelector:@selector(operationStarted:) withObject:message];
BOOL result = NO;
// send request, this updates lasterror appropriately
if ([self sendXMLRequest:message]) {
for (;;) {
// read next reply - this updates lasterror appropriately
NSDictionary *reply = [self readXMLReply];
if (!reply) break;
[self performDelegateSelector:@selector(operationContinues:) withObject:reply];
NSString *s;
// if there is an error key, we bail out
s = [reply objectForKey:@"Error"];
if (s) {
self.lasterror = s;
break;
}
// otherwise, keep looping until the entry for Status == Complete
s = [reply objectForKey:@"Status"];
if (![s isEqual:@"Complete"]) continue;
result = YES;
break;
}
}
[self performDelegateSelector:@selector(operationCompleted:) withObject:message];
return result;
}
- (NSInputStream*)inputStreamFromSocket
{
CFReadStreamRef s;
int sock = (int)((uint32_t)_service);
CFStreamCreatePairWithSocket(
kCFAllocatorDefault, (CFSocketNativeHandle)sock, &s, NULL);
return [(NSInputStream*)s autorelease];
}
/*
am_service socket;
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket);
AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncWillStart"), NULL);
AMDPostNotification(socket, &CFSTR("com.apple.itunes-mobdev.syncDidFinish"), NULL);
AMDShutdownNotificationProxy(socket);
*/
@end
@implementation AMDLService
- (id)waitForDLResponse:(NSString*)response
{
id result = nil;
NSArray *reply = [self readXMLReply];
if (reply) {
NSString *s = [reply firstObject];
if (s) {
if ([s isEqualToString:response]) {
result = reply;
} else if ([s isEqualToString:@"DLMessageDisconnect"]) {
self.lasterror = [reply objectAtIndex:1];
} else {
self.lasterror = [NSString stringWithFormat:@"Expected '%@', got '%@'",response,s];
}
} else {
self.lasterror = @"Response truncated";
}
}
return result;
}
- (BOOL)versionHandshake
{
BOOL result = NO;
NSArray *request, *reply;
// step 1 - he sends us DLMessageVersionExchange, major, minor
reply = [self waitForDLResponse:@"DLMessageVersionExchange"];
if (reply) {
// we could check a bit harder here
NSInteger major = [[reply objectAtIndex:1] intValue];
NSInteger minor = [[reply objectAtIndex:2] intValue];
NSLog(@"Device requesting DeviceLinkProtocol %ld,%ld", (long)major, (long)minor);
// we say yes, we accept that version. I suspect we might be able to tell him a lower
// version number here, but I don't know what the versions really mean at this point so
// lets just claim to understand him...
request = @[
@"DLMessageVersionExchange",
@"DLVersionsOk",
@(major)
];
if ([self sendXMLRequest:request]) {
// he then replies with DLMessageDeviceReady
if ([self waitForDLResponse:@"DLMessageDeviceReady"]) {
// and we are cool to go
result = YES;
}
}
}
return result;
}
- (id)sendDLProcessMessage:(NSDictionary*)message
andWaitForReply:(NSString*)replyType
{
static NSString *header = @"DLMessageProcessMessage";
// messages are actually send as arrays, first element being DLMessageProcessMessage
NSArray *request = @[ header, message ];
// transaction is still raw xml representations, but reply is an array whose first element
// should also be our header, and whose second element is a dictionary
NSDictionary *result = nil;
if ([self sendXMLRequest:request]) {
// and wait for a corresponding response
NSArray *reply = [self waitForDLResponse:header];
NSString *s;
if (reply) {
// if it gets here, we know that its the right kind of message, but we still need to
// make sure it isn't truncated
if ([reply count] < 2) {
self.lasterror = @"Reply is too short";
return nil;
}
// lift out the response dictionary
result = [reply objectAtIndex:1];
// look for an error message
s = [result objectForKey:@"ErrorMessage"];
if (s) {
self.lasterror = s;
return nil;
}
// no error message, is it the right message type ?
s = [result objectForKey:@"MessageType"];
if (![s isEqualToString:replyType]) {
self.lasterror = [NSString stringWithFormat:@"Expected '%@', got '%@'", replyType, s];
return nil;
}
// fall through to return
}
}
return result;
}
// DLServices need an additional handshake to ensure that we all agree on the version
// of the protocol we are talking.
- (id)initWithName:(NSString*)name onDevice:(AMDevice*)device
{
if (self = [super initWithName:name onDevice:device]) {
// at this point, the service is started. We need to do the version handshake. If
// that fails, we need to nuke ourselves
if (![self versionHandshake]) {
NSLog(@"failed to handshake: %@",self.lasterror);
[self release];
self = nil;
}
}
return self;
}
@end
@implementation AFCFileReference
-(NSString*)lasterror {
return _lasterror;
}
-(void)setLasterror:(NSString*)newval
{
[newval retain];
[_lasterror release];
_lasterror = newval;
}
- (bool)checkStatus:(afc_error_t)ret from:(const char *)func
{
if (ret != 0) {
self.lasterror = [NSString stringWithFormat:@"%s failed: %d",func,ret];
return NO;
}
self.lasterror = nil;
return YES;
}
- (bool)ensureFileIsOpen
{
if (_ref) return YES;
self.lasterror = @"File is not open";
return NO;
}
- (void)dealloc
{
[self closeFile];
[_lasterror release];
[super dealloc];
}
- (id)initWithPath:(NSString*)path reference:(afc_file_ref)ref afc:(afc_connection)afc
{
if (self=[super init]) {
_ref = ref;
_afc = afc;
}
return self;
}
- (bool)closeFile
{
if (![self ensureFileIsOpen]) return NO;
if (![self checkStatus:AFCFileRefClose(_afc, _ref) from:"AFCFileRefClose"]) return NO;
_ref = 0;
return YES;
}
- (bool)seek:(int64_t)offset mode:(int)m
{
if (![self ensureFileIsOpen]) return NO;
return [self checkStatus:AFCFileRefSeek(_afc, _ref, offset, m) from:"AFCFileRefSeek"];
}
- (bool)tell:(uint64_t*)offset
{
if (![self ensureFileIsOpen]) return NO;
return [self checkStatus:AFCFileRefTell(_afc, _ref, offset) from:"AFCFileRefTell"];
}
- (afc_long)readN:(afc_long)n bytes:(char *)buff
{
if (![self ensureFileIsOpen]) return NO;
afc_long afcSize = n;
if (![self checkStatus:AFCFileRefRead(_afc, _ref, buff, &afcSize) from:"AFCFileRefRead"]) return 0;
return afcSize;
}
- (bool)writeN:(afc_long)n bytes:(const char *)buff
{
if (![self ensureFileIsOpen]) return NO;
if (n>0) {
return [self checkStatus:AFCFileRefWrite(_afc, _ref, buff, n) from:"AFCFileRefWrite"];
}
return YES;
}
- (bool)writeNSData:(NSData*)data
{
return [self writeN:[data length] bytes:[data bytes]];
}
- (bool)setFileSize:(uint64_t)size
{
if (![self ensureFileIsOpen]) return NO;
return [self checkStatus:AFCFileRefSetFileSize(_afc, _ref, size) from:"AFCFileRefSetFileSize"];
}
@end
@implementation AFCDirectoryAccess
- (void)dealloc
{
if (_afc) [self close];
[super dealloc];
}
- (bool)checkStatus:(int)ret from:(const char *)func
{
if (ret != 0) {
self.lasterror = [NSString stringWithFormat:@"%s failed: Return code = 0x%04X",func,ret];
return NO;
}
self.lasterror = nil;
return YES;
}
- (bool)ensureConnectionIsOpen
{
if (_afc) return YES;
self.lasterror = @"Connection is not open";
return NO;
}
- (void)close
{
if (_afc) {
NSLog(@"disconnecting");
int ret = AFCConnectionClose(_afc);
if (ret != 0) {
NSLog(@"AFCConnectionClose failed: %d", ret);
}
_afc = nil;
}
}
- (NSMutableDictionary*)readAfcDictionary:(afc_dictionary)dict
{
NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
const char *k, *v;
while (0 == AFCKeyValueRead(dict, &k, &v)) {
if (!k) break;
if (!v) break;
// if all the characters in the value are digits, pass it back as
// as 'long long' in a dictionary - else pass it back as a string
const char *p;
for (p=v; *p; p++) if (*p<'0' | *p>'9') break;
if (*p) {
/* its a string */
[result setObject:[NSString stringWithUTF8String:v] forKey:[NSString stringWithUTF8String:k]];
} else {
[result setObject:[NSNumber numberWithLongLong:atoll(v)] forKey:[NSString stringWithUTF8String:k]];
}
}
return result;
}
// retrieve a dictionary of information describing the device
// {
// FSFreeBytes = 93876224
// FSBlockSize = 4096
// FSTotalBytes = 524288000
// Model = iPod1,1
// }
- (NSDictionary*)deviceInfo
{
if (![self ensureConnectionIsOpen]) return nil;
afc_dictionary dict;
if ([self checkStatus:AFCDeviceInfoOpen(_afc, &dict) from:"AFCDeviceInfoOpen"]) {
NSMutableDictionary *result = [self readAfcDictionary:dict];
AFCKeyValueClose(dict);
self.lasterror = nil;
return [NSDictionary dictionaryWithDictionary:result];
}
return nil;
}
/***
/dev/console
2009-08-07 20:10:11.331 MobileDeviceAccess[7284:10b] st_blocks = 0
2009-08-07 20:10:11.331 MobileDeviceAccess[7284:10b] st_nlink = 1
2009-08-07 20:10:11.332 MobileDeviceAccess[7284:10b] st_size = 0
2009-08-07 20:10:11.333 MobileDeviceAccess[7284:10b] st_ifmt = S_IFCHR
/dev/disk1
2009-08-07 20:11:35.842 MobileDeviceAccess[7296:10b] st_blocks = 0
2009-08-07 20:11:35.843 MobileDeviceAccess[7296:10b] st_nlink = 1
2009-08-07 20:11:35.844 MobileDeviceAccess[7296:10b] st_size = 0
2009-08-07 20:11:35.844 MobileDeviceAccess[7296:10b] st_ifmt = S_IFBLK
****/
// var/mobile/Media
// 2009-08-06 23:38:04.070 MobileDeviceAccess[1823:813] st_blocks = 0
// 2009-08-06 23:38:04.071 MobileDeviceAccess[1823:813] st_nlink = 11
// 2009-08-06 23:38:04.071 MobileDeviceAccess[1823:813] st_size = 476
// 2009-08-06 23:38:04.072 MobileDeviceAccess[1823:813] st_ifmt = S_IFDIR
// jailbreak.log
// 2009-08-06 23:37:23.089 MobileDeviceAccess[1800:813] st_blocks = 64
// 2009-08-06 23:37:23.089 MobileDeviceAccess[1800:813] st_nlink = 1
// 2009-08-06 23:37:23.090 MobileDeviceAccess[1800:813] st_size = 29260
// 2009-08-06 23:37:23.091 MobileDeviceAccess[1800:813] st_ifmt = S_IFREG
// "st_birthtime" = 9223372036854775807;
// "st_mtime" = 280689926000000000;
// /Applications
// 2009-08-06 23:39:01.872 MobileDeviceAccess[1864:813] st_blocks = 8
// 2009-08-06 23:39:01.872 MobileDeviceAccess[1864:813] st_nlink = 1
// 2009-08-06 23:39:01.876 MobileDeviceAccess[1864:813] st_size = 27
// 2009-08-06 23:39:01.877 MobileDeviceAccess[1864:813] st_ifmt = S_IFLNK
// 2009-08-06 23:39:01.873 MobileDeviceAccess[1864:813] LinkTarget = /var/stash/Applications.pwn
-(void) fix_date_entry:(NSString*)key in:(NSMutableDictionary *)dict
{
id d = [dict objectForKey:key];
if (d) {
long v = [d doubleValue] / 1000000000.0;
d = [NSDate dateWithTimeIntervalSince1970:v];
[dict setObject:d forKey:key];
}
}
- (NSDictionary*)getFileInfo:(NSString*)path
{
if (!path) {
self.lasterror = @"Input path is nil";
return nil;
}
if ([self ensureConnectionIsOpen]) {
afc_dictionary dict;
if ([self checkStatus:AFCFileInfoOpen(_afc, [path UTF8String], &dict) from:"AFCFileInfoOpen"]) {
NSMutableDictionary *result = [self readAfcDictionary:dict];
[result setObject:path forKey:@"path"];
AFCKeyValueClose(dict);
self.lasterror = nil;
// fix the ones we know are dates
[self fix_date_entry:@"st_birthtime" in:result];
[self fix_date_entry:@"st_mtime" in:result];
return [NSDictionary dictionaryWithDictionary:result];
}
}
return nil;
}
- (BOOL)fileExistsAtPath:(NSString *)path
{
if (!path) {
self.lasterror = @"Input path is nil";
return NO;
}
if ([self ensureConnectionIsOpen]) {
afc_dictionary dict;
if (AFCFileInfoOpen(_afc, [path UTF8String], &dict)==0) {
AFCKeyValueClose(dict);
self.lasterror = nil;
return YES;
}
}
return NO;
}
- (NSArray*)directoryContents:(NSString*)path
{
if (!path) {
self.lasterror = @"Input path is nil";
return nil;
}
if (![self ensureConnectionIsOpen]) return nil;
afc_directory dir;
if ([self checkStatus:AFCDirectoryOpen(_afc,[path UTF8String],&dir) from:"AFCDirectoryOpen"]) {
NSMutableArray *result = [NSMutableArray new];
while (1) {
char *d = NULL;
AFCDirectoryRead(_afc,dir,&d);
if (!d) break;
if (*d=='.') {
if (d[1]=='\000') continue; // skip '.'
if (d[1]=='.') {
if (d[2]=='\000') continue; // skip '..'
}
}
[result addObject:[NSString stringWithUTF8String:d]];
}
AFCDirectoryClose(_afc,dir);
self.lasterror = nil;
return [NSArray arrayWithArray:[result autorelease]];
}
// ret=4: path is a file
// ret=8: can't open path
return nil;
}
static BOOL read_dir( AFCDirectoryAccess *self, afc_connection afc, NSString *path, NSMutableArray *files )
{
BOOL result;
afc_directory dir;
int ret = AFCDirectoryOpen(afc,[path UTF8String],&dir);
if (ret == 4) {
// its a file, so add it in and return
[files addObject:path];
return YES;
}
if (ret != 0) {
// something other than a file causes us to fail
return [self checkStatus:ret from:"AFCDirectoryOpen"];
}
// collect us, with a trailing slash, since we are a directory
[files addObject:[NSString stringWithFormat:@"%@/",path]];
// build a list of all the files located here.
NSMutableArray *here = [NSMutableArray new];
while (1) {
char *d = NULL;
AFCDirectoryRead(afc,dir,&d);
if (!d) break;
if (*d=='.') {
if (d[1]=='\000') continue; // skip '.'
if (d[1]=='.') {
if (d[2]=='\000') continue; // skip '..'
}
}
[here addObject:[NSString stringWithFormat:@"%@/%s",path,d]];
}
AFCDirectoryClose(afc,dir);
// step through everything we found and add to the array
result = YES;
for (NSString *f in here) {
if (!read_dir(self, afc, f, files)) {
result = NO;
break;
}
}
[here release];
return result;
}
- (NSArray*)recursiveDirectoryContents:(NSString*)path
{
if (!path) {
self.lasterror = @"Input path is nil";
return nil;
}
if (![self ensureConnectionIsOpen]) return nil;
NSMutableArray *unsorted = [NSMutableArray new];
if (read_dir(self, _afc, path, unsorted)) {
[unsorted sortUsingSelector:@selector(compare:)];
NSArray *result = [NSArray arrayWithArray:unsorted];
[unsorted release];
return result;
}
[unsorted release];
return nil;
}
- (BOOL)mkdir:(NSString*)path
{
if (!path) {
self.lasterror = @"Input path is nil";
return NO;
}
if (![self ensureConnectionIsOpen]) return NO;
return [self checkStatus:AFCDirectoryCreate(_afc, [path UTF8String]) from:"AFCDirectoryCreate"];
}
- (BOOL)unlink:(NSString*)path
{
if (!path) {
self.lasterror = @"Input path is nil";
return NO;
}
if (![self ensureConnectionIsOpen]) return NO;
return [self checkStatus:AFCRemovePath(_afc, [path UTF8String]) from:"AFCRemovePath"];
}
- (BOOL)rename:(NSString*)path1 to:(NSString*)path2
{
if (!path1) {
self.lasterror = @"Old path is nil";
return NO;
}
if (!path2) {
self.lasterror = @"New path is nil";
return NO;
}
if (![self ensureConnectionIsOpen]) return NO;
return [self checkStatus:AFCRenamePath(_afc, [path1 UTF8String], [path2 UTF8String]) from:"AFCRenamePath"];
}
- (BOOL)link:(NSString*)path to:(NSString*)target
{
if (!path) {
self.lasterror = @"Path is nil";
return NO;
}
if (!target) {
self.lasterror = @"Target is nil";
return NO;
}
if (![self ensureConnectionIsOpen]) return NO;
return [self checkStatus:AFCLinkPath(_afc, 1, [target UTF8String], [path UTF8String]) from:"AFCLinkPath"];
}
- (BOOL)symlink:(NSString*)path to:(NSString*)target
{
if (!path) {
self.lasterror = @"Path is nil";
return NO;
}
if (!target) {
self.lasterror = @"Target is nil";
return NO;
}
if (![self ensureConnectionIsOpen]) return NO;
return [self checkStatus:AFCLinkPath(_afc, 2, [target UTF8String], [path UTF8String]) from:"AFCLinkPath"];
}
- (bool)processOp:(afc_operation)op from:(const char *)func
{
BOOL result = NO;
if ([self checkStatus:AFCConnectionProcessOperation(_afc, op, AFCConnectionGetIOTimeout(_afc)) from:"AFCConnectionProcessOperation"]) {
afc_error_t e = AFCOperationGetResultStatus(op);
if (e == 0) {
self.lasterror = nil;
result = YES;
} else {
CFTypeRef err = AFCConnectionCopyLastErrorInfo(_afc);
if (err) {
id msg = [(id)err objectForKey:@"NSLocalizedDescription"];
if (msg) {