Difference between revisions of "MobileDevice Library"

From The iPhone Wiki
Jump to: navigation, search
m (some more)
Line 235: Line 235:
 
 
 
 
/* Unregisters notifications. Buggy (iTunes 8.2): if you subscribe, unsubscribe and subscribe again, arriving
+
/* Unregisters notifications. Buggy (iTunes 8.2): if you subscribe, unsubscribe and subscribe again, arriving
notifications will contain cookie and subscription from 1st call to subscribe, not the 2nd one. iTunes
+
* notifications will contain cookie and subscription from 1st call to subscribe, not the 2nd one. iTunes
calls this function only once on exit.
+
* calls this function only once on exit. */
*/
 
 
__DLLIMPORT mach_error_t AMDeviceNotificationUnsubscribe(struct AMDeviceNotification *subscription);
 
__DLLIMPORT mach_error_t AMDeviceNotificationUnsubscribe(struct AMDeviceNotification *subscription);
 
 
Line 294: Line 293:
 
 
 
/* Reads various device settings. One of domain or cfstring arguments should be NULL.
 
/* Reads various device settings. One of domain or cfstring arguments should be NULL.
*
+
*
* ActivationPublicKey
+
* ActivationPublicKey
* ActivationState
+
* ActivationState
* ActivationStateAcknowledged
+
* ActivationStateAcknowledged
* ActivityURL
+
* ActivityURL
* BasebandBootloaderVersion
+
* BasebandBootloaderVersion
* BasebandSerialNumber
+
* BasebandSerialNumber
* BasebandStatus
+
* BasebandStatus
* BasebandVersion
+
* BasebandVersion
* BluetoothAddress
+
* BluetoothAddress
* BuildVersion
+
* BuildVersion
* CPUArchitecture
+
* CPUArchitecture
* DeviceCertificate
+
* DeviceCertificate
* DeviceClass
+
* DeviceClass
* DeviceColor
+
* DeviceColor
* DeviceName
+
* DeviceName
* DevicePublicKey
+
* DevicePublicKey
* DieID
+
* DieID
* FirmwareVersion
+
* FirmwareVersion
* HardwareModel
+
* HardwareModel
* HardwarePlatform
+
* HardwarePlatform
* HostAttached
+
* HostAttached
* IMLockdownEverRegisteredKey
+
* IMLockdownEverRegisteredKey
* IntegratedCircuitCardIdentity
+
* IntegratedCircuitCardIdentity
* InternationalMobileEquipmentIdentity
+
* InternationalMobileEquipmentIdentity
* InternationalMobileSubscriberIdentity
+
* InternationalMobileSubscriberIdentity
* iTunesHasConnected
+
* iTunesHasConnected
* MLBSerialNumber
+
* MLBSerialNumber
* MobileSubscriberCountryCode
+
* MobileSubscriberCountryCode
* MobileSubscriberNetworkCode
+
* MobileSubscriberNetworkCode
* ModelNumber
+
* ModelNumber
* PartitionType
+
* PartitionType
* PasswordProtected
+
* PasswordProtected
* PhoneNumber
+
* PhoneNumber
* ProductionSOC
+
* ProductionSOC
* ProductType
+
* ProductType
* ProductVersion
+
* ProductVersion
* ProtocolVersion
+
* ProtocolVersion
* ProximitySensorCalibration
+
* ProximitySensorCalibration
* RegionInfo
+
* RegionInfo
* SBLockdownEverRegisteredKey
+
* SBLockdownEverRegisteredKey
* SerialNumber
+
* SerialNumber
* SIMStatus
+
* SIMStatus
* SoftwareBehavior
+
* SoftwareBehavior
* SoftwareBundleVersion
+
* SoftwareBundleVersion
* SupportedDeviceFamilies
+
* SupportedDeviceFamilies
* TelephonyCapability
+
* TelephonyCapability
* TimeIntervalSince1970
+
* TimeIntervalSince1970
* TimeZone
+
* TimeZone
* TimeZoneOffsetFromUTC
+
* TimeZoneOffsetFromUTC
* TrustedHostAttached
+
* TrustedHostAttached
* UniqueChipID
+
* UniqueChipID
* UniqueDeviceID
+
* UniqueDeviceID
* UseActivityURL
+
* UseActivityURL
* UseRaptorCerts
+
* UseRaptorCerts
* Uses24HourClock
+
* Uses24HourClock
* WeDelivered
+
* WeDelivered
* WiFiAddress
+
* WiFiAddress
* // Updated by DiAifU 14.10.2010 for iOS5 and iTunes 5.0
+
* // Updated by DiAifU 14.10.2010 for iOS5 and iTunes 5.0
*
+
*
* Possible values for domain:
+
* Possible values for domain:
* com.apple.mobile.battery
+
* com.apple.mobile.battery
 
*/
 
*/
 
__DLLIMPORT CFStringRef AMDeviceCopyValue(struct AMDevice *device,
 
__DLLIMPORT CFStringRef AMDeviceCopyValue(struct AMDevice *device,
Line 405: Line 404:
 
 
 
 
/* Copy an environment variable value from iBoot
+
/* Copy an environment variable value from iBoot
*/
+
*/
__DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct AMRecoveryDevice *rdev,
+
__DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct AMRecoveryDevice *rdev,
 
CFStringRef str);
 
CFStringRef str);
 
 
Line 477: Line 476:
 
#endif
 
#endif
 
/* Opens file for reading or writing without locking it in any way. AFCFileRef should not be shared between threads -
 
/* Opens file for reading or writing without locking it in any way. AFCFileRef should not be shared between threads -
* opening file in one thread and closing it in another will lead to possible crash.
+
* opening file in one thread and closing it in another will lead to possible crash.
 
* path - UTF-8 encoded absolute path to file
 
* path - UTF-8 encoded absolute path to file
 
* mode - read (2); write (3); unknown (0)
 
* mode - read (2); write (3); unknown (0)
Line 502: Line 501:
 
* origin - 0 = from beginning, 1 = from current position, 2 = from end
 
* origin - 0 = from beginning, 1 = from current position, 2 = from end
 
*/
 
*/
__DLLIMPORT AFCError AFCFileRefSeek(struct afc_connection *conn, afc_file_ref ref,
+
__DLLIMPORT AFCError AFCFileRefSeek(struct AFCConnection *connection, afc_file_ref ref,
 
unsigned long long offset, int origin, int unused);
 
unsigned long long offset, int origin, int unused);
 
 
 
/* Gets the current position of a file pointer into offset argument.
 
/* Gets the current position of a file pointer into offset argument.
 
*/
 
*/
__DLLIMPORT AFCError AFCFileRefTell(struct afc_connection *conn, afc_file_ref ref,
+
__DLLIMPORT AFCError AFCFileRefTell(struct AFCConnection *connection, afc_file_ref ref,
 
unsigned long long* offset);
 
unsigned long long* offset);
 
 
 
/* Truncates a file at the specified offset.
 
/* Truncates a file at the specified offset.
 
*/
 
*/
__DLLIMPORT AFCError AFCFileRefSetFileSize(struct afc_connection *conn, afc_file_ref ref,
+
__DLLIMPORT AFCError AFCFileRefSetFileSize(struct AFCConnection *connection, afc_file_ref ref,
 
unsigned long long offset);
 
unsigned long long offset);
 
 
 
 
__DLLIMPORT AFCError AFCFileRefLock(struct afc_connection *conn, afc_file_ref ref);
+
__DLLIMPORT AFCError AFCFileRefLock(struct AFCConnection *connection, afc_file_ref ref);
__DLLIMPORT AFCError AFCFileRefUnlock(struct afc_connection *conn, afc_file_ref ref);
+
__DLLIMPORT AFCError AFCFileRefUnlock(struct AFCConnection *connection, afc_file_ref ref);
__DLLIMPORT AFCError AFCFileRefClose(struct afc_connection *conn, afc_file_ref ref);
+
__DLLIMPORT AFCError AFCFileRefClose(struct AFCConnection *connection, afc_file_ref ref);
 
 
 
/* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo
 
/* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo
 
to get the same information)
 
to get the same information)
 
*/
 
*/
__DLLIMPORT AFCError AFCFileInfoOpen(struct afc_connection *conn, char *path, struct
+
__DLLIMPORT AFCError AFCFileInfoOpen(struct AFCConnection *connection, char *path, struct
 
afc_dictionary **info);
 
afc_dictionary **info);
 
 
Line 535: Line 534:
 
"LinkTarget": val - path to symlink target
 
"LinkTarget": val - path to symlink target
 
*/
 
*/
__DLLIMPORT AFCError AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
+
__DLLIMPORT AFCError AFCKeyValueRead(struct AFCDictionary *dictionary,
val);
+
uint8_t **key,
  +
uint8_t **val);
 
/* Closes dictionary
 
/* Closes dictionary
 
*/
 
*/
__DLLIMPORT AFCError AFCKeyValueClose(struct afc_dictionary *dict);
+
__DLLIMPORT AFCError AFCKeyValueClose(struct AFCDictionary *dictionary);
 
 
 
 
 
/* Returns the context field of the given AFC connection. */
 
/* Returns the context field of the given AFC connection. */
__DLLIMPORT unsigned int AFCConnectionGetContext(struct afc_connection *conn);
+
__DLLIMPORT unsigned int AFCConnectionGetContext(struct AFCConnection *connection);
 
 
 
/* Returns the fs_block_size field of the given AFC connection. */
 
/* Returns the fs_block_size field of the given AFC connection. */
__DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct afc_connection *conn);
+
__DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct AFCConnection *connection);
 
 
 
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
 
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
 
* 0. */
 
* 0. */
__DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct afc_connection *conn);
+
__DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct AFCConnection *connection);
 
 
 
/* Returns the sock_block_size field of the given AFC connection. */
 
/* Returns the sock_block_size field of the given AFC connection. */
__DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct afc_connection *conn);
+
__DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct AFCConnection *connection);
 
 
 
/* Closes the given AFC connection. */
 
/* Closes the given AFC connection. */
__DLLIMPORT AFCError AFCConnectionClose(struct afc_connection *conn);
+
__DLLIMPORT AFCError AFCConnectionClose(struct AFCConnection *connection);
 
 
 
/* Registers for device notifications related to the restore process. unknown0
 
/* Registers for device notifications related to the restore process. unknown0
Line 566: Line 566:
 
* 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
 
* 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
 
*/
 
*/
__DLLIMPORT unsigned int AMRestoreRegisterForDeviceNotifications(
+
__DLLIMPORT uint32_t AMRestoreRegisterForDeviceNotifications(AMRestoreDeviceNotificationCallback dfuConnectCallback,
  +
AMRestoreDeviceNotificationCallback recoveryConnectCallback,
am_restore_device_notification_callback dfu_connect_callback,
 
  +
AMRestoreDeviceNotificationCallback dfuDisconectCallback,
am_restore_device_notification_callback recovery_connect_callback,
 
  +
AMRestoreDeviceNotificationCallback recoveryDisconnectCallback,
am_restore_device_notification_callback dfu_disconnect_callback,
 
  +
uint32_t unknown0,
am_restore_device_notification_callback recovery_disconnect_callback,
 
unsigned int unknown0,
+
void *userInfo);
void *user_info);
 
 
 
 
/* Causes the restore functions to spit out (unhelpful) progress messages to
 
/* Causes the restore functions to spit out (unhelpful) progress messages to
Line 580: Line 579:
 
* unused number.
 
* unused number.
 
*/
 
*/
__DLLIMPORT unsigned int AMRestoreEnableFileLogging(char *path);
+
__DLLIMPORT uint32_t AMRestoreEnableFileLogging(uint8_t *path);
 
 
 
/* Initializes a new option dictionary to default values. Pass the constant
 
/* Initializes a new option dictionary to default values. Pass the constant
Line 608: Line 607:
 
* ------------------------------------------------------------------------- */
 
* ------------------------------------------------------------------------- */
 
 
__DLLIMPORT unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
+
__DLLIMPORT uint32_t AMRestorePerformRecoveryModeRestore(struct AMRecoveryDevice *rdev,
  +
CFDictionaryRef options,
rdev, CFDictionaryRef opts, void *callback, void *user_info);
 
  +
void *callback,
__DLLIMPORT unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
 
  +
__DLLIMPORT uint32_t AMRestorePerformRestoreModeRestore(struct AMRecoveryDevice *rdev,
__DLLIMPORT struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
 
  +
CFDictionaryRef options,
unsigned int connection_id, unsigned int unknown1);
 
  +
void *callback,
__DLLIMPORT unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
 
  +
void *userInfo);
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
 
  +
__DLLIMPORT struct AMRestoreDevice* AMRestoreModeDeviceCreate(uint32_t unknown0,
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
 
  +
uint32_t connectionID,
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
 
ramdisk_path);
+
uint32_t unknown1);
  +
__DLLIMPORT uint32_t AMRestoreCreatePathsForBundle(CFStringRef restoreBundleType,
__DLLIMPORT unsigned int AMRestoreModeDeviceReboot(struct am_restore_device *rdev); // Added by JB 30.07.2008
 
  +
CFStringRef kernelCacheType,
__DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct am_device *device);
 
  +
CFStringRef bootImageType,
__DLLIMPORT mach_error_t AMDeviceDisconnect(struct am_device *device);
 
rdev, CFDictionaryRef opts, void *callback, void *user_info);
+
void *userInfo);
  +
uint32_t unknown0,
  +
CFStringRef *firwareDirectory,
  +
CFStringRef *kernelCacheRestorePath,
  +
uint32_t unknown1,
  +
CFStringRef *ramdiskPath);
  +
__DLLIMPORT uint32_t AMRestoreModeDeviceReboot(struct AMRestoreDevice *rdev);
  +
__DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct AMDevice *device);
  +
__DLLIMPORT mach_error_t AMDeviceDisconnect(struct AMDevice *device);
 
 
 
 
 
/* to use this, start the service "com.apple.mobile.notification_proxy", handle will be the socket to use */
 
/* to use this, start the service "com.apple.mobile.notification_proxy", handle will be the socket to use */
typedef void (*NOTIFY_CALLBACK)(CFSTR notification, USERDATA data);
+
typedef void (*AMDeviceNotifyCallback)(CFStringRef notification, USERDATA data);
__DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket, CFStringRef notification, CFStringRef userinfo);
+
__DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket,
  +
CFStringRef notification,
__DLLIMPORT mach_error_t AMDObserveNotification(SOCKET socket, CFSTR notification);
 
  +
CFStringRef userinfo);
__DLLIMPORT mach_error_t AMDListenForNotifications(SOCKET socket, NOTIFY_CALLBACK cb, USERDATA data);
 
  +
__DLLIMPORT mach_error_t AMDObserveNotification(SOCKET socket,
  +
CFStringRef notification);
  +
__DLLIMPORT mach_error_t AMDListenForNotifications(SOCKET socket,
  +
AMDeviceNotifyCallback callback,
  +
USERDATA userData);
 
__DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
 
__DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
 
 
  +
__DLLIMPORT mach_error_t AMDeviceDeactivate(struct AMDevice *device);
/*edits by geohot*/
 
__DLLIMPORT mach_error_t AMDeviceDeactivate(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDeviceActivate(struct AMDevice *device,
__DLLIMPORT mach_error_t AMDeviceActivate(struct am_device *device, CFDictionaryRef dict);
+
CFDictionaryRef dict);
__DLLIMPORT mach_error_t AMDeviceRemoveValue(struct am_device *device, unsigned int, CFStringRef cfstring);
+
__DLLIMPORT mach_error_t AMDeviceRemoveValue(struct AMDevice *device,
  +
uint32_t unknown,
  +
CFStringRef str);
 
 
 
/* ----------------------------------------------------------------------------
 
/* ----------------------------------------------------------------------------
Line 640: Line 654:
 
* ------------------------------------------------------------------------- */
 
* ------------------------------------------------------------------------- */
 
 
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
+
/* Pass in a USBMuxListener1 structure and a USBMuxListener2 structure
* pointer, which will be filled with the resulting usbmux_listener_2.
+
* pointer, which will be filled with the resulting USBMuxListener2.
 
*
 
*
 
* Returns:
 
* Returns:
Line 648: Line 662:
 
* MDERR_USBMUX_FAILED if the listener was not created successfully
 
* MDERR_USBMUX_FAILED if the listener was not created successfully
 
*/
 
*/
__DLLIMPORT usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
+
__DLLIMPORT USBMuxError USBMuxListenerCreate(struct USBMuxListener1 *source,
usbmux_listener_2 **eax_fp12);
+
struct USBMuxListener2 **destination);
 
 
 
/* ----------------------------------------------------------------------------
 
/* ----------------------------------------------------------------------------
 
* Less-documented semi-private routines
 
* Less-documented semi-private routines
 
* ------------------------------------------------------------------------- */
 
* ------------------------------------------------------------------------- */
__DLLIMPORT usbmux_error_t USBMuxListenerHandleData(void *);
+
__DLLIMPORT USBMuxError USBMuxListenerHandleData(void *unknown);
 
 
 
/* ----------------------------------------------------------------------------
 
/* ----------------------------------------------------------------------------
* Private routines - here be dragons
+
* Private routines - no exports means no function declarations
 
* ------------------------------------------------------------------------- */
 
* ------------------------------------------------------------------------- */
 
 
Line 666: Line 680:
 
 
 
/*
 
/*
typedef unsigned int (*t_performOperation)(struct am_restore_device *rdev,
+
typedef unsigned int (*t_performOperation)(struct AMRestoreDevice *device, CFDictionaryRef operation)__attribute__ ((regparm(2)));
CFDictionaryRef op) __attribute__ ((regparm(2)));
 
 
t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
 
t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
 
*/
 
*/
Line 677: Line 690:
 
 
 
/*
 
/*
typedef int (*t_socketForPort)(struct am_restore_device *rdev, unsigned int port)
+
typedef int32_t (*t_socketForPort)(struct AMRestoreDevice *device, unsigned int port)__attribute__ ((regparm(2)));
  +
t_socketForPort _socketForPort = (t_socketForPort)0x3c39f36c;
__attribute__ ((regparm(2)));
 
t_socketForPort _socketForPort = (t_socketForPort)(void *)0x3c39f36c;
 
 
 
 
typedef void (*t_restored_send_message)(int port, CFDictionaryRef msg);
 
typedef void (*t_restored_send_message)(int port, CFDictionaryRef msg);
Line 687: Line 699:
 
t_restored_receive_message _restored_receive_message = (t_restored_receive_message)0x3c3a4d40;
 
t_restored_receive_message _restored_receive_message = (t_restored_receive_message)0x3c3a4d40;
 
 
typedef unsigned int (*t_sendControlPacket)(struct am_recovery_device *rdev, unsigned
+
typedef uint32_t (*t_sendControlPacket)(struct AMRecoveryDevice *device, uint32_t message1, uint32_t message2, uint32_t unknown0, uint32_t *unknown1, uint8_t *unknown2)__attribute__ ((regparm(3)));
int msg1, unsigned int msg2, unsigned int unknown0, unsigned int *unknown1,
 
unsigned char *unknown2) __attribute__ ((regparm(3)));
 
 
t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
 
t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
 
 
typedef unsigned int (*t_sendCommandToDevice)(struct am_recovery_device *rdev,
+
typedef uint32_t (*t_sendCommandToDevice)(struct AMRecoveryDevice *device, CFStringRef command)__attribute__ ((regparm(2)));
CFStringRef cmd) __attribute__ ((regparm(2)));
 
 
t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
 
t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
 
 
typedef unsigned int (*t_AMRUSBInterfaceReadPipe)(unsigned int readwrite_pipe, unsigned
+
typedef uint32_t (*t_AMRUSBInterfaceReadPipe)(uint32_t readwrite_pipe, uint32_t read_pipe, uint8_t *buffer, uint32_t *length);
int read_pipe, unsigned char *data, unsigned int *len);
 
 
t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
 
t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
 
 
typedef unsigned int (*t_AMRUSBInterfaceWritePipe)(unsigned int readwrite_pipe, unsigned
+
typedef uint32_t (*t_AMRUSBInterfaceWritePipe)(uint32_t readWritePipe, uint32_t writePipe, void *data, uint32_t length);
int write_pipe, void *data, unsigned int len);
 
 
t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
 
t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
 
*/
 
*/
 
 
int performOperation(am_restore_device *rdev, CFMutableDictionaryRef message);
+
int32_t performOperation(AMRestoreDevice *device,
  +
CFMutableDictionaryRef message);
int socketForPort(am_restore_device *rdev, unsigned int portnum);
 
  +
int32_t socketForPort(AMRestoreDevice *device,
int sendCommandToDevice(am_recovery_device *rdev, CFStringRef cfs, int block);
 
  +
uint32_t portnum);
int sendFileToDevice(am_recovery_device *rdev, CFStringRef filename);
 
  +
int32_t sendCommandToDevice(AMRestoreDevice *device,
 
  +
CFStringRef command,
  +
int block);
  +
int32_t sendFileToDevice(AMRestoreDevice *device,
  +
CFStringRef fileName);
 
 
 
#if !defined(__GCC__)
 
#if !defined(__GCC__)
Line 720: Line 731:
 
#endif
 
#endif
 
 
#endif
+
#endif /* MOBILEDEVICE_H */
 
/* -*- mode:c; indent-tabs-mode:nil; c-basic-offset:2; tab-width:2; */
 
   
 
=== AFC Connection ===
 
=== AFC Connection ===
Line 738: Line 747:
   
 
Next we open the itunes lock file:
 
Next we open the itunes lock file:
afc_file_ref lockref;
+
AFCFileRef lockref;
 
AFCFileRefOpen(conn, "/com.apple.itunes.lock_sync", 2, &lockref);
 
AFCFileRefOpen(conn, "/com.apple.itunes.lock_sync", 2, &lockref);
   
Line 747: Line 756:
   
 
When the file is successfully locked, post another notification, and stop the notification service.
 
When the file is successfully locked, post another notification, and stop the notification service.
AMDPostNotification(socket,CFSTR("com.apple.itunes-mobdev.syncDidStart"), NULL);
+
AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncDidStart"), NULL);
 
AMDShutdownNotificationProxy(socket);
 
AMDShutdownNotificationProxy(socket);
   
Line 760: Line 769:
 
AMDShutdownNotificationProxy(socket);
 
AMDShutdownNotificationProxy(socket);
   
To handle "Slide to Cancel" and terminate sync when user slides cancel switch, use AMDObserveNotification to subscribe notifications about “com.apple.itunes-client.syncCancelRequest”. Then start listening for notifications (AMDListenForNotifications) until you get “AMDNotificationFaceplant”.
+
To handle "Slide to Cancel" and terminate sync when user slides cancel switch, use AMDObserveNotification to subscribe notifications about "com.apple.itunes-client.syncCancelRequest". Then start listening for notifications (AMDListenForNotifications) until you get "AMDNotificationFaceplant".
When notification got, you should unlock and close lock file handle (don’t sure if you need to post “syncDidFinish” to proxy, seems it doesn’t matter) and terminate sync gracefully.
+
When notification got, you should unlock and close lock file handle (don’t sure if you need to post “syncDidFinish” to proxy, seems it doesn't matter) and terminate sync gracefully.
 
The same notification is also got when you unplug your device, so you should always be ready for errors.
 
The same notification is also got when you unplug your device, so you should always be ready for errors.
   
NOTE: You may find that starting the notification_proxy service once and once only at the start of your app and using the same socket in calls to AMDPostNotification works better. [[iTunes]] opens and closes the notification_proxy regularly, but it appears to be a bit flakey when you open/close it all the time.
+
NOTE: You may find that starting the notification_proxy service once and once only at the start of your app and using the same socket in calls to AMDPostNotification works better. [[iTunes]] opens and closes the notification_proxy regularly, but it appears to be a bit flaky when you open/close it all the time.
   
 
=== Known Functions ===
 
=== Known Functions ===
  +
These are functions that are known to exist, but their decleration is unknown:
 
* AFCLockCreate
 
* AFCLockCreate
 
* AFCLockFree
 
* AFCLockFree
Line 1,013: Line 1,023:
   
 
=== Private Functions ===
 
=== Private Functions ===
  +
==== Obtaining address ====
==== How to find address of privates functions in iTunesMobileDevice.dll or MobileDevice.framework ====
 
 
In order to obtain the address of a usable private function in MobileDevice, you will have to be able to understand x86-64 assembly to reverse engineer it. A private function will not have its name exported in the mach-o symbol table, so in a debugger, like GDB, it will show up as part of another function. However, you will know that it is a separate function as a new stack frame is set up.
 
In order to obtain the address of a usable private function in MobileDevice, you will have to be able to understand x86-64 assembly to reverse engineer it. A private function will not have its name exported in the mach-o symbol table, so in a debugger, like GDB, it will show up as part of another function. However, you will know that it is a separate function as a new stack frame is set up.
   
Line 1,027: Line 1,037:
 
# an integer, whose use is currently unknown, but should be set to 0 to work.
 
# an integer, whose use is currently unknown, but should be set to 0 to work.
   
unsigned int sendFileToiDevice(struct am_recovery_device *rdev, CFStringRef filename);
+
uint32_t sendFileToDevice(struct AMRecoveryDevice *device, CFStringRef fileName);
 
Address is obtainable by adding 1763(0x6e3) to the address of AMRecoveryDeviceGetProductType(), a public symbol that you can obtain via nlist() or dlsym().
 
Address is obtainable by adding 1763(0x6e3) to the address of AMRecoveryDeviceGetProductType(), a public symbol that you can obtain via nlist() or dlsym().
 
Address: <code>0x100024969</code>
 
Address: <code>0x100024969</code>
Line 1,036: Line 1,046:
   
 
===== OSX 10.6 - [[iTunes]] 9.0.3(15) =====
 
===== OSX 10.6 - [[iTunes]] 9.0.3(15) =====
unsigned int sendCommandToiBoot(struct am_recovery_device *rdev, CFStringRef command, int u);
+
unsigned int sendCommandToIBoot(struct AMRecoveryDevice *device, CFStringRef command, int unknown);
 
Addresss: <code>AMRecoveryDeviceGetProductType() + 0x37f(895); full offset: 0x2a0ed</code>
 
Addresss: <code>AMRecoveryDeviceGetProductType() + 0x37f(895); full offset: 0x2a0ed</code>
   
unsigned int sendFileToiDevice(struct am_recovery_device *rdev, CFStringRef filename);
+
unsigned int sendFileToDevice(struct AMRecoveryDevice *device, CFStringRef filename);
 
Address: <code>AMRecoveryDeviceGetProductType()+0x6f3(1790); full offset: 0x2a46c</code>
 
Address: <code>AMRecoveryDeviceGetProductType()+0x6f3(1790); full offset: 0x2a46c</code>
   
Line 1,051: Line 1,061:
   
 
=== Known Error Codes ===
 
=== Known Error Codes ===
 
 
* kAMDProhibitedBySupervision = -402653053
 
* kAMDProhibitedBySupervision = -402653053
 
* kAMDAlreadyArchivedError = -402653094
 
* kAMDAlreadyArchivedError = -402653094

Revision as of 23:17, 4 January 2013

MobileDevice Library is used by iTunes to transfer data between iPhone and computer over the USB connection.

PC Windows : iTunesMobileDevice.dll

The DLL is written using Microsoft Visual C++ 8.0 DLL Method [2].

  • Location: iTunesMobileDeviceDLL registry value under HKLM\SOFTWARE\Apple Inc.\Apple Mobile Device Support\Shared key.
  • Supporting CoreFoundation.dll (used for CFStringRef, CFPropertyListRef management) is located in the same dir (when using iTunes prior 9.0).
  • For iTunes 9.0, the location of CoreFoundation.dll is stored in InstallDir registry value under HKLM\SOFTWARE\Apple Inc.\Apple Application Support registry key.

Mac OSX : MobileDevice.framework

  • Location: /System/Library/PrivateFrameworks/MobileDevice.framework
  • Export command: nm /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice

MobileDevice Header (MobileDevice.h)

Reverse engineered C header for MobileDevice Library. If a variable is labeled _unknown followed by a number, it means it's purpose has yet to be discovered. The comments next to a variable specify the variable's offset into the structure while assuming the size of a pointer (sizeof(void*)) is 4 bytes, or 32-bits. If a variable's comment mentions that it's size is unknown, it means the size of the array isn't known.

Some of this information was stolen taken from MobileDeviceSupport.m from iScrobbler.

/* -------------------------------------------------------- *
 *   MobileDevice.h - interface to MobileDevice.framework   *
 * -------------------------------------------------------- */

#ifndef MOBILEDEVICE_H
#define MOBILEDEVICE_H

#if defined(__cplusplus)
extern "C" {
#endif
    
#ifndef __GCC__
#  pragma pack(push, 1)
#  define __PACK
#else
#  define __PACK __attribute__((__packed__))
#endif

#if defined(WIN32)
#  define __DLLIMPORT [DllImport("iTunesMobileDevice.dll")]
    using namespace System::Runtime::InteropServices;
#  include <CoreFoundation.h>
    typedef unsigned int mach_error_t;
#elif defined(__APPLE__)
#  define __DLLIMPORT
#  include <CoreFoundation/CoreFoundation.h>
#  include <mach/error.h>
#endif    
    
    /* Error codes */
#define MDERR_APPLE_MOBILE  (err_system(0x3a))
#define MDERR_IPHONE        (err_sub(0))
    
    /* Apple Mobile (AM*) errors */
#define MDERR_OK                ERR_SUCCESS
#define MDERR_SYSCALL           (ERR_MOBILE_DEVICE | 0x01)
#define MDERR_OUT_OF_MEMORY     (ERR_MOBILE_DEVICE | 0x03)
#define MDERR_QUERY_FAILED      (ERR_MOBILE_DEVICE | 0x04) 
#define MDERR_INVALID_ARGUMENT  (ERR_MOBILE_DEVICE | 0x0b)
#define MDERR_DICT_NOT_LOADED   (ERR_MOBILE_DEVICE | 0x25)
    
    /* Apple File Connection (AFC*) errors */
#define MDERR_AFC_OUT_OF_MEMORY 0x03
    
    /* USBMux errors */
#define MDERR_USBMUX_ARG_NULL   0x16
#define MDERR_USBMUX_FAILED     0xffffffff
    
    /* Messages passed to device notification callbacks: passed as part of
     * AMDeviceNotificationCallbackInfo. */
#define ADNCI_MSG_CONNECTED     1
#define ADNCI_MSG_DISCONNECTED  2
#define ADNCI_MSG_UNSUBSCRIBED  3
    
#define AMD_IPHONE_PRODUCT_ID   0x1290
    //#define AMD_IPHONE_SERIAL       ""
    
    /* Services, found in /System/Library/Lockdown/Services.plist */
#define AMSVC_AFC                   CFSTR("com.apple.afc")
#define AMSVC_BACKUP                CFSTR("com.apple.mobilebackup")
#define AMSVC_CRASH_REPORT_COPY     CFSTR("com.apple.crashreportcopy")
#define AMSVC_DEBUG_IMAGE_MOUNT     CFSTR("com.apple.mobile.debug_image_mount")
#define AMSVC_NOTIFICATION_PROXY    CFSTR("com.apple.mobile.notification_proxy")
#define AMSVC_PURPLE_TEST           CFSTR("com.apple.purpletestr")
#define AMSVC_SOFTWARE_UPDATE       CFSTR("com.apple.mobile.software_update")
#define AMSVC_SYNC                  CFSTR("com.apple.mobilesync")
#define AMSVC_SCREENSHOT            CFSTR("com.apple.screenshotr")
#define AMSVC_SYSLOG_RELAY          CFSTR("com.apple.syslog_relay")
#define AMSVC_SYSTEM_PROFILER       CFSTR("com.apple.mobile.system_profiler")
    
    typedef uint32_t AFCError;
    typedef uint32_t usbmux_error_t;
    
    struct AMRecoveryDevice;
    
    struct AMDeviceNotificationCallbackInfo {
        struct AMDevice *_device;                   /* 0 - device */ 
        uint32_t _message;                          /* 4 - one of ADNCI_MSG_* */
               struct AMDeviceNotification* _subscription; /* 8 */
    } __PACK;
    
    /* The type of the device restore notification callback functions.
     * TODO: change to correct type. */
    typedef void (*AMRestoreDeviceNotificationCallback)(struct AMRecoveryDevice*);
    
    /* This is a CoreFoundation object of class AMRecoveryModeDevice. */
    struct AMRecoveryDevice {
        uint8_t _unknown0[8];                          /* 0  */
        AMRestoreDeviceNotificationCallback _callback; /* 8  */
        void *_userInfo;                               /* 12 */
        uint8_t unknown1[12];                          /* 16 */
        uint32_t _readWritePipe;                       /* 28 */
        uint8_t _readPipe;                             /* 32 */
        uint8_t _writeControlPipe;                     /* 33 */
        uint8_t _readUnknownPipe;                      /* 34 */
        uint8_t _writeFilePipe;                        /* 35 */
        uint8_t _writeInputPipe;                       /* 36 */
    } __PACK;
    
    /* A CoreFoundation object of class AMRestoreModeDevice. */
    struct AMRestoreDevice {
        uint8_t _unknown[32]; /* 0 */
        int32_t _port;        /* 32 */
    } __PACK;
    
    /* The type of the device notification callback function. */
    typedef void (*AMDeviceNotificationCallback)(struct AMDeviceNotificationCallbackInfo*, int _cookie);
    
    /* The type of the _AMDDeviceAttached function.
     * TODO: change to correct type. */
    typedef void *AMDDeviceAttatchedCallback;
    
    /* The type of the device restore notification callback functions.
     * TODO: change to correct type. */
    typedef void (*AMRestoreDeviceNotificationCallback)(struct AMRecoveryDevice*);

    /* Structure that contains internal data used by AMDevice... functions. Never try 
        * to access its members directly! Use AMDeviceCopyDeviceIdentifier, 
        * AMDeviceGetConnectionID, AMDeviceRetain, AMDeviceRelease instead. */
    struct AMDevice {
        uint8_t _uuid[16];            /* 0  - Unique Device Identifier */
        uint32_t _deviceID;           /* 16 */
        uint32_t _productID;          /* 20 - set to AMD_IPHONE_PRODUCT_ID */
        CFStringRef _serial;          /* 24 - serial string of device */
        uint32_t _unknown0;           /* 28 */
        uint32_t _unknown1;           /* 32 - reference counter, increased by AMDeviceRetain, decreased by AMDeviceRelease */
        uint32_t _lockdownConnection; /* 36 */
        uint8_t _unknown2[8];         /* 40 */
#if (__ITUNES_VER > 740)
        uint32_t _unknown3;           /* 48 - used to store CriticalSection Handle*/
#endif
#if (__ITUNES_VER >= 800)
        uint8_t _unknown4[24];        /* 52 */
#endif
    } __PACK;
    
    struct AMDeviceNotification {
        uint32_t _unknown0;                     /* 0  */
        uint32_t _unknown1;                     /* 4  */
        uint32_t _unknown2;                     /* 8  */
        AMDeviceNotificationCallback _callback; /* 12 */ 
        uint32_t _cookie;                       /* 16 */
    } __PACK;
    
    struct AFCConnection {
        uint32_t _handle;          /* 0  */
        uint32_t _unknown0;        /* 4  */
        uint8_t _unknown1;         /* 8  */
        uint8_t _padding[3];       /* 9  */
        uint32_t _unknown2;        /* 12 */
        uint32_t _unknown3;        /* 16 */
        uint32_t _unknown4;        /* 20 */
        uint32_t _fsBlockSize;     /* 24 */
        uint32_t _socketBlockSize; /* 28 - always 0x3c */
        uint32_t _ioTimeout;       /* 32 - from AFCConnectionOpen, usu. 0 */
        void *_afcLock;            /* 36 */
        uint32_t _context;         /* 40 */
    } __PACK;
    
    struct AFCDeviceInfo {
        uint8_t _unknown[12]; /* 0 */
    } __PACK;

    struct AFCDirectory {
        uint8_t _unknown[0]; /* 0 - size unknown */
    } __PACK;

    struct AFCDictionary {
        uint8_t _unknown[0]; /* 0 - size unknown */
    } __PACK;
    
    typedef uint64_t AFCFileRef;
    
    struct USBMuxListener1 { 
        uint32_t _unknown0;                   /* 0  - set to 1 */
        void *_unknown1;                      /* 4  */
        AMDDeviceAttatchedCallback _callback; /* 8  - set to _AMDDeviceAttached */
        uint32_t _unknown3;                   /* 12 */
        uint32_t _unknown4;                   /* 16 */
        uint32_t _unknown5;                   /* 20 */
    } __PACK;
    
    struct USBMuxListener2 {
        uint8_t _unknown0[4144]; /* 0 - most likely a packet buffer */
    } __PACK;
    
    struct AMBootloaderControlPacket {
        uint8_t _opcode;     /* 0 */
        uint8_t _length;     /* 1 */
        uint8_t _magic[2];   /* 2 - set to 0x34, 0x12 */
        uint8_t _payload[0]; /* 4 - size unknown */
    } __PACK;
    
    /* ----------------------------------------------------------------------------
     *   Public routines
     * ------------------------------------------------------------------------- */
    
    /*  Registers a notification with the current run loop. The callback gets
     *  copied into the notification struct, as well as being registered with the
     *  current run loop. Cookie gets copied into cookie in the same.
     *  (Cookie is a user info parameter that gets passed as an arg to
     *  the callback) unused0 and unused1 are both 0 when iTunes calls this.
     *
     *  Never try to access directly or copy contents of dev and subscription fields 
     *  in am_device_notification_callback_info. Treat them as abstract handles. 
     *  When done with connection use AMDeviceRelease to free resources allocated for am_device.
     *  
     *  Returns:
     *      MDERR_OK            if successful
     *      MDERR_SYSCALL       if CFRunLoopAddSource() failed
     *      MDERR_OUT_OF_MEMORY if we ran out of memory
     */
    __DLLIMPORT mach_error_t AMDeviceNotificationSubscribe(AMDeviceNotificationCallback callback, 
                                                           uint32_t unused0,
                                                          uint32_t unused1, 
                                                           uint32_t cookie, 
                                                           struct AMDeviceNotification **subscription);
    

    /*  Unregisters notifications. Buggy (iTunes 8.2): if you subscribe, unsubscribe and subscribe again, arriving 
     * notifications will contain cookie and subscription from 1st call to subscribe, not the 2nd one. iTunes 
     * calls this function only once on exit. */
    __DLLIMPORT mach_error_t AMDeviceNotificationUnsubscribe(struct AMDeviceNotification *subscription);

    /*  Returns _deviceID field of AMDevice structure
     */
    __DLLIMPORT uint32_t AMDeviceGetConnectionID(struct AMDevice *device);

    /*  Returns serial field of AMDevice structure
     */
    __DLLIMPORT CFStringRef AMDeviceCopyDeviceIdentifier(struct AMDevice *device);

    /*  Connects to the iPhone. Pass in the AMDevice structure that the
     *  notification callback will give to you.
     *
     *  Returns:
     *      MDERR_OK                if successfully connected
     *      MDERR_SYSCALL           if setsockopt() failed
     *      MDERR_QUERY_FAILED      if the daemon query failed
     *      MDERR_INVALID_ARGUMENT  if USBMuxConnectByPort returned 0xffffffff
     */
    __DLLIMPORT mach_error_t AMDeviceConnect(struct AMDevice *device);
    
    /*  Calls PairingRecordPath() on the given device, than tests whether the path
     *  which that function returns exists. During the initial connect, the path
     *  returned by that function is '/', and so this returns 1.
     *
     *  Returns:
     *      0   if the path did not exist
     *      1   if it did
     */
    __DLLIMPORT mach_error_t AMDeviceIsPaired(struct AMDevice *device);
    __DLLIMPORT mach_error_t AMDevicePair(struct AMDevice *device);
    
    /*  iTunes calls this function immediately after testing whether the device is
     *  paired. It creates a pairing file and establishes a Lockdown connection.
     *
     *  Returns:
     *      MDERR_OK                if successful
     *      MDERR_INVALID_ARGUMENT  if the supplied device is null
     *      MDERR_DICT_NOT_LOADED   if the load_dict() call failed
     */
    __DLLIMPORT mach_error_t AMDeviceValidatePairing(struct AMDevice *device);
    
    /*  Creates a Lockdown session and adjusts the device structure appropriately
     *  to indicate that the session has been started. iTunes calls this function
     *  after validating pairing.
     *
     *  Returns:
     *      MDERR_OK                if successful
     *      MDERR_INVALID_ARGUMENT  if the Lockdown conn has not been established
     *      MDERR_DICT_NOT_LOADED   if the load_dict() call failed
     */
    __DLLIMPORT mach_error_t AMDeviceStartSession(struct AMDevice *device);


    /* Reads various device settings. One of domain or cfstring arguments should be NULL.
     *
     * ActivationPublicKey 
     * ActivationState 
     * ActivationStateAcknowledged 
     * ActivityURL 
     * BasebandBootloaderVersion 
     * BasebandSerialNumber 
     * BasebandStatus 
     * BasebandVersion 
     * BluetoothAddress 
     * BuildVersion 
     * CPUArchitecture 
     * DeviceCertificate 
     * DeviceClass 
     * DeviceColor 
     * DeviceName 
     * DevicePublicKey 
     * DieID 
     * FirmwareVersion 
     * HardwareModel 
     * HardwarePlatform 
     * HostAttached 
     * IMLockdownEverRegisteredKey 
     * IntegratedCircuitCardIdentity 
     * InternationalMobileEquipmentIdentity 
     * InternationalMobileSubscriberIdentity 
     * iTunesHasConnected 
     * MLBSerialNumber 
     * MobileSubscriberCountryCode 
     * MobileSubscriberNetworkCode 
     * ModelNumber 
     * PartitionType 
     * PasswordProtected 
     * PhoneNumber 
     * ProductionSOC 
     * ProductType 
     * ProductVersion 
     * ProtocolVersion 
     * ProximitySensorCalibration 
     * RegionInfo 
     * SBLockdownEverRegisteredKey 
     * SerialNumber 
     * SIMStatus 
     * SoftwareBehavior 
     * SoftwareBundleVersion 
     * SupportedDeviceFamilies 
     * TelephonyCapability 
     * TimeIntervalSince1970 
     * TimeZone 
     * TimeZoneOffsetFromUTC 
     * TrustedHostAttached 
     * UniqueChipID 
     * UniqueDeviceID 
     * UseActivityURL 
     * UseRaptorCerts 
     * Uses24HourClock 
     * WeDelivered 
     * WiFiAddress 
     * // Updated by DiAifU 14.10.2010 for iOS5 and iTunes 5.0
     *
     * Possible values for domain:
     * com.apple.mobile.battery
     */
    __DLLIMPORT CFStringRef AMDeviceCopyValue(struct AMDevice *device,
                                              CFStringRef domain,
                                              CFStringRef str);
    
    /* Starts a service and returns a socket file descriptor that can be used in order to further
     * access the service. You should stop the session and disconnect before using
     * the service. iTunes calls this function after starting a session. It starts 
     * the service and the SSL connection. service_name should be one of the AMSVC_*
     * constants.
     *
     * Returns:
     *      MDERR_OK                if successful
     *      MDERR_SYSCALL           if the setsockopt() call failed
     *      MDERR_INVALID_ARGUMENT  if the Lockdown conn has not been established
     */
    __DLLIMPORT mach_error_t AMDeviceStartService(struct AMDevice *device,
                                                  CFStringRef sericeName,
                                                  int32_t *sockedFD);
    
    /* Stops a session. You should do this before accessing services.
     *
     * Returns:
     *      MDERR_OK                if successful
     *      MDERR_INVALID_ARGUMENT  if the Lockdown conn has not been established
     */
    __DLLIMPORT mach_error_t AMDeviceStopSession(struct AMDevice *device);
    
    /* Decrements reference counter and, if nothing left, releases resources hold 
     * by connection, invalidates  pointer to device
     */
    __DLLIMPORT void AMDeviceRelease(struct AMDevice *device);

    /* Increments reference counter
     */
    __DLLIMPORT void AMDeviceRetain(struct AMDevice *device);

    /* Opens an Apple File Connection. You must start the appropriate service
     * first with AMDeviceStartService(). In iTunes, io_timeout is 0.
     *
     * Returns:
     *      MDERR_OK                if successful
     *      MDERR_AFC_OUT_OF_MEMORY if malloc() failed
     */
    __DLLIMPORT AFCError AFCConnectionOpen(int32_t socketFD,
                                           uint32_t ioTimeout,
                                           struct AFCConnection **connection);


    /* Copy an environment variable value from iBoot
     */
    __DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct AMRecoveryDevice *rdev,
                                                                  CFStringRef str);
    
    /* Pass in a pointer to an afc_dictionary structure. It will be filled. You can
     * iterate it using AFCKeyValueRead. When done use AFCKeyValueClose. Possible keys:
     * FSFreeBytes - free bytes on system device for afc2, user device for afc
     * FSBlockSize - filesystem block size
     * FSTotalBytes - size of device
     * Model - iPhone1,1 etc.

     */
    __DLLIMPORT AFCError AFCDeviceInfoOpen(struct AFCConnection *connection,
                                           struct AFCDictionary **info);
    
    /* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric
     * value, or if the file '/AFCDEBUG' is present and contains a value. */
#if defined(__APPLE__)
    void AFCPlatformInitialize();
#endif
    
    /* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in.
     * Note that this normally only accesses the iTunes sandbox/partition as the
     * root, which is /var/root/Media. Pathnames are specified with '/' delimiters
     * as in Unix style. Use UTF-8 to specify non-ASCII symbols in path.
     *
     * Returns:
     *      MDERR_OK                if successful
     */
    __DLLIMPORT AFCError AFCDirectoryOpen(struct AFCConnection *connection,
                                       uint8_t *path,
                                       struct AFCDirectory **directory);
    
    /* I'm not completely sure they are char pointers
     * as Apple always uses CFStringRef */
    
    /* Acquires the next entry in a directory previously opened with
     * AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
     * of the directory has been reached. '.' and '..' will be returned as the
     * first two entries in each directory except the root; you may want to skip
     * over them.
     *
     * Returns:
     *      MDERR_OK                if successful, even if no entries remain
     */
    __DLLIMPORT AFCError AFCDirectoryRead(struct AFCConnection *connection,
                                          struct AFCDirectory *directory,
                                          uint8_t **dirent);
    __DLLIMPORT AFCError AFCDirectoryClose(struct AFCConnection *connection,
                                           struct AFCDirectory *directory);
    __DLLIMPORT AFCError AFCDirectoryCreate(struct AFCConnection *connection,
                                         uint8_t *directory);
    __DLLIMPORT AFCError AFCRemovePath(struct AFCConnection *connection,
                                    uint8_t *directory);
    __DLLIMPORT AFCError AFCRenamePath(struct AFCConnection *connection,
                                    uint8_t *oldPath,
                                    uint8_t *newPath);
    
#if (__ITUNES_VER >= 800)
    /* Creates symbolic or hard link
        * linktype - int64: 1 means hard link, 2 - soft (symbolic) link
        * target - absolute or relative path to link target
        * linkname - absolute path where to create new link
     */
    __DLLIMPORT AFCError AFCLinkPath(struct AFCConnection *connection,
                                  int64_t linkType,
                                  uint8_t *target, 
                                  uint8_t *linkName);

#endif
    /* Opens file for reading or writing without locking it in any way. AFCFileRef should not be shared between threads - 
     * opening file in one thread and closing it in another will lead to possible crash.
     * path - UTF-8 encoded absolute path to file
     * mode - read (2); write (3); unknown (0)
     * fileRef - receives file handle
     */
    __DLLIMPORT AFCError AFCFileRefOpen(struct AFCConnection *connection,
                                     uint8_t *path,
                                     uint64_t mode,
                                     AFCFileRef *fileRef);
    /* Reads specified amount (len) of bytes from file into buf. Puts actual count of read bytes into len on return
     */
    __DLLIMPORT AFCError AFCFileRefRead(struct AFCConnection *connection,
                                      AFCFileRef fileRef,
                                      void *buffer,
                                      uint32_t *length);
    /* Writes specified amount (len) of bytes from buf into file.
     */
    __DLLIMPORT AFCError AFCFileRefWrite(struct AFCConnection *connection,
                                      AFCFileRef ref,
                                      void *buffer,
                                      uint32_t length);
    /* Moves the file pointer to a specified location.
     * offset - Number of bytes from origin (int64)
     * origin - 0 = from beginning, 1 = from current position, 2 = from end
     */
    __DLLIMPORT AFCError AFCFileRefSeek(struct AFCConnection *connection, afc_file_ref ref,
                               unsigned long long offset, int origin, int unused);

    /* Gets the current position of a file pointer into offset argument.
     */
    __DLLIMPORT AFCError AFCFileRefTell(struct AFCConnection *connection, afc_file_ref ref,
                               unsigned long long* offset);

    /*  Truncates a file at the specified offset.
     */
    __DLLIMPORT AFCError AFCFileRefSetFileSize(struct AFCConnection *connection, afc_file_ref ref,
                               unsigned long long offset);


    __DLLIMPORT AFCError AFCFileRefLock(struct AFCConnection *connection, afc_file_ref ref);
    __DLLIMPORT AFCError AFCFileRefUnlock(struct AFCConnection *connection, afc_file_ref ref);
    __DLLIMPORT AFCError AFCFileRefClose(struct AFCConnection *connection, afc_file_ref ref);

    /* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo
       to get the same information)
    */
    __DLLIMPORT AFCError AFCFileInfoOpen(struct AFCConnection *connection, char *path, struct
                                afc_dictionary **info);

    /* Reads next entry from dictionary. When last entry is read, function returns NULL in key argument
       Possible keys:
         "st_size":     val - size in bytes
         "st_blocks":   val - size in blocks
         "st_nlink":    val - number of hardlinks
         "st_ifmt":     val - "S_IFDIR" for folders
                            "S_IFLNK" for symlinks
         "LinkTarget":  val - path to symlink target
    */
    __DLLIMPORT AFCError AFCKeyValueRead(struct AFCDictionary *dictionary,
                                         uint8_t **key,
                                         uint8_t **val);
    /* Closes dictionary
    */
    __DLLIMPORT AFCError AFCKeyValueClose(struct AFCDictionary *dictionary);

    
    /* Returns the context field of the given AFC connection. */
    __DLLIMPORT unsigned int AFCConnectionGetContext(struct AFCConnection *connection);
    
    /* Returns the fs_block_size field of the given AFC connection. */
    __DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct AFCConnection *connection);
    
    /* Returns the io_timeout field of the given AFC connection. In iTunes this is
     * 0. */
    __DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct AFCConnection *connection);
    
    /* Returns the sock_block_size field of the given AFC connection. */
    __DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct AFCConnection *connection);
    
    /* Closes the given AFC connection. */
    __DLLIMPORT AFCError AFCConnectionClose(struct AFCConnection *connection);
    
    /* Registers for device notifications related to the restore process. unknown0
     * is zero when iTunes calls this. In iTunes,
     * the callbacks are located at:
     *      1: $3ac68e-$3ac6b1, calls $3ac542(unknown1, arg, 0)
     *      2: $3ac66a-$3ac68d, calls $3ac542(unknown1, 0, arg)
     *      3: $3ac762-$3ac785, calls $3ac6b2(unknown1, arg, 0)
     *      4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
     */
    __DLLIMPORT uint32_t AMRestoreRegisterForDeviceNotifications(AMRestoreDeviceNotificationCallback dfuConnectCallback,
                                                                 AMRestoreDeviceNotificationCallback recoveryConnectCallback,
                                                                 AMRestoreDeviceNotificationCallback dfuDisconectCallback,
                                                                 AMRestoreDeviceNotificationCallback recoveryDisconnectCallback,
                                                                 uint32_t unknown0,
                                                                 void *userInfo);
    
    /* Causes the restore functions to spit out (unhelpful) progress messages to
     * the file specified by the given path. iTunes always calls this right before
     * restoring with a path of
     * "$HOME/Library/Logs/iPhone Updater Logs/iPhoneUpdater X.log", where X is an
     * unused number.
     */
    __DLLIMPORT uint32_t AMRestoreEnableFileLogging(uint8_t *path);
    
    /* Initializes a new option dictionary to default values. Pass the constant
     * kCFAllocatorDefault as the allocator. The option dictionary looks as
     * follows:
     * {
     *      NORImageType => 'production',
     *      AutoBootDelay => 0,
     *      KernelCacheType => 'Release',
     *      UpdateBaseband => true,
     *      DFUFileType => 'RELEASE',
     *      SystemImageType => 'User',
     *      CreateFilesystemPartitions => true,
     *      FlashNOR => true,
     *      RestoreBootArgs => 'rd=md0 nand-enable-reformat=1 -progress'
     *      BootImageType => 'User'
     *  }
     *
     * Returns:
     *      the option dictionary   if successful
     *      NULL                    if out of memory
     */ 
    __DLLIMPORT CFMutableDictionaryRef AMRestoreCreateDefaultOptions(CFAllocatorRef allocator);
    
    /* ----------------------------------------------------------------------------
     *   Less-documented public routines
     * ------------------------------------------------------------------------- */
    
    __DLLIMPORT uint32_t AMRestorePerformRecoveryModeRestore(struct AMRecoveryDevice *rdev,
                                                             CFDictionaryRef options,
                                                             void *callback,
                                                             void *userInfo);
    __DLLIMPORT uint32_t AMRestorePerformRestoreModeRestore(struct AMRecoveryDevice *rdev,
                                                             CFDictionaryRef options,
                                                             void *callback,
                                                             void *userInfo);
    __DLLIMPORT struct AMRestoreDevice* AMRestoreModeDeviceCreate(uint32_t unknown0,
                                                                  uint32_t connectionID,
                                                                  uint32_t unknown1);
    __DLLIMPORT uint32_t AMRestoreCreatePathsForBundle(CFStringRef restoreBundleType,
                                                       CFStringRef kernelCacheType,
                                                       CFStringRef bootImageType,
                                                       uint32_t unknown0,
                                                       CFStringRef *firwareDirectory,
                                                       CFStringRef *kernelCacheRestorePath,
                                                       uint32_t unknown1,
                                                       CFStringRef *ramdiskPath);
    __DLLIMPORT uint32_t AMRestoreModeDeviceReboot(struct AMRestoreDevice *rdev);
    __DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct AMDevice *device);
    __DLLIMPORT mach_error_t AMDeviceDisconnect(struct AMDevice *device);


    /* to use this, start the service "com.apple.mobile.notification_proxy", handle will be the socket to use */
    typedef void (*AMDeviceNotifyCallback)(CFStringRef notification, USERDATA data);
    __DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket,
                                                 CFStringRef notification,
                                                 CFStringRef userinfo);
    __DLLIMPORT mach_error_t AMDObserveNotification(SOCKET socket,
                                                    CFStringRef notification);
    __DLLIMPORT mach_error_t AMDListenForNotifications(SOCKET socket,
                                                       AMDeviceNotifyCallback callback,
                                                       USERDATA userData);
    __DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
    
    __DLLIMPORT mach_error_t AMDeviceDeactivate(struct AMDevice *device);
    __DLLIMPORT mach_error_t AMDeviceActivate(struct AMDevice *device,
                                              CFDictionaryRef dict);
    __DLLIMPORT mach_error_t AMDeviceRemoveValue(struct AMDevice *device,
                                                 uint32_t unknown,
                                                 CFStringRef str);
    
    /* ----------------------------------------------------------------------------
     *   Semi-private routines
     * ------------------------------------------------------------------------- */
    
    /*  Pass in a USBMuxListener1 structure and a USBMuxListener2 structure
     *  pointer, which will be filled with the resulting USBMuxListener2.
     *
     *  Returns:
     *      MDERR_OK                if completed successfully
     *      MDERR_USBMUX_ARG_NULL   if one of the arguments was NULL
     *      MDERR_USBMUX_FAILED     if the listener was not created successfully
     */
    __DLLIMPORT USBMuxError USBMuxListenerCreate(struct USBMuxListener1 *source,
                                                    struct USBMuxListener2 **destination);
    
    /* ----------------------------------------------------------------------------
     *   Less-documented semi-private routines
     * ------------------------------------------------------------------------- */
    __DLLIMPORT USBMuxError USBMuxListenerHandleData(void *unknown);
    
    /* ----------------------------------------------------------------------------
     *   Private routines - no exports means no function declarations
     * ------------------------------------------------------------------------- */
    
    /* AMRestorePerformRestoreModeRestore() calls this function with a dictionary
     * in order to perform certain special restore operations
     * (RESTORED_OPERATION_*). It is thought that this function might enable
     * significant access to the phone. */
    
    /*
     typedef unsigned int (*t_performOperation)(struct AMRestoreDevice *device, CFDictionaryRef operation)__attribute__ ((regparm(2)));
     t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
     */ 
    
    /* ----------------------------------------------------------------------------
     *   Less-documented private routines
     * ------------------------------------------------------------------------- */
    
    
    /*
     typedef int32_t (*t_socketForPort)(struct AMRestoreDevice *device, unsigned int port)__attribute__ ((regparm(2)));
     t_socketForPort _socketForPort = (t_socketForPort)0x3c39f36c;
     
     typedef void (*t_restored_send_message)(int port, CFDictionaryRef msg);
     t_restored_send_message _restored_send_message = (t_restored_send_message)0x3c3a4e40;
     
     typedef CFDictionaryRef (*t_restored_receive_message)(int port);
     t_restored_receive_message _restored_receive_message = (t_restored_receive_message)0x3c3a4d40;
     
     typedef uint32_t (*t_sendControlPacket)(struct AMRecoveryDevice *device, uint32_t message1, uint32_t message2, uint32_t unknown0, uint32_t *unknown1, uint8_t *unknown2)__attribute__ ((regparm(3)));
     t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
     
     typedef uint32_t (*t_sendCommandToDevice)(struct AMRecoveryDevice *device, CFStringRef command)__attribute__ ((regparm(2)));
     t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
     
     typedef uint32_t (*t_AMRUSBInterfaceReadPipe)(uint32_t readwrite_pipe, uint32_t read_pipe, uint8_t *buffer, uint32_t *length);
     t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
     
     typedef uint32_t (*t_AMRUSBInterfaceWritePipe)(uint32_t readWritePipe, uint32_t writePipe, void *data, uint32_t length);
     t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
     */
    
    int32_t performOperation(AMRestoreDevice *device,
                             CFMutableDictionaryRef message);
    int32_t socketForPort(AMRestoreDevice *device,
                          uint32_t portnum);
    int32_t sendCommandToDevice(AMRestoreDevice *device,
                                CFStringRef command,
                                int block);
    int32_t sendFileToDevice(AMRestoreDevice *device,
                             CFStringRef fileName);

#if !defined(__GCC__)
#  pragma pack(pop)
#endif
#undef __PACK
#if defined(__cplusplus)
}
#endif

#endif /* MOBILEDEVICE_H */

AFC Connection

...

Locking the Device for Sync

When iTunes sends a new song to the device, the device shows a "Sync in progress" screen and when complete, the Music app on the device re-reads the iTunesDB file so it picks up the new song.

To get this behaviour, first start the notification service:

SOCKET socket;
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);

Now we post a notificaton message to signal that we are going to start a sync:

AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncWillStart"), NULL);

Next we open the itunes lock file:

AFCFileRef lockref;
AFCFileRefOpen(conn, "/com.apple.itunes.lock_sync", 2, &lockref);

Now post a notification to say we are going to lock this file, and try and lock it. If the AFCFileRefLock call fails, pause and repeat.

AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncLockRequest"), NULL);
mach_error_t error = AFCFileRefLock(conn, lockref);

When the file is successfully locked, post another notification, and stop the notification service.

AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncDidStart"), NULL);
AMDShutdownNotificationProxy(socket);

Now the sync can proceed, so copy your files across and make the changes to the iTunesDB.

To release the lock, start the notification system again, unlock and close the lock file, and send a sync finished notification message:

AFCFileRefUnlock(conn, lockref);
AFCFileRefClose(conn, lockref);
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);
AMDPostNotification(socket, &CFSTR("com.apple.itunes-mobdev.syncDidFinish"), NULL);
AMDShutdownNotificationProxy(socket);

To handle "Slide to Cancel" and terminate sync when user slides cancel switch, use AMDObserveNotification to subscribe notifications about "com.apple.itunes-client.syncCancelRequest". Then start listening for notifications (AMDListenForNotifications) until you get "AMDNotificationFaceplant". When notification got, you should unlock and close lock file handle (don’t sure if you need to post “syncDidFinish” to proxy, seems it doesn't matter) and terminate sync gracefully. The same notification is also got when you unplug your device, so you should always be ready for errors.

NOTE: You may find that starting the notification_proxy service once and once only at the start of your app and using the same socket in calls to AMDPostNotification works better. iTunes opens and closes the notification_proxy regularly, but it appears to be a bit flaky when you open/close it all the time.

Known Functions

These are functions that are known to exist, but their decleration is unknown:

  • AFCLockCreate
  • AFCLockFree
  • AFCLockLock
  • AFCLockTryLock
  • AFCLockUnlock
  • AFCStringBufferAlloc
  • AFCStringBufferAppend
  • AFCStringBufferFree
  • AFCStringCopy
  • MISProfileCopyPayload
  • MISProfileCopySignerSubjectSummary
  • MISProfileCreateDataRepresentation
  • MISProfileCreateWithData
  • MISProfileCreateWithFile
  • MISProfileGetValue
  • MISProfileIsMutable
  • MISProfileValidateSignature
  • MISProfileValidateSignatureWithAnchors
  • MISProfileWriteToFile
  • MISProvisioningProfileCheckValidity
  • MISProvisioningProfileGetCreationDate
  • MISProvisioningProfileGetDeveloperCertificates
  • MISProvisioningProfileGetExpirationDate
  • MISProvisioningProfileGetName
  • MISProvisioningProfileGetProvisionedDevices
  • MISProvisioningProfileGetUUID
  • MISProvisioningProfileGetVersion
  • MISProvisioningProfileIncludesDevice
  • MISProvisioningProfileProvisionsAllDevices
  • MISProvisioningProfileValidateSignature
  • AFCConnectionClose
  • AFCConnectionGetContext
  • AFCConnectionGetFSBlockSize
  • AFCConnectionGetIOTimeout
  • AFCConnectionGetSocketBlockSize
  • AFCConnectionOpen
  • AFCConnectionSetContext
  • AFCConnectionSetFSBlockSize
  • AFCConnectionSetFatalError
  • AFCConnectionSetIOTimeout
  • AFCConnectionSetSocketBlockSize
  • AFCDeviceInfoOpen
  • AFCDirectoryClose
  • AFCDirectoryCreate
  • AFCDirectoryOpen
  • AFCDirectoryRead
  • AFCDiscardBodyData
  • AFCDiscardData
  • AFCErrnoToAFCError
  • AFCFileInfoOpen
  • AFCFileRefClose
  • AFCFileRefLock
  • AFCFileRefOpen
  • AFCFileRefRead
  • AFCFileRefSeek
  • AFCFileRefSetFileSize
  • AFCFileRefTell
  • AFCFileRefUnlock
  • AFCFileRefWrite
  • AFCFlushData
  • AFCGetClientVersionString
  • AFCGetDeviceInfo
  • AFCGetFileInfo
  • AFCInitHeader
  • AFCKeyValueClose
  • AFCKeyValueRead
  • AFCParseDataPacketHeader
  • AFCParseStatusPacket
  • AFCReadData
  • AFCReadPacket
  • AFCReadPacketBody
  • AFCReadPacketHeader
  • AFCRemovePath
  • AFCRenamePath
  • AFCSendData
  • AFCSendDataPacket
  • AFCSendHeader
  • AFCSendPacket
  • AFCSendStatus
  • AFCValidateHeader
  • AMDFUModeDeviceGetLocationID
  • AMDFUModeDeviceGetProductID
  • AMDFUModeDeviceGetProductType
  • AMDFUModeDeviceGetProgress
  • AMDFUModeDeviceGetTypeID
  • AMDListenForNotifications
  • AMDObserveNotification
  • AMDPostNotification
  • AMDShutdownNotificationProxy
  • AMDeviceActivate
  • AMDeviceArchiveApplication
  • AMDeviceConnect
  • AMDeviceCopyDeviceIdentifier
  • AMDeviceCopyProvisioningProfiles
  • AMDeviceCopyValue
  • AMDeviceDeactivate
  • AMDeviceDisconnect
  • AMDeviceEnterRecovery
  • AMDeviceGetConnectionID
  • AMDeviceInstallApplication
  • AMDeviceInstallProvisioningProfile
  • AMDeviceIsPaired
  • AMDeviceIsValid
  • AMDeviceLookupApplicationArchives
  • AMDeviceLookupApplications
  • AMDeviceNotificationGetThreadHandle
  • AMDeviceNotificationSubscribe
  • AMDeviceNotificationUnsubscribe
  • AMDevicePair
  • AMDeviceRelease
  • AMDeviceRemoveApplicationArchive
  • AMDeviceRemoveProvisioningProfile
  • AMDeviceRemoveValue
  • AMDeviceRestoreApplication
  • AMDeviceRetain
  • AMDeviceSetValue
  • AMDeviceSoftwareUpdate
  • AMDeviceStartHouseArrestService
  • AMDeviceStartService
  • AMDeviceStartSession
  • AMDeviceStopSession
  • AMDeviceTransferApplication
  • AMDeviceUninstallApplication
  • AMDeviceValidatePairing
  • AMRecoveryModeDeviceCopyIMEI
  • AMRecoveryModeDeviceCopySerialNumber
  • AMRecoveryModeDeviceGetLocationID
  • AMRecoveryModeDeviceGetProductID
  • AMRecoveryModeDeviceGetProductType
  • AMRecoveryModeDeviceGetProgress
  • AMRecoveryModeDeviceGetSecurityEpoch
  • AMRecoveryModeDeviceGetTypeID
  • AMRecoveryModeDeviceReboot
  • AMRecoveryModeDeviceSetAutoBoot
  • AMRecoveryModeGetSoftwareBuildVersion
  • AMRestoreCreateBootArgsByAddingArg
  • AMRestoreCreateBootArgsByRemovingArg
  • AMRestoreCreateDefaultOptions
  • AMRestoreCreateDefaultOptionsForIdentification
  • AMRestoreCreatePathsForBundle
  • AMRestoreDisableFileLogging
  • AMRestoreEnableExtraDFUDevices
  • AMRestoreEnableFileLogging
  • AMRestoreGetSupportedPayloadVersion
  • AMRestoreModeDeviceCopyIMEI
  • AMRestoreModeDeviceCopyRestoreLog
  • AMRestoreModeDeviceCopySerialNumber
  • AMRestoreModeDeviceCreate
  • AMRestoreModeDeviceGetDeviceID
  • AMRestoreModeDeviceGetLocationID
  • AMRestoreModeDeviceGetProgress
  • AMRestoreModeDeviceGetTypeID
  • AMRestoreModeDeviceReboot
  • AMRestorePerformDFURestore
  • AMRestorePerformRecoveryModeRestore
  • AMRestorePerformRestoreModeRestore
  • AMRestoreRegisterForDeviceNotifications
  • AMRestoreSetLogLevel
  • AMSBackup
  • AMSBeginSync
  • AMSBeginSyncForDataClasses
  • AMSCancelBackupRestore
  • AMSCancelCrashReportCopy
  • AMSCancelSync
  • AMSCancelSyncDiagnostics
  • AMSCleanup
  • AMSConnectToCrashReportCopyTarget
  • AMSCopyAndSubmitCrashLogs
  • AMSCopyAndSubmitCrashLogsFromTarget
  • AMSCopyApplicationListFromBackup
  • AMSCopyCrashReportPath
  • AMSCopyCrashReportsFromTarget
  • AMSCopySourcesForRestoreCompatibleWith
  • AMSDisconnectFromCrashReportCopyTarget
  • AMSGetAOSUsername
  • AMSGetApplicationProviderInfo
  • AMSGetCalendarDayLimit
  • AMSGetClientIdentifierAndDisplayNameForTarget
  • AMSGetCollectionsForDataClassName
  • AMSGetConflictInformation
  • AMSGetConflictInformationForIdentifiers
  • AMSGetCrashReportCopyPreferencesForTarget
  • AMSGetDCAChangeInformation
  • AMSGetDataChangeAlertInfo
  • AMSGetDataClassInfoForTarget
  • AMSGetLastSyncDateForDataClass
  • AMSGetNewRecordCalendarName
  • AMSGetNewRecordGroupName
  • AMSGetNumberOfCrashReportsToCopy
  • AMSGetNumberOfCrashReportsToSubmit
  • AMSGetSourcesForRestore
  • AMSGetSupportedDataClassNames
  • AMSInitialize
  • AMSRefreshCollectionsForDataClassName
  • AMSRegisterCallbacks
  • AMSRegisterClientWithTargetIdentifierAndDisplayName
  • AMSResetSyncData
  • AMSRestore
  • AMSRestoreWithApplications
  • AMSRunSyncDiagnostics
  • AMSSetCalendarDayLimit
  • AMSSetConflictWinners
  • AMSSetCrashReportCopyPreferencesForTarget
  • AMSSetDataChangeAlertInfo
  • AMSSetDataClassInfoForTarget
  • AMSSetDesignatedProviderForDataClassName
  • AMSSetFilteredCollectionNamesForDataClassName
  • AMSSetNewRecordCalendarName
  • AMSSetNewRecordGroupName
  • AMSSubmitCrashReportsFromTarget
  • AMSSyncConflictsSelections
  • AMSUnregisterTarget
  • ASRServerHandleConnection
  • GoogleSyncConduitCopyUsername
  • GoogleSyncConduitRegisterClient
  • GoogleSyncConduitSetUsernameAndPassword
  • GoogleSyncConduitUnregisterClient
  • GoogleSyncConduitValidateUser
  • USBMuxConnectByPort
  • USBMuxListenForDevices
  • USBMuxListenerClose
  • USBMuxListenerCreate
  • USBMuxListenerGetEvent
  • USBMuxListenerGetFD
  • USBMuxListenerHandleData
  • USBMuxListenerSetDebug
  • YahooConduitCopyYahooID
  • YahooConduitIsTokenValid
  • YahooConduitLastSyncError
  • YahooConduitRegister
  • YahooConduitUnregister
  • kAMDMobileDeviceVersionNumber
  • kLDErrorInvalidResponse
  • lockdown_activate
  • lockdown_connection_create
  • lockdown_connection_destroy
  • lockdown_get_value
  • lockdown_goodbye
  • lockdown_pair
  • lockdown_remove_value
  • lockdown_service_start
  • lockdown_session_start
  • lockdown_session_stop
  • lockdown_set_value

Private Functions

Obtaining address

In order to obtain the address of a usable private function in MobileDevice, you will have to be able to understand x86-64 assembly to reverse engineer it. A private function will not have its name exported in the mach-o symbol table, so in a debugger, like GDB, it will show up as part of another function. However, you will know that it is a separate function as a new stack frame is set up.

Private Function Address List

OSX 10.6 - iTunes 9.0.2(25)
unsigned int sendCommandToiBoot(struct am_recovery_device *rdev, CFStringRef command, int u);

Address is obtainable by adding 868(0x364) to the address of AMRecoveryDeviceGetProductType(), a public symbol that you can obtain via nlist() or dlsym(). Address: 0x1000245ea

Parameters

  1. rdev - the device you wish to send the command to.
  2. a CFStringRef of the command to send.
  3. an integer, whose use is currently unknown, but should be set to 0 to work.
uint32_t sendFileToDevice(struct AMRecoveryDevice *device, CFStringRef fileName);

Address is obtainable by adding 1763(0x6e3) to the address of AMRecoveryDeviceGetProductType(), a public symbol that you can obtain via nlist() or dlsym(). Address: 0x100024969

Parameters

  1. rdev - the device you wish to send the file to.
  2. a CFStringRef of the path to the file to send.
OSX 10.6 - iTunes 9.0.3(15)
unsigned int sendCommandToIBoot(struct AMRecoveryDevice *device, CFStringRef command, int unknown);

Addresss: AMRecoveryDeviceGetProductType() + 0x37f(895); full offset: 0x2a0ed

unsigned int sendFileToDevice(struct AMRecoveryDevice *device, CFStringRef filename);

Address: AMRecoveryDeviceGetProductType()+0x6f3(1790); full offset: 0x2a46c

As of now, Apple has decided to make these functions public with the following names:

  • _AMRecoveryModeDeviceSendFileToDevice
  • _AMRecoveryModeDeviceSendCommandToDevice
  • _AMRecoveryModeDeviceSendBlindCommandToDevice

The last of those returns no response from the device. One can only assume that the parameters to these functions are the same or similar to the private ones. They're not the exact same function though, as it appears that these functions call the previously private ones.

Known Error Codes

  • kAMDProhibitedBySupervision = -402653053
  • kAMDAlreadyArchivedError = -402653094
  • kAMDiTunesMetadataCaptureFailedError = -402653095
  • kAMDiTunesArtworkCaptureFailedError = -402653096
  • kAMDSymlinkFailedError = -402653097
  • kAMDStageCreationFailedError = -402653098
  • kAMDSeatbeltProfileRemovalFailedError = -402653099
  • kAMDRestoreContainerFailedError = -402653100
  • kAMDPathConversionFailedError = -402653101
  • kAMDPackageMoveFailedError = -402653102
  • kAMDPackageInspectionFailedError = -402653103
  • kAMDPackageExtractionFailedError = -402653104
  • kAMDNotificationFailedError = -402653105
  • kAMDMissingContainerError = -402653106
  • kAMDMissingBundlePathError = -402653107
  • kAMDMissingBundleIdentifierError = -402653108
  • kAMDMissingBundleExecutableError = -402653109
  • kAMDMapGenerationFailedError = -402653110
  • kAMDManifestCaptureFailedError = -402653111
  • kAMDInstallMapUpdateFailedError = -402653112
  • kAMDExistenceCheckFailedError = -402653113
  • kAMDExecutableTwiddleFailedError = -402653114
  • kAMDErrorError = -402653115
  • kAMDEmbeddedProfileInstallFailedError = -402653116
  • kAMDContainerRemovalFailedError = -402653117
  • kAMDContainerP0wnFailedError = -402653118
  • kAMDContainerCreationFailedError = -402653119
  • kAMDCommCenterNotificationFailedError = -402653120
  • kAMDCarrierBundleMissingSupportedSIMsError = -402653121
  • kAMDCarrierBundleDirectoryCreationFailedError = -402653122
  • kAMDCarrierBundleCopyFailedError = -402653123
  • kAMDBundleVerificationFailedError = -402653124
  • kAMDArchiveDestructionFailedError = -402653125
  • kAMDApplicationVerificationFailedError = -402653126
  • kAMDApplicationSandboxFailedError = -402653127
  • kAMDApplicationSINFCaptureFailedError = -402653128
  • kAMDApplicationMoveFailedError = -402653129
  • kAMDApplicationAlreadyInstalledError = -402653130
  • kAMDMuxError = -402653131
  • kAMDMissingDigestError = -402653132
  • kAMDInvalidDiskImageError = -402653133
  • kAMDStartServiceError = -402653134
  • kAMDDigestFailedError = -402653135
  • kAMDMissingImageTypeError = -402653136
  • kAMDMissingOptionsError = -402653137
  • kAMDReceiveMessageError = -402653138
  • kAMDSendMessageError = -402653139
  • kAMDProvisioningProfileNotValid = -402653140
  • kAMDSUFirmwareError = -402653141
  • kAMDSUPatchError = -402653142
  • kAMDSUVerificationError = -402653143
  • kAMDWrongDroidError = -402653144
  • kAMDMissingActivationRecordError = -402653145
  • kAMDInvalidActivationRecordError = -402653146
  • kAMDMissingPairRecordError = -402653147
  • kAMDCheckinTimeoutError = -402653148
  • kAMDInvalidCheckinError = -402653149
  • kAMDInvalidServiceError = -402653150
  • kAMDMissingServiceError = -402653151
  • kAMDInvalidSessionIDError = -402653152
  • kAMDMissingSessionIDError = -402653153
  • kAMDSessionInactiveError = -402653154
  • kAMDSessionActiveError = -402653155
  • kAMDInvalidHostIDError = -402653156
  • kAMDMissingHostIDError = -402653157
  • kAMDPasswordProtectedError = -402653158
  • kAMDImmutableValueError = -402653159
  • kAMDRemoveProhibitedError = -402653160
  • kAMDSetProhibitedError = -402653161
  • kAMDGetProhibitedError = -402653162
  • kAMDMissingValueError = -402653163
  • kAMDMissingKeyError = -402653164
  • kAMDInvalidResponseError = -402653165
  • kAMDCryptoError = -402653166
  • kAMDBusyError = -402653167
  • kAMDFileExistsError = -402653168
  • kAMDUnsupportedError = -402653169
  • kAMDEOFError = -402653170
  • kAMDOverrunError = -402653171
  • kAMDTimeOutError = -402653172
  • kAMDNotConnectedError = -402653173
  • kAMDPermissionError = -402653174
  • kAMDIsDirectoryError = -402653175
  • kAMDNotFoundError = -402653176
  • kAMDInvalidArgumentError = -402653177
  • kAMDUnknownPacketError = -402653178
  • kAMDWriteError = -402653179
  • kAMDReadError = -402653180
  • kAMDNoResourcesError = -402653181
  • kAMDBadHeaderError = -402653182
  • kAMDUndefinedError = -402653183
  • kAMDSuccess = 0

Libraries Implementations