Difference between revisions of "MobileDevice Library"

From The iPhone Wiki
Jump to: navigation, search
(lib gone)
(when you remove it, at least only remove the link + converted it to wiki markup (big changes as in almost every line))
Line 1: Line 1:
 
MobileDevice Library is used by [[iTunes]] to transfer data between iPhone and computer over the USB connection.
 
MobileDevice Library is used by [[iTunes]] to transfer data between iPhone and computer over the USB connection.
   
===PC Windows : iTunesMobileDevice.dll===
+
=== PC Windows : iTunesMobileDevice.dll ===
 
The DLL is written using Microsoft Visual C++ 8.0 DLL Method [2].
 
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 : Location is stored in '''iTunesMobileDeviceDLL''' registry value under '''HKLM\SOFTWARE\Apple Inc.\Apple Mobile Device Support\Shared''' key. Usually - C:\Program Files\Common Files\Apple\Mobile Device Support\bin\iTunesMobileDevice.dll.
 
  +
* Location: /System/Library/PrivateFrameworks/MobileDevice.framework
 
  +
* Export command: <code>nm /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice</code>
* Supporting CoreFoundation.dll (used for CFStringRef, CFPropertyListRef management) is located in the same dir (when using iTunes prior 9.0).
 
 
* For iTunes 9.0 location of CoreFoundation.dll is stored in '''InstallDir''' registry value under '''HKLM\SOFTWARE\Apple Inc.\Apple Application Support''' key, usually C:\Program Files\Common Files\Apple\Apple Application Support\. CoreFoundation.dll from Mobile Device Support\bin should not be used.
 
 
===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)===
 
   
  +
=== MobileDevice Header (mobiledevice.h) ===
 
Reverse engineered C header for MobileDevice Library.
 
Reverse engineered C header for MobileDevice Library.
   
  +
/* ----------------------------------------------------------------------------
<pre>
 
  +
* MobileDevice.h - interface to MobileDevice.framework
/* ----------------------------------------------------------------------------
 
  +
* ------------------------------------------------------------------------- */
* MobileDevice.h - interface to MobileDevice.framework
 
  +
#pragma once
* ------------------------------------------------------------------------- */
 
  +
#pragma once
 
  +
#ifndef MOBILEDEVICE_H
 
#ifndef MOBILEDEVICE_H
+
#define MOBILEDEVICE_H
  +
#define MOBILEDEVICE_H
 
  +
#ifdef __cplusplus
 
  +
extern "C" {
#ifdef __cplusplus
 
  +
#endif
extern "C" {
 
  +
#endif
 
  +
#ifndef __GCC__
 
  +
#pragma pack
#ifndef __GCC__
 
  +
#define __PACK
#pragma pack
 
  +
#else
#define __PACK
 
  +
#define __PACK __attribute__((__packed__))
#else
 
  +
#endif
#define __PACK __attribute__((__packed__))
 
  +
#endif
 
  +
#if defined(WIN32)
 
  +
#define __DLLIMPORT [DllImport("iTunesMobileDevice.dll")]
#if defined(WIN32)
 
  +
using namespace System::Runtime::InteropServices;
#define __DLLIMPORT [DllImport("iTunesMobileDevice.dll")]
 
  +
#include <CoreFoundation.h>
using namespace System::Runtime::InteropServices;
 
  +
typedef unsigned int mach_error_t;
#include <CoreFoundation.h>
 
  +
#elif defined(__APPLE__)
typedef unsigned int mach_error_t;
 
  +
#define __DLLIMPORT
#elif defined(__APPLE__)
 
  +
#include <CoreFoundation/CoreFoundation.h>
#define __DLLIMPORT
 
  +
#endif
#include <mach/error.h>
 
  +
#endif
 
  +
/* Error codes */
 
  +
#define MDERR_APPLE_MOBILE (err_system(0x3a))
/* Error codes */
 
#define MDERR_APPLE_MOBILE (err_system(0x3a))
+
#define MDERR_IPHONE (err_sub(0))
  +
#define MDERR_IPHONE (err_sub(0))
 
  +
/* Apple Mobile (AM*) errors */
 
  +
#define MDERR_OK ERR_SUCCESS
/* Apple Mobile (AM*) errors */
 
#define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01)
+
#define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03)
#define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03)
+
#define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04)
#define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04)
+
#define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b)
#define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b)
+
#define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25)
  +
#define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25)
 
  +
/* Apple File Connection (AFC*) errors */
 
  +
#define MDERR_AFC_OUT_OF_MEMORY 0x03
/* Apple File Connection (AFC*) errors */
 
  +
#define MDERR_AFC_OUT_OF_MEMORY 0x03
 
  +
/* USBMux errors */
 
  +
#define MDERR_USBMUX_ARG_NULL 0x16
/* USBMux errors */
 
  +
#define MDERR_USBMUX_FAILED 0xffffffff
 
  +
/* Messages passed to device notification callbacks: passed as part of
 
  +
* am_device_notification_callback_info. */
/* Messages passed to device notification callbacks: passed as part of
 
  +
#define ADNCI_MSG_CONNECTED 1
* am_device_notification_callback_info. */
 
  +
#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")
/* Services, found in /System/Library/Lockdown/Services.plist */
 
#define AMSVC_AFC CFSTR("com.apple.afc")
+
#define AMSVC_BACKUP CFSTR("com.apple.mobilebackup")
#define AMSVC_BACKUP CFSTR("com.apple.mobilebackup")
+
#define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy")
#define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy")
+
#define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount")
#define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount")
+
#define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy")
#define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy")
+
#define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr")
#define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr")
+
#define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update")
#define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update")
+
#define AMSVC_SYNC CFSTR("com.apple.mobilesync")
#define AMSVC_SYNC CFSTR("com.apple.mobilesync")
+
#define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr")
#define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr")
+
#define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay")
#define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay")
+
#define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler")
  +
#define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler")
 
  +
typedef unsigned int afc_error_t;
 
  +
typedef unsigned int usbmux_error_t;
 
  +
struct am_recovery_device;
 
  +
struct am_recovery_device;
 
  +
struct am_device_notification_callback_info {
 
  +
struct am_device *dev; /* 0 device */
struct am_device_notification_callback_info {
 
#include <CoreFoundation/CoreFoundation.h>
+
#include <mach/error.h>
#define MDERR_OK ERR_SUCCESS
+
#define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01)
#define MDERR_USBMUX_ARG_NULL 0x16
+
#define MDERR_USBMUX_FAILED 0xffffffff
#define ADNCI_MSG_CONNECTED 1
+
#define ADNCI_MSG_DISCONNECTED 2
#define ADNCI_MSG_DISCONNECTED 2
+
#define ADNCI_MSG_UNSUBSCRIBED 3
#define AMD_IPHONE_PRODUCT_ID 0x1290
+
//#define AMD_IPHONE_SERIAL ""
typedef unsigned int afc_error_t;
+
typedef unsigned int usbmux_error_t;
struct am_device *dev; /* 0 device */
+
unsigned int msg; /* 4 one of ADNCI_MSG_* */
unsigned int msg; /* 4 one of ADNCI_MSG_* */
 
 
struct am_device_notification* subscription;
 
struct am_device_notification* subscription;
} __PACK;
+
} __PACK;
  +
 
* TODO: change to correct type. */
+
* TODO: change to correct type. */
typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
+
typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
  +
 
unsigned char unknown0[8]; /* 0 */
+
unsigned char unknown0[8]; /* 0 */
am_restore_device_notification_callback callback; /* 8 */
+
am_restore_device_notification_callback callback; /* 8 */
void *user_info; /* 12 */
+
void *user_info; /* 12 */
unsigned char unknown1[12]; /* 16 */
+
unsigned char unknown1[12]; /* 16 */
unsigned int readwrite_pipe; /* 28 */
+
unsigned int readwrite_pipe; /* 28 */
unsigned char read_pipe; /* 32 */
+
unsigned char read_pipe; /* 32 */
unsigned char write_ctrl_pipe; /* 33 */
+
unsigned char write_ctrl_pipe; /* 33 */
unsigned char read_unknown_pipe; /* 34 */
+
unsigned char read_unknown_pipe; /* 34 */
unsigned char write_file_pipe; /* 35 */
+
unsigned char write_file_pipe; /* 35 */
unsigned char write_input_pipe; /* 36 */
+
unsigned char write_input_pipe; /* 36 */
} __PACK;
+
} __PACK;
  +
 
  +
 
  +
 
  +
 
* TODO: change to correct type. */
+
* TODO: change to correct type. */
typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
+
typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
  +
 
/* The type of the device restore notification callback functions.
+
/* The type of the device restore notification callback functions.
/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
+
/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
struct am_recovery_device {
+
struct am_recovery_device {
/* A CoreFoundation object of class AMRestoreModeDevice. */
+
/* A CoreFoundation object of class AMRestoreModeDevice. */
struct am_restore_device {
+
struct am_restore_device {
unsigned char unknown[32];
+
unsigned char unknown[32];
int port;
+
int port;
} __PACK;
+
} __PACK;
/* The type of the device notification callback function. */
+
/* The type of the device notification callback function. */
typedef void(*am_device_notification_callback)(struct am_device_notification_callback_info *, int cookie);
+
typedef void(*am_device_notification_callback)(struct am_device_notification_callback_info *, int cookie);
/* The type of the _AMDDeviceAttached function.
+
/* The type of the _AMDDeviceAttached function.
* TODO: change to correct type. */
+
* TODO: change to correct type. */
typedef void *amd_device_attached_callback;
+
typedef void *amd_device_attached_callback;
/* The type of the device restore notification callback functions.
+
/* The type of the device restore notification callback functions.
/* Structure that contains internal data used by AMDevice... functions. Never try
+
/* Structure that contains internal data used by AMDevice... functions. Never try
 
* to access its members directly! Use AMDeviceCopyDeviceIdentifier,
 
* to access its members directly! Use AMDeviceCopyDeviceIdentifier,
 
* AMDeviceGetConnectionID, AMDeviceRetain, AMDeviceRelease instead. */
 
* AMDeviceGetConnectionID, AMDeviceRetain, AMDeviceRelease instead. */
struct am_device {
+
struct am_device {
unsigned char unknown0[16]; /* 0 - zero */
+
unsigned char unknown0[16]; /* 0 - zero */
unsigned int device_id; /* 16 */
+
unsigned int device_id; /* 16 */
unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */
+
unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */
char *serial; /* 24 - set to UDID, Unique Device Identifier */
+
char *serial; /* 24 - set to UDID, Unique Device Identifier */
unsigned int unknown1; /* 28 */
+
unsigned int unknown1; /* 28 */
unsigned int unknown2; /* 32 - reference counter, increased by AMDeviceRetain, decreased by AMDeviceRelease*/
+
unsigned int unknown2; /* 32 - reference counter, increased by AMDeviceRetain, decreased by AMDeviceRelease*/
unsigned int lockdown_conn; /* 36 */
+
unsigned int lockdown_conn; /* 36 */
unsigned char unknown3[8]; /* 40 */
+
unsigned char unknown3[8]; /* 40 */
#if (__ITUNES_VER > 740)
+
#if (__ITUNES_VER > 740)
unsigned int unknown4; /* 48 - used to store CriticalSection Handle*/
+
unsigned int unknown4; /* 48 - used to store CriticalSection Handle*/
#endif
+
#endif
#if (__ITUNES_VER >= 800)
+
#if (__ITUNES_VER >= 800)
unsigned char unknown5[24]; /* 52 */
+
unsigned char unknown5[24]; /* 52 */
#endif
+
#endif
} __PACK;
+
} __PACK;
  +
 
  +
 
unsigned int sock_block_size; /* 28: always 0x3c */
+
unsigned int sock_block_size; /* 28: always 0x3c */
unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */
+
unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */
void *afc_lock; /* 36 */
+
void *afc_lock; /* 36 */
unsigned int context; /* 40 */
+
unsigned int context; /* 40 */
} __PACK;
+
} __PACK;
  +
 
  +
 
  +
 
  +
 
} __PACK;
+
} __PACK;
  +
 
unsigned char unknown[0]; /* size unknown */
+
unsigned char unknown[0]; /* size unknown */
} __PACK;
+
} __PACK;
  +
 
  +
 
unsigned int unknown0; /* 0 1 */
+
unsigned int unknown0; /* 0 1 */
unsigned char *unknown1; /* 4 ptr, maybe device? */
+
unsigned char *unknown1; /* 4 ptr, maybe device? */
amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */
+
amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */
unsigned int unknown3; /* 12 */
+
unsigned int unknown3; /* 12 */
unsigned int unknown4; /* 16 */
+
unsigned int unknown4; /* 16 */
unsigned int unknown5; /* 20 */
+
unsigned int unknown5; /* 20 */
} __PACK;
+
} __PACK;
  +
 
  +
 
unsigned char payload[0]; /* 4 */
+
unsigned char payload[0]; /* 4 */
} __PACK;
+
} __PACK;
  +
 
* ------------------------------------------------------------------------- */
+
* ------------------------------------------------------------------------- */
  +
 
* copied into the notification struct, as well as being registered with the
+
* copied into the notification struct, as well as being registered with the
* current run loop. Cookie gets copied into cookie in the same.
+
* current run loop. Cookie gets copied into cookie in the same.
* (Cookie is a user info parameter that gets passed as an arg to
+
* (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.
+
* the callback) unused0 and unused1 are both 0 when iTunes calls this.
*
+
*
* Never try to acces directly or copy contents of dev and subscription fields
+
* Never try to acces directly or copy contents of dev and subscription fields
* in am_device_notification_callback_info. Treat them as abstract handles.
+
* in am_device_notification_callback_info. Treat them as abstract handles.
* When done with connection use AMDeviceRelease to free resources allocated for am_device.
+
* When done with connection use AMDeviceRelease to free resources allocated for am_device.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
* MDERR_SYSCALL if CFRunLoopAddSource() failed
+
* MDERR_SYSCALL if CFRunLoopAddSource() failed
* MDERR_OUT_OF_MEMORY if we ran out of memory
+
* MDERR_OUT_OF_MEMORY if we ran out of memory
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback callback,
+
__DLLIMPORT mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback callback,
unsigned int unused0, unsigned int unused1,
+
unsigned int unused0, unsigned int unused1,
unsigned int cookie,
+
unsigned int cookie,
struct am_device_notification **subscription);
+
struct am_device_notification **subscription);
  +
 
  +
 
struct am_device_notification {
+
struct am_device_notification {
unsigned int unknown0; /* 0 */
+
unsigned int unknown0; /* 0 */
unsigned int unknown1; /* 4 */
+
unsigned int unknown1; /* 4 */
unsigned int unknown2; /* 8 */
+
unsigned int unknown2; /* 8 */
am_device_notification_callback callback; /* 12 */
+
am_device_notification_callback callback; /* 12 */
unsigned int cookie; /* 16 */
+
unsigned int cookie; /* 16 */
} __PACK;
+
} __PACK;
struct afc_connection {
+
struct afc_connection {
unsigned int handle; /* 0 */
+
unsigned int handle; /* 0 */
unsigned int unknown0; /* 4 */
+
unsigned int unknown0; /* 4 */
unsigned char unknown1; /* 8 */
+
unsigned char unknown1; /* 8 */
unsigned char padding[3]; /* 9 */
+
unsigned char padding[3]; /* 9 */
unsigned int unknown2; /* 12 */
+
unsigned int unknown2; /* 12 */
unsigned int unknown3; /* 16 */
+
unsigned int unknown3; /* 16 */
unsigned int unknown4; /* 20 */
+
unsigned int unknown4; /* 20 */
unsigned int fs_block_size; /* 24 */
+
unsigned int fs_block_size; /* 24 */
struct afc_device_info {
+
struct afc_device_info {
unsigned char unknown[12]; /* 0 */
+
unsigned char unknown[12]; /* 0 */
} __PACK;
+
} __PACK;
struct afc_directory {
+
struct afc_directory {
unsigned char unknown[0]; /* size unknown */
+
unsigned char unknown[0]; /* size unknown */
struct afc_dictionary {
+
struct afc_dictionary {
typedef unsigned long long afc_file_ref;
+
typedef unsigned long long afc_file_ref;
struct usbmux_listener_1 { /* offset value in iTunes */
+
struct usbmux_listener_1 { /* offset value in iTunes */
struct usbmux_listener_2 {
+
struct usbmux_listener_2 {
unsigned char unknown0[4144];
+
unsigned char unknown0[4144];
} __PACK;
+
} __PACK;
struct am_bootloader_control_packet {
+
struct am_bootloader_control_packet {
unsigned char opcode; /* 0 */
+
unsigned char opcode; /* 0 */
unsigned char length; /* 1 */
+
unsigned char length; /* 1 */
unsigned char magic[2]; /* 2: 0x34, 0x12 */
+
unsigned char magic[2]; /* 2: 0x34, 0x12 */
/* ----------------------------------------------------------------------------
+
/* ----------------------------------------------------------------------------
* Public routines
+
* Public routines
/* Registers a notification with the current run loop. The callback gets
+
/* Registers a notification with the current run loop. The callback gets
 
/* 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(am_device_notification* subscription);
+
__DLLIMPORT mach_error_t AMDeviceNotificationUnsubscribe(am_device_notification* subscription);
  +
 
*/
+
*/
__DLLIMPORT unsigned int AMDeviceGetConnectionID(struct am_device *device);
+
__DLLIMPORT unsigned int AMDeviceGetConnectionID(struct am_device *device);
  +
 
__DLLIMPORT CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device);
+
__DLLIMPORT CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device);
  +
 
* notification callback will give to you.
+
* notification callback will give to you.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successfully connected
+
* MDERR_OK if successfully connected
* MDERR_SYSCALL if setsockopt() failed
+
* MDERR_SYSCALL if setsockopt() failed
* MDERR_QUERY_FAILED if the daemon query failed
+
* MDERR_QUERY_FAILED if the daemon query failed
* MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff
+
* MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceConnect(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDeviceConnect(struct am_device *device);
  +
 
__DLLIMPORT mach_error_t AMDevicePair(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDevicePair(struct am_device *device);
  +
 
* paired. It creates a pairing file and establishes a Lockdown connection.
+
* paired. It creates a pairing file and establishes a Lockdown connection.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the supplied device is null
+
* MDERR_INVALID_ARGUMENT if the supplied device is null
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
+
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceValidatePairing(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDeviceValidatePairing(struct am_device *device);
  +
 
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceStartSession(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDeviceStartSession(struct am_device *device);
  +
 
  +
 
/* Returns device_id field of am_device structure
+
/* Returns device_id field of am_device structure
/* Returns serial field of am_device structure
+
/* Returns serial field of am_device structure
*/
+
*/
/* Connects to the iPhone. Pass in the am_device structure that the
+
/* Connects to the iPhone. Pass in the am_device structure that the
/* Calls PairingRecordPath() on the given device, than tests whether the path
+
/* Calls PairingRecordPath() on the given device, than tests whether the path
* which that function returns exists. During the initial connect, the path
+
* which that function returns exists. During the initial connect, the path
* returned by that function is '/', and so this returns 1.
+
* returned by that function is '/', and so this returns 1.
*
+
*
* Returns:
+
* Returns:
* 0 if the path did not exist
+
* 0 if the path did not exist
* 1 if it did
+
* 1 if it did
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceIsPaired(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDeviceIsPaired(struct am_device *device);
/* iTunes calls this function immediately after testing whether the device is
+
/* iTunes calls this function immediately after testing whether the device is
/* Creates a Lockdown session and adjusts the device structure appropriately
+
/* Creates a Lockdown session and adjusts the device structure appropriately
* to indicate that the session has been started. iTunes calls this function
+
* to indicate that the session has been started. iTunes calls this function
* after validating pairing.
+
* after validating pairing.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
+
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
+
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
/* 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.
 
*
 
*
 
* Possible values for cfstring:
 
* Possible values for cfstring:
* ActivationState
+
* ActivationState
* ActivationStateAcknowledged
+
* ActivationStateAcknowledged
* BasebandBootloaderVersion
+
* BasebandBootloaderVersion
* BasebandVersion
+
* BasebandVersion
* BluetoothAddress
+
* BluetoothAddress
* BuildVersion
+
* BuildVersion
* DeviceCertificate
+
* DeviceCertificate
* DeviceClass
+
* DeviceClass
* DeviceName
+
* DeviceName
* DevicePublicKey
+
* DevicePublicKey
* FirmwareVersion
+
* FirmwareVersion
* HostAttached
+
* HostAttached
* IntegratedCircuitCardIdentity
+
* IntegratedCircuitCardIdentity
* InternationalMobileEquipmentIdentity
+
* InternationalMobileEquipmentIdentity
* InternationalMobileSubscriberIdentity
+
* InternationalMobileSubscriberIdentity
* ModelNumber
+
* ModelNumber
* PhoneNumber
+
* PhoneNumber
* ProductType
+
* ProductType
* ProductVersion
+
* ProductVersion
* ProtocolVersion
+
* ProtocolVersion
* RegionInfo
+
* RegionInfo
* SBLockdownEverRegisteredKey
+
* SBLockdownEverRegisteredKey
* SIMStatus
+
* SIMStatus
* SerialNumber
+
* SerialNumber
* SomebodySetTimeZone
+
* SomebodySetTimeZone
* TimeIntervalSince1970
+
* TimeIntervalSince1970
* TimeZone
+
* TimeZone
* TimeZoneOffsetFromUTC
+
* TimeZoneOffsetFromUTC
* TrustedHostAttached
+
* TrustedHostAttached
* UniqueDeviceID
+
* UniqueDeviceID
* Uses24HourClock
+
* Uses24HourClock
* WiFiAddress
+
* WiFiAddress
* iTunesHasConnected
+
* iTunesHasConnected
 
*
 
*
 
* Possible values for domain:
 
* Possible values for domain:
 
* com.apple.mobile.battery
 
* com.apple.mobile.battery
*/
+
*/
__DLLIMPORT CFStringRef AMDeviceCopyValue(struct am_device *device, CFStringRef domain, CFStringRef cfstring);
+
__DLLIMPORT CFStringRef AMDeviceCopyValue(struct am_device *device, CFStringRef domain, CFStringRef cfstring);
  +
 
* the service. iTunes calls this function after starting a session. It starts
+
* 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_*
+
* the service and the SSL connection. service_name should be one of the AMSVC_*
* constants.
+
* constants.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
* MDERR_SYSCALL if the setsockopt() call failed
+
* MDERR_SYSCALL if the setsockopt() call failed
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
+
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef
+
__DLLIMPORT mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef
service_name, int *socket_fd);
+
service_name, int *socket_fd);
  +
 
  +
 
  +
 
/* Increments reference counter
+
/* Increments reference counter
*/
+
*/
__DLLIMPORT void AMDeviceRetain(struct am_device *device);
+
__DLLIMPORT void AMDeviceRetain(struct am_device *device);
  +
 
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
* MDERR_AFC_OUT_OF_MEMORY if malloc() failed
+
* MDERR_AFC_OUT_OF_MEMORY if malloc() failed
*/
+
*/
__DLLIMPORT afc_error_t AFCConnectionOpen(int socket_fd, unsigned int io_timeout,
+
__DLLIMPORT afc_error_t AFCConnectionOpen(int socket_fd, unsigned int io_timeout,
struct afc_connection **conn);
+
struct afc_connection **conn);
  +
 
  +
 
/* Starts a service and returns a socket file descriptor that can be used in order to further
+
/* 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
+
* access the service. You should stop the session and disconnect before using
/* Stops a session. You should do this before accessing services.
+
/* Stops a session. You should do this before accessing services.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
+
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
+
*/
__DLLIMPORT mach_error_t AMDeviceStopSession(struct am_device *device);
+
__DLLIMPORT mach_error_t AMDeviceStopSession(struct am_device *device);
/* Decrements reference counter and, if nothing left, releases resources hold
+
/* Decrements reference counter and, if nothing left, releases resources hold
* by connection, invalidates pointer to device
+
* by connection, invalidates pointer to device
*/
+
*/
__DLLIMPORT void AMDeviceRelease(struct am_device *device);
+
__DLLIMPORT void AMDeviceRelease(struct am_device *device);
/* Opens an Apple File Connection. You must start the appropriate service
+
/* Opens an Apple File Connection. You must start the appropriate service
* first with AMDeviceStartService(). In iTunes, io_timeout is 0.
+
* first with AMDeviceStartService(). In iTunes, io_timeout is 0.
*
+
*
 
/* Copy an enviromental variable value from iBoot
 
/* Copy an enviromental variable value from iBoot
*/
+
*/
 
__DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct am_recovery_device *rdev, CFStringRef var);
 
__DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct am_recovery_device *rdev, CFStringRef var);
  +
 
/* Pass in a pointer to an afc_dictionary structure. It will be filled. You can
+
/* 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:
+
* iterate it using AFCKeyValueRead. When done use AFCKeyValueClose. Possible keys:
* FSFreeBytes - free bytes on system device for afc2, user device for afc
+
* FSFreeBytes - free bytes on system device for afc2, user device for afc
* FSBlockSize - filesystem block size
+
* FSBlockSize - filesystem block size
* FSTotalBytes - size of device
+
* FSTotalBytes - size of device
* Model - iPhone1,1 etc.
+
* Model - iPhone1,1 etc.
  +
 
  +
 
void AFCPlatformInitialize();
+
void AFCPlatformInitialize();
#endif
+
#endif
  +
 
* root, which is /var/root/Media. Pathnames are specified with '/' delimiters
+
* 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.
+
* as in Unix style. Use UTF-8 to specify non-ASCII symbols in path.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful
+
* MDERR_OK if successful
*/
+
*/
__DLLIMPORT afc_error_t AFCDirectoryOpen(struct afc_connection *conn, char *path, struct
+
__DLLIMPORT afc_error_t AFCDirectoryOpen(struct afc_connection *conn, char *path, struct
afc_directory **dir);
+
afc_directory **dir);
  +
 
*/
+
*/
__DLLIMPORT afc_error_t AFCDirectoryRead(struct afc_connection *conn, struct afc_directory *dir,
+
__DLLIMPORT afc_error_t AFCDirectoryRead(struct afc_connection *conn, struct afc_directory *dir,
char **dirent);
+
char **dirent);
__DLLIMPORT afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
+
__DLLIMPORT afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
__DLLIMPORT afc_error_t AFCDirectoryCreate(afc_connection *conn, char *dirname);
+
__DLLIMPORT afc_error_t AFCDirectoryCreate(afc_connection *conn, char *dirname);
__DLLIMPORT afc_error_t AFCRemovePath(afc_connection *conn, char *dirname);
+
__DLLIMPORT afc_error_t AFCRemovePath(afc_connection *conn, char *dirname);
__DLLIMPORT afc_error_t AFCRenamePath(afc_connection *conn, char *oldpath, char *newpath);
+
__DLLIMPORT afc_error_t AFCRenamePath(afc_connection *conn, char *oldpath, char *newpath);
  +
 
*/
+
*/
__DLLIMPORT afc_error_t AFCDeviceInfoOpen(struct afc_connection *conn, struct
+
__DLLIMPORT afc_error_t AFCDeviceInfoOpen(struct afc_connection *conn, struct
afc_dictionary **info);
+
afc_dictionary **info);
/* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric
+
/* 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. */
+
* value, or if the file '/AFCDEBUG' is present and contains a value. */
#if defined(__APPLE__)
+
#if defined(__APPLE__)
/* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in.
+
/* 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
+
* Note that this normally only accesses the iTunes [[sandbox]]/partition as the
/* Acquires the next entry in a directory previously opened with
+
/* Acquires the next entry in a directory previously opened with
* AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
+
* AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
* of the directory has been reached. '.' and '..' will be returned as the
+
* 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
+
* first two entries in each directory except the root; you may want to skip
* over them.
+
* over them.
*
+
*
* Returns:
+
* Returns:
* MDERR_OK if successful, even if no entries remain
+
* MDERR_OK if successful, even if no entries remain
#if (__ITUNES_VER >= 800)
+
#if (__ITUNES_VER >= 800)
/* Creates symbolic or hard link
+
/* Creates symbolic or hard link
 
* linktype - int64: 1 means hard link, 2 - soft (symbolic) link
 
* linktype - int64: 1 means hard link, 2 - soft (symbolic) link
 
* target - absolute or relative path to link target
 
* target - absolute or relative path to link target
 
* linkname - absolute path where to create new link
 
* linkname - absolute path where to create new link
*/
+
*/
__DLLIMPORT afc_error_t AFCLinkPath(struct afc_connection *conn, long long int linktype, const char *target,
+
__DLLIMPORT afc_error_t AFCLinkPath(struct afc_connection *conn, long long int linktype, const char *target,
const char *linkname);
+
const char *linkname);
  +
  +
#endif
  +
/* Opens file for reading or writing without locking it in any way. afc_file_ref 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 2 = read, mode 3 = write; unknown = 0
  +
* ref - receives file handle
  +
*/
  +
__DLLIMPORT afc_error_t AFCFileRefOpen(struct afc_connection *conn, char *path, unsigned
  +
long long int mode, afc_file_ref *ref);
  +
/* Reads specified amount (len) of bytes from file into buf. Puts actual count of read bytes into len on return
  +
*/
  +
__DLLIMPORT afc_error_t AFCFileRefRead(struct afc_connection *conn, afc_file_ref ref,
  +
void *buf, unsigned int *len);
  +
/* Writes specified amount (len) of bytes from buf into file.
  +
*/
  +
__DLLIMPORT afc_error_t AFCFileRefWrite(struct afc_connection *conn, afc_file_ref ref,
  +
void *buf, unsigned int len);
  +
/* 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 afc_error_t AFCFileRefSeek(struct afc_connection *conn, afc_file_ref ref,
  +
unsigned long long offset, int origin, int unused);
  +
  +
/* Gets the current position of a file pointer into offset argument.
  +
*/
  +
__DLLIMPORT afc_error_t AFCFileRefTell(struct afc_connection *conn, afc_file_ref ref,
  +
unsigned long long* offset);
  +
  +
/* Truncates a file at the specified offset.
  +
*/
  +
__DLLIMPORT afc_error_t AFCFileRefSetFileSize(struct afc_connection *conn, afc_file_ref ref,
  +
unsigned long long offset);
  +
  +
  +
__DLLIMPORT afc_error_t AFCFileRefLock(struct afc_connection *conn, afc_file_ref ref);
  +
__DLLIMPORT afc_error_t AFCFileRefUnlock(struct afc_connection *conn, afc_file_ref ref);
  +
__DLLIMPORT afc_error_t AFCFileRefClose(struct afc_connection *conn, afc_file_ref ref);
  +
  +
/* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo
  +
to get the same information)
  +
*/
  +
__DLLIMPORT afc_error_t AFCFileInfoOpen(struct afc_connection *conn, 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 afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
  +
val);
  +
/* Closes dictionary
  +
*/
  +
__DLLIMPORT afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);
  +
  +
  +
/* Returns the context field of the given AFC connection. */
  +
__DLLIMPORT unsigned int AFCConnectionGetContext(struct afc_connection *conn);
  +
  +
/* Returns the fs_block_size field of the given AFC connection. */
  +
__DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct afc_connection *conn);
  +
  +
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
  +
* 0. */
  +
__DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct afc_connection *conn);
  +
  +
/* Returns the sock_block_size field of the given AFC connection. */
  +
__DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct afc_connection *conn);
  +
  +
/* Closes the given AFC connection. */
  +
__DLLIMPORT afc_error_t AFCConnectionClose(struct afc_connection *conn);
  +
  +
/* 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 unsigned int AMRestoreRegisterForDeviceNotifications(
  +
am_restore_device_notification_callback dfu_connect_callback,
  +
am_restore_device_notification_callback recovery_connect_callback,
  +
am_restore_device_notification_callback dfu_disconnect_callback,
  +
am_restore_device_notification_callback recovery_disconnect_callback,
  +
unsigned int unknown0,
  +
void *user_info);
  +
  +
/* 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 unsigned int AMRestoreEnableFileLogging(char *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 unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
  +
rdev, CFDictionaryRef opts, void *callback, void *user_info);
  +
__DLLIMPORT unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
  +
rdev, CFDictionaryRef opts, void *callback, void *user_info);
  +
__DLLIMPORT struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
  +
unsigned int connection_id, unsigned int unknown1);
  +
__DLLIMPORT unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
  +
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
  +
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
  +
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
  +
ramdisk_path);
  +
__DLLIMPORT unsigned int AMRestoreModeDeviceReboot(struct am_restore_device *rdev); // Added by JB 30.07.2008
  +
__DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct am_device *device);
  +
__DLLIMPORT mach_error_t AMDeviceDisconnect(struct am_device *device);
  +
  +
  +
/* 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);
  +
__DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket, CFStringRef notification, CFStringRef userinfo);
  +
__DLLIMPORT mach_error_t AMDObserveNotification(SOCKET socket, CFSTR notification);
  +
__DLLIMPORT mach_error_t AMDListenForNotifications(SOCKET socket, NOTIFY_CALLBACK cb, USERDATA data);
  +
__DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
  +
  +
/*edits by geohot*/
  +
__DLLIMPORT mach_error_t AMDeviceDeactivate(struct am_device *device);
  +
__DLLIMPORT mach_error_t AMDeviceActivate(struct am_device *device, CFDictionaryRef dict);
  +
__DLLIMPORT mach_error_t AMDeviceRemoveValue(struct am_device *device, unsigned int, CFStringRef cfstring);
  +
  +
/* ----------------------------------------------------------------------------
  +
* Semi-private routines
  +
* ------------------------------------------------------------------------- */
  +
  +
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
  +
* pointer, which will be filled with the resulting usbmux_listener_2.
  +
*
  +
* 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 usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
  +
usbmux_listener_2 **eax_fp12);
  +
  +
/* ----------------------------------------------------------------------------
  +
* Less-documented semi-private routines
  +
* ------------------------------------------------------------------------- */
  +
__DLLIMPORT usbmux_error_t USBMuxListenerHandleData(void *);
  +
  +
/* ----------------------------------------------------------------------------
  +
* Private routines - here be dragons
  +
* ------------------------------------------------------------------------- */
  +
  +
/* 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 am_restore_device *rdev,
  +
CFDictionaryRef op) __attribute__ ((regparm(2)));
  +
t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
  +
*/
  +
  +
/* ----------------------------------------------------------------------------
  +
* Less-documented private routines
  +
* ------------------------------------------------------------------------- */
  +
  +
  +
/*
  +
typedef int (*t_socketForPort)(struct am_restore_device *rdev, unsigned int port)
  +
__attribute__ ((regparm(2)));
  +
t_socketForPort _socketForPort = (t_socketForPort)(void *)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 unsigned int (*t_sendControlPacket)(struct am_recovery_device *rdev, unsigned
  +
int msg1, unsigned int msg2, unsigned int unknown0, unsigned int *unknown1,
  +
unsigned char *unknown2) __attribute__ ((regparm(3)));
  +
t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
  +
  +
typedef unsigned int (*t_sendCommandToDevice)(struct am_recovery_device *rdev,
  +
CFStringRef cmd) __attribute__ ((regparm(2)));
  +
t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
  +
  +
typedef unsigned int (*t_AMRUSBInterfaceReadPipe)(unsigned int readwrite_pipe, unsigned
  +
int read_pipe, unsigned char *data, unsigned int *len);
  +
t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
  +
  +
typedef unsigned int (*t_AMRUSBInterfaceWritePipe)(unsigned int readwrite_pipe, unsigned
  +
int write_pipe, void *data, unsigned int len);
  +
t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
  +
*/
  +
  +
int performOperation(am_restore_device *rdev, CFMutableDictionaryRef message);
  +
int socketForPort(am_restore_device *rdev, unsigned int portnum);
  +
int sendCommandToDevice(am_recovery_device *rdev, CFStringRef cfs, int block);
  +
int sendFileToDevice(am_recovery_device *rdev, CFStringRef filename);
  +
  +
  +
#ifdef __cplusplus
  +
}
  +
#endif
  +
  +
#endif
  +
  +
/* -*- mode:c; indent-tabs-mode:nil; c-basic-offset:2; tab-width:2; */
   
  +
=== AFC Connection ===
#endif
 
/* Opens file for reading or writing without locking it in any way. afc_file_ref 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 2 = read, mode 3 = write; unknown = 0
 
* ref - receives file handle
 
*/
 
__DLLIMPORT afc_error_t AFCFileRefOpen(struct afc_connection *conn, char *path, unsigned
 
long long int mode, afc_file_ref *ref);
 
/* Reads specified amount (len) of bytes from file into buf. Puts actual count of read bytes into len on return
 
*/
 
__DLLIMPORT afc_error_t AFCFileRefRead(struct afc_connection *conn, afc_file_ref ref,
 
void *buf, unsigned int *len);
 
/* Writes specified amount (len) of bytes from buf into file.
 
*/
 
__DLLIMPORT afc_error_t AFCFileRefWrite(struct afc_connection *conn, afc_file_ref ref,
 
void *buf, unsigned int len);
 
/* 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 afc_error_t AFCFileRefSeek(struct afc_connection *conn, afc_file_ref ref,
 
unsigned long long offset, int origin, int unused);
 
 
/* Gets the current position of a file pointer into offset argument.
 
*/
 
__DLLIMPORT afc_error_t AFCFileRefTell(struct afc_connection *conn, afc_file_ref ref,
 
unsigned long long* offset);
 
 
/* Truncates a file at the specified offset.
 
*/
 
__DLLIMPORT afc_error_t AFCFileRefSetFileSize(struct afc_connection *conn, afc_file_ref ref,
 
unsigned long long offset);
 
 
 
__DLLIMPORT afc_error_t AFCFileRefLock(struct afc_connection *conn, afc_file_ref ref);
 
__DLLIMPORT afc_error_t AFCFileRefUnlock(struct afc_connection *conn, afc_file_ref ref);
 
__DLLIMPORT afc_error_t AFCFileRefClose(struct afc_connection *conn, afc_file_ref ref);
 
 
/* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo
 
to get the same information)
 
*/
 
__DLLIMPORT afc_error_t AFCFileInfoOpen(struct afc_connection *conn, 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 afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
 
val);
 
/* Closes dictionary
 
*/
 
__DLLIMPORT afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);
 
 
 
/* Returns the context field of the given AFC connection. */
 
__DLLIMPORT unsigned int AFCConnectionGetContext(struct afc_connection *conn);
 
 
/* Returns the fs_block_size field of the given AFC connection. */
 
__DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct afc_connection *conn);
 
 
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
 
* 0. */
 
__DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct afc_connection *conn);
 
 
/* Returns the sock_block_size field of the given AFC connection. */
 
__DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct afc_connection *conn);
 
 
/* Closes the given AFC connection. */
 
__DLLIMPORT afc_error_t AFCConnectionClose(struct afc_connection *conn);
 
 
/* 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 unsigned int AMRestoreRegisterForDeviceNotifications(
 
am_restore_device_notification_callback dfu_connect_callback,
 
am_restore_device_notification_callback recovery_connect_callback,
 
am_restore_device_notification_callback dfu_disconnect_callback,
 
am_restore_device_notification_callback recovery_disconnect_callback,
 
unsigned int unknown0,
 
void *user_info);
 
 
/* 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 unsigned int AMRestoreEnableFileLogging(char *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 unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
 
rdev, CFDictionaryRef opts, void *callback, void *user_info);
 
__DLLIMPORT unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
 
rdev, CFDictionaryRef opts, void *callback, void *user_info);
 
__DLLIMPORT struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
 
unsigned int connection_id, unsigned int unknown1);
 
__DLLIMPORT unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
 
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
 
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
 
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
 
ramdisk_path);
 
__DLLIMPORT unsigned int AMRestoreModeDeviceReboot(struct am_restore_device *rdev); // Added by JB 30.07.2008
 
__DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct am_device *device);
 
__DLLIMPORT mach_error_t AMDeviceDisconnect(struct am_device *device);
 
 
 
/* 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);
 
__DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket, CFStringRef notification, CFStringRef userinfo);
 
__DLLIMPORT mach_error_t AMDObserveNotification(SOCKET socket, CFSTR notification);
 
__DLLIMPORT mach_error_t AMDListenForNotifications(SOCKET socket, NOTIFY_CALLBACK cb, USERDATA data);
 
__DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
 
 
/*edits by geohot*/
 
__DLLIMPORT mach_error_t AMDeviceDeactivate(struct am_device *device);
 
__DLLIMPORT mach_error_t AMDeviceActivate(struct am_device *device, CFDictionaryRef dict);
 
__DLLIMPORT mach_error_t AMDeviceRemoveValue(struct am_device *device, unsigned int, CFStringRef cfstring);
 
 
/* ----------------------------------------------------------------------------
 
* Semi-private routines
 
* ------------------------------------------------------------------------- */
 
 
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
 
* pointer, which will be filled with the resulting usbmux_listener_2.
 
*
 
* 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 usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
 
usbmux_listener_2 **eax_fp12);
 
 
/* ----------------------------------------------------------------------------
 
* Less-documented semi-private routines
 
* ------------------------------------------------------------------------- */
 
__DLLIMPORT usbmux_error_t USBMuxListenerHandleData(void *);
 
 
/* ----------------------------------------------------------------------------
 
* Private routines - here be dragons
 
* ------------------------------------------------------------------------- */
 
 
/* 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 am_restore_device *rdev,
 
CFDictionaryRef op) __attribute__ ((regparm(2)));
 
t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
 
*/
 
 
/* ----------------------------------------------------------------------------
 
* Less-documented private routines
 
* ------------------------------------------------------------------------- */
 
 
 
/*
 
typedef int (*t_socketForPort)(struct am_restore_device *rdev, unsigned int port)
 
__attribute__ ((regparm(2)));
 
t_socketForPort _socketForPort = (t_socketForPort)(void *)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 unsigned int (*t_sendControlPacket)(struct am_recovery_device *rdev, unsigned
 
int msg1, unsigned int msg2, unsigned int unknown0, unsigned int *unknown1,
 
unsigned char *unknown2) __attribute__ ((regparm(3)));
 
t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
 
 
typedef unsigned int (*t_sendCommandToDevice)(struct am_recovery_device *rdev,
 
CFStringRef cmd) __attribute__ ((regparm(2)));
 
t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
 
 
typedef unsigned int (*t_AMRUSBInterfaceReadPipe)(unsigned int readwrite_pipe, unsigned
 
int read_pipe, unsigned char *data, unsigned int *len);
 
t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
 
 
typedef unsigned int (*t_AMRUSBInterfaceWritePipe)(unsigned int readwrite_pipe, unsigned
 
int write_pipe, void *data, unsigned int len);
 
t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
 
*/
 
 
int performOperation(am_restore_device *rdev, CFMutableDictionaryRef message);
 
int socketForPort(am_restore_device *rdev, unsigned int portnum);
 
int sendCommandToDevice(am_recovery_device *rdev, CFStringRef cfs, int block);
 
int sendFileToDevice(am_recovery_device *rdev, CFStringRef filename);
 
 
 
#ifdef __cplusplus
 
}
 
#endif
 
 
#endif
 
 
/* -*- mode:c; indent-tabs-mode:nil; c-basic-offset:2; tab-width:2; */
 
</pre>
 
 
===AFC Connection===
 
 
...
 
...
   
===Locking the Device for Sync===
+
=== 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.
+
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:
 
To get this behaviour, first start the notification service:
<pre>SOCKET socket;
+
SOCKET socket;
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);</pre>
+
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:
 
Now we post a notificaton message to signal that we are going to start a sync:
<pre>AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncWillStart"), NULL);</pre>
+
AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncWillStart"), NULL);
   
 
Next we open the itunes lock file:
 
Next we open the itunes lock file:
<pre>afc_file_ref lockref;
+
afc_file_ref lockref;
AFCFileRefOpen(conn, "/com.apple.itunes.lock_sync", 2, &lockref);</pre>
+
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.
 
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.
 
If the AFCFileRefLock call fails, pause and repeat.
<pre>AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncLockRequest"), NULL);
+
AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncLockRequest"), NULL);
mach_error_t error = AFCFileRefLock(conn, lockref);</pre>
+
mach_error_t error = AFCFileRefLock(conn, lockref);
   
 
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.
<pre>AMDPostNotification(socket,CFSTR("com.apple.itunes-mobdev.syncDidStart"), NULL);
+
AMDPostNotification(socket,CFSTR("com.apple.itunes-mobdev.syncDidStart"), NULL);
AMDShutdownNotificationProxy(socket);</pre>
+
AMDShutdownNotificationProxy(socket);
   
 
Now the sync can proceed, so copy your files across and make the changes to the iTunesDB.
 
Now the sync can proceed, so copy your files across and make the changes to the iTunesDB.
Line 709: Line 702:
 
To release the lock, start the notification system again, unlock and close the lock file, and send a sync finished notification message:
 
To release the lock, start the notification system again, unlock and close the lock file, and send a sync finished notification message:
   
<pre>AFCFileRefUnlock(conn, lockref);
+
AFCFileRefUnlock(conn, lockref);
AFCFileRefClose(conn, lockref);
+
AFCFileRefClose(conn, lockref);
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);
+
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);
AMDPostNotification(socket, &CFSTR("com.apple.itunes-mobdev.syncDidFinish"), NULL);
+
AMDPostNotification(socket, &CFSTR("com.apple.itunes-mobdev.syncDidFinish"), NULL);
AMDShutdownNotificationProxy(socket);</pre>
+
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”.
Line 719: Line 712:
 
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 flakey when you open/close it all the time.
   
===Known Functions===
+
=== Known Functions ===
  +
* AFCLockCreate
 
  +
* AFCLockFree
AFCLockCreate
 
  +
* AFCLockLock
AFCLockFree
 
  +
* AFCLockTryLock
AFCLockLock
 
  +
* AFCLockUnlock
AFCLockTryLock
 
  +
* AFCStringBufferAlloc
AFCLockUnlock
 
  +
* AFCStringBufferAppend
AFCStringBufferAlloc
 
  +
* AFCStringBufferFree
AFCStringBufferAppend
 
  +
* AFCStringCopy
AFCStringBufferFree
 
  +
* MISProfileCopyPayload
AFCStringCopy
 
  +
* MISProfileCopySignerSubjectSummary
MISProfileCopyPayload
 
  +
* MISProfileCreateDataRepresentation
MISProfileCopySignerSubjectSummary
 
  +
* MISProfileCreateWithData
MISProfileCreateDataRepresentation
 
  +
* MISProfileCreateWithFile
MISProfileCreateWithData
 
  +
* MISProfileGetValue
MISProfileCreateWithFile
 
  +
* MISProfileIsMutable
MISProfileGetValue
 
  +
* MISProfileValidateSignature
MISProfileIsMutable
 
  +
* MISProfileValidateSignatureWithAnchors
MISProfileValidateSignature
 
  +
* MISProfileWriteToFile
MISProfileValidateSignatureWithAnchors
 
  +
* MISProvisioningProfileCheckValidity
MISProfileWriteToFile
 
  +
* MISProvisioningProfileGetCreationDate
MISProvisioningProfileCheckValidity
 
  +
* MISProvisioningProfileGetDeveloperCertificates
MISProvisioningProfileGetCreationDate
 
  +
* MISProvisioningProfileGetExpirationDate
MISProvisioningProfileGetDeveloperCertificates
 
  +
* MISProvisioningProfileGetName
MISProvisioningProfileGetExpirationDate
 
  +
* MISProvisioningProfileGetProvisionedDevices
MISProvisioningProfileGetName
 
  +
* MISProvisioningProfileGetUUID
MISProvisioningProfileGetProvisionedDevices
 
  +
* MISProvisioningProfileGetVersion
MISProvisioningProfileGetUUID
 
  +
* MISProvisioningProfileIncludesDevice
MISProvisioningProfileGetVersion
 
  +
* MISProvisioningProfileProvisionsAllDevices
MISProvisioningProfileIncludesDevice
 
  +
* MISProvisioningProfileValidateSignature
MISProvisioningProfileProvisionsAllDevices
 
  +
* AFCConnectionClose
MISProvisioningProfileValidateSignature
 
  +
* AFCConnectionGetContext
AFCConnectionClose
 
  +
* AFCConnectionGetFSBlockSize
AFCConnectionGetContext
 
  +
* AFCConnectionGetIOTimeout
AFCConnectionGetFSBlockSize
 
  +
* AFCConnectionGetSocketBlockSize
AFCConnectionGetIOTimeout
 
  +
* AFCConnectionOpen
AFCConnectionGetSocketBlockSize
 
  +
* AFCConnectionSetContext
AFCConnectionOpen
 
  +
* AFCConnectionSetFSBlockSize
AFCConnectionSetContext
 
  +
* AFCConnectionSetFatalError
AFCConnectionSetFSBlockSize
 
  +
* AFCConnectionSetIOTimeout
AFCConnectionSetFatalError
 
  +
* AFCConnectionSetSocketBlockSize
AFCConnectionSetIOTimeout
 
  +
* AFCDeviceInfoOpen
AFCConnectionSetSocketBlockSize
 
  +
* AFCDirectoryClose
AFCDeviceInfoOpen
 
  +
* AFCDirectoryCreate
AFCDirectoryClose
 
  +
* AFCDirectoryOpen
AFCDirectoryCreate
 
  +
* AFCDirectoryRead
AFCDirectoryOpen
 
  +
* AFCDiscardBodyData
AFCDirectoryRead
 
  +
* AFCDiscardData
AFCDiscardBodyData
 
  +
* AFCErrnoToAFCError
AFCDiscardData
 
  +
* AFCFileInfoOpen
AFCErrnoToAFCError
 
  +
* AFCFileRefClose
AFCFileInfoOpen
 
  +
* AFCFileRefLock
AFCFileRefClose
 
  +
* AFCFileRefOpen
AFCFileRefLock
 
  +
* AFCFileRefRead
AFCFileRefOpen
 
  +
* AFCFileRefSeek
AFCFileRefRead
 
  +
* AFCFileRefSetFileSize
AFCFileRefSeek
 
  +
* AFCFileRefTell
AFCFileRefSetFileSize
 
  +
* AFCFileRefUnlock
AFCFileRefTell
 
  +
* AFCFileRefWrite
AFCFileRefUnlock
 
  +
* AFCFlushData
AFCFileRefWrite
 
  +
* AFCGetClientVersionString
AFCFlushData
 
  +
* AFCGetDeviceInfo
AFCGetClientVersionString
 
  +
* AFCGetFileInfo
AFCGetDeviceInfo
 
  +
* AFCInitHeader
AFCGetFileInfo
 
  +
* AFCKeyValueClose
AFCInitHeader
 
  +
* AFCKeyValueRead
AFCKeyValueClose
 
  +
* AFCParseDataPacketHeader
AFCKeyValueRead
 
  +
* AFCParseStatusPacket
AFCParseDataPacketHeader
 
  +
* AFCReadData
AFCParseStatusPacket
 
  +
* AFCReadPacket
AFCReadData
 
  +
* AFCReadPacketBody
AFCReadPacket
 
  +
* AFCReadPacketHeader
AFCReadPacketBody
 
  +
* AFCRemovePath
AFCReadPacketHeader
 
  +
* AFCRenamePath
AFCRemovePath
 
  +
* AFCSendData
AFCRenamePath
 
  +
* AFCSendDataPacket
AFCSendData
 
  +
* AFCSendHeader
AFCSendDataPacket
 
  +
* AFCSendPacket
AFCSendHeader
 
  +
* AFCSendStatus
AFCSendPacket
 
  +
* AFCValidateHeader
AFCSendStatus
 
  +
* AMDFUModeDeviceGetLocationID
AFCValidateHeader
 
  +
* AMDFUModeDeviceGetProductID
AMDFUModeDeviceGetLocationID
 
  +
* AMDFUModeDeviceGetProductType
AMDFUModeDeviceGetProductID
 
  +
* AMDFUModeDeviceGetProgress
AMDFUModeDeviceGetProductType
 
  +
* AMDFUModeDeviceGetTypeID
AMDFUModeDeviceGetProgress
 
  +
* AMDListenForNotifications
AMDFUModeDeviceGetTypeID
 
  +
* AMDObserveNotification
AMDListenForNotifications
 
  +
* AMDPostNotification
AMDObserveNotification
 
  +
* AMDShutdownNotificationProxy
AMDPostNotification
 
  +
* AMDeviceActivate
AMDShutdownNotificationProxy
 
  +
* AMDeviceArchiveApplication
AMDeviceActivate
 
  +
* AMDeviceConnect
AMDeviceArchiveApplication
 
  +
* AMDeviceCopyDeviceIdentifier
AMDeviceConnect
 
  +
* AMDeviceCopyProvisioningProfiles
AMDeviceCopyDeviceIdentifier
 
  +
* AMDeviceCopyValue
AMDeviceCopyProvisioningProfiles
 
  +
* AMDeviceDeactivate
AMDeviceCopyValue
 
  +
* AMDeviceDisconnect
AMDeviceDeactivate
 
  +
* AMDeviceEnterRecovery
AMDeviceDisconnect
 
  +
* AMDeviceGetConnectionID
AMDeviceEnterRecovery
 
  +
* AMDeviceInstallApplication
AMDeviceGetConnectionID
 
  +
* AMDeviceInstallProvisioningProfile
AMDeviceInstallApplication
 
  +
* AMDeviceIsPaired
AMDeviceInstallProvisioningProfile
 
  +
* AMDeviceIsValid
AMDeviceIsPaired
 
  +
* AMDeviceLookupApplicationArchives
AMDeviceIsValid
 
  +
* AMDeviceLookupApplications
AMDeviceLookupApplicationArchives
 
  +
* AMDeviceNotificationGetThreadHandle
AMDeviceLookupApplications
 
  +
* AMDeviceNotificationSubscribe
AMDeviceNotificationGetThreadHandle
 
  +
* AMDeviceNotificationUnsubscribe
AMDeviceNotificationSubscribe
 
  +
* AMDevicePair
AMDeviceNotificationUnsubscribe
 
  +
* AMDeviceRelease
AMDevicePair
 
  +
* AMDeviceRemoveApplicationArchive
AMDeviceRelease
 
  +
* AMDeviceRemoveProvisioningProfile
AMDeviceRemoveApplicationArchive
 
  +
* AMDeviceRemoveValue
AMDeviceRemoveProvisioningProfile
 
  +
* AMDeviceRestoreApplication
AMDeviceRemoveValue
 
  +
* AMDeviceRetain
AMDeviceRestoreApplication
 
  +
* AMDeviceSetValue
AMDeviceRetain
 
  +
* AMDeviceSoftwareUpdate
AMDeviceSetValue
 
  +
* AMDeviceStartHouseArrestService
AMDeviceSoftwareUpdate
 
  +
* AMDeviceStartService
AMDeviceStartHouseArrestService
 
  +
* AMDeviceStartSession
AMDeviceStartService
 
  +
* AMDeviceStopSession
AMDeviceStartSession
 
  +
* AMDeviceTransferApplication
AMDeviceStopSession
 
  +
* AMDeviceUninstallApplication
AMDeviceTransferApplication
 
  +
* AMDeviceValidatePairing
AMDeviceUninstallApplication
 
  +
* AMRecoveryModeDeviceCopyIMEI
AMDeviceValidatePairing
 
  +
* AMRecoveryModeDeviceCopySerialNumber
AMRecoveryModeDeviceCopyIMEI
 
  +
* AMRecoveryModeDeviceGetLocationID
AMRecoveryModeDeviceCopySerialNumber
 
  +
* AMRecoveryModeDeviceGetProductID
AMRecoveryModeDeviceGetLocationID
 
  +
* AMRecoveryModeDeviceGetProductType
AMRecoveryModeDeviceGetProductID
 
  +
* AMRecoveryModeDeviceGetProgress
AMRecoveryModeDeviceGetProductType
 
  +
* AMRecoveryModeDeviceGetSecurityEpoch
AMRecoveryModeDeviceGetProgress
 
  +
* AMRecoveryModeDeviceGetTypeID
AMRecoveryModeDeviceGetSecurityEpoch
 
  +
* AMRecoveryModeDeviceReboot
AMRecoveryModeDeviceGetTypeID
 
  +
* AMRecoveryModeDeviceSetAutoBoot
AMRecoveryModeDeviceReboot
 
  +
* AMRecoveryModeGetSoftwareBuildVersion
AMRecoveryModeDeviceSetAutoBoot
 
  +
* AMRestoreCreateBootArgsByAddingArg
AMRecoveryModeGetSoftwareBuildVersion
 
  +
* AMRestoreCreateBootArgsByRemovingArg
AMRestoreCreateBootArgsByAddingArg
 
  +
* AMRestoreCreateDefaultOptions
AMRestoreCreateBootArgsByRemovingArg
 
  +
* AMRestoreCreateDefaultOptionsForIdentification
AMRestoreCreateDefaultOptions
 
  +
* AMRestoreCreatePathsForBundle
AMRestoreCreateDefaultOptionsForIdentification
 
  +
* AMRestoreDisableFileLogging
AMRestoreCreatePathsForBundle
 
  +
* AMRestoreEnableExtraDFUDevices
AMRestoreDisableFileLogging
 
  +
* AMRestoreEnableFileLogging
AMRestoreEnableExtraDFUDevices
 
  +
* AMRestoreGetSupportedPayloadVersion
AMRestoreEnableFileLogging
 
  +
* AMRestoreModeDeviceCopyIMEI
AMRestoreGetSupportedPayloadVersion
 
  +
* AMRestoreModeDeviceCopyRestoreLog
AMRestoreModeDeviceCopyIMEI
 
  +
* AMRestoreModeDeviceCopySerialNumber
AMRestoreModeDeviceCopyRestoreLog
 
  +
* AMRestoreModeDeviceCreate
AMRestoreModeDeviceCopySerialNumber
 
  +
* AMRestoreModeDeviceGetDeviceID
AMRestoreModeDeviceCreate
 
  +
* AMRestoreModeDeviceGetLocationID
AMRestoreModeDeviceGetDeviceID
 
  +
* AMRestoreModeDeviceGetProgress
AMRestoreModeDeviceGetLocationID
 
  +
* AMRestoreModeDeviceGetTypeID
AMRestoreModeDeviceGetProgress
 
  +
* AMRestoreModeDeviceReboot
AMRestoreModeDeviceGetTypeID
 
  +
* AMRestorePerformDFURestore
AMRestoreModeDeviceReboot
 
  +
* AMRestorePerformRecoveryModeRestore
AMRestorePerformDFURestore
 
  +
* AMRestorePerformRestoreModeRestore
AMRestorePerformRecoveryModeRestore
 
  +
* AMRestoreRegisterForDeviceNotifications
AMRestorePerformRestoreModeRestore
 
  +
* AMRestoreSetLogLevel
AMRestoreRegisterForDeviceNotifications
 
  +
* AMSBackup
AMRestoreSetLogLevel
 
  +
* AMSBeginSync
AMSBackup
 
  +
* AMSBeginSyncForDataClasses
AMSBeginSync
 
  +
* AMSCancelBackupRestore
AMSBeginSyncForDataClasses
 
  +
* AMSCancelCrashReportCopy
AMSCancelBackupRestore
 
  +
* AMSCancelSync
AMSCancelCrashReportCopy
 
  +
* AMSCancelSyncDiagnostics
AMSCancelSync
 
  +
* AMSCleanup
AMSCancelSyncDiagnostics
 
  +
* AMSConnectToCrashReportCopyTarget
AMSCleanup
 
  +
* AMSCopyAndSubmitCrashLogs
AMSConnectToCrashReportCopyTarget
 
  +
* AMSCopyAndSubmitCrashLogsFromTarget
AMSCopyAndSubmitCrashLogs
 
  +
* AMSCopyApplicationListFromBackup
AMSCopyAndSubmitCrashLogsFromTarget
 
  +
* AMSCopyCrashReportPath
AMSCopyApplicationListFromBackup
 
  +
* AMSCopyCrashReportsFromTarget
AMSCopyCrashReportPath
 
  +
* AMSCopySourcesForRestoreCompatibleWith
AMSCopyCrashReportsFromTarget
 
  +
* AMSDisconnectFromCrashReportCopyTarget
AMSCopySourcesForRestoreCompatibleWith
 
  +
* AMSGetAOSUsername
AMSDisconnectFromCrashReportCopyTarget
 
  +
* AMSGetApplicationProviderInfo
AMSGetAOSUsername
 
  +
* AMSGetCalendarDayLimit
AMSGetApplicationProviderInfo
 
  +
* AMSGetClientIdentifierAndDisplayNameForTarget
AMSGetCalendarDayLimit
 
  +
* AMSGetCollectionsForDataClassName
AMSGetClientIdentifierAndDisplayNameForTarget
 
  +
* AMSGetConflictInformation
AMSGetCollectionsForDataClassName
 
  +
* AMSGetConflictInformationForIdentifiers
AMSGetConflictInformation
 
  +
* AMSGetCrashReportCopyPreferencesForTarget
AMSGetConflictInformationForIdentifiers
 
  +
* AMSGetDCAChangeInformation
AMSGetCrashReportCopyPreferencesForTarget
 
  +
* AMSGetDataChangeAlertInfo
AMSGetDCAChangeInformation
 
  +
* AMSGetDataClassInfoForTarget
AMSGetDataChangeAlertInfo
 
  +
* AMSGetLastSyncDateForDataClass
AMSGetDataClassInfoForTarget
 
  +
* AMSGetNewRecordCalendarName
AMSGetLastSyncDateForDataClass
 
  +
* AMSGetNewRecordGroupName
AMSGetNewRecordCalendarName
 
  +
* AMSGetNumberOfCrashReportsToCopy
AMSGetNewRecordGroupName
 
  +
* AMSGetNumberOfCrashReportsToSubmit
AMSGetNumberOfCrashReportsToCopy
 
  +
* AMSGetSourcesForRestore
AMSGetNumberOfCrashReportsToSubmit
 
  +
* AMSGetSupportedDataClassNames
AMSGetSourcesForRestore
 
  +
* AMSInitialize
AMSGetSupportedDataClassNames
 
  +
* AMSRefreshCollectionsForDataClassName
AMSInitialize
 
  +
* AMSRegisterCallbacks
AMSRefreshCollectionsForDataClassName
 
  +
* AMSRegisterClientWithTargetIdentifierAndDisplayName
AMSRegisterCallbacks
 
  +
* AMSResetSyncData
AMSRegisterClientWithTargetIdentifierAndDisplayName
 
  +
* AMSRestore
AMSResetSyncData
 
  +
* AMSRestoreWithApplications
AMSRestore
 
  +
* AMSRunSyncDiagnostics
AMSRestoreWithApplications
 
  +
* AMSSetCalendarDayLimit
AMSRunSyncDiagnostics
 
  +
* AMSSetConflictWinners
AMSSetCalendarDayLimit
 
  +
* AMSSetCrashReportCopyPreferencesForTarget
AMSSetConflictWinners
 
  +
* AMSSetDataChangeAlertInfo
AMSSetCrashReportCopyPreferencesForTarget
 
  +
* AMSSetDataClassInfoForTarget
AMSSetDataChangeAlertInfo
 
  +
* AMSSetDesignatedProviderForDataClassName
AMSSetDataClassInfoForTarget
 
  +
* AMSSetFilteredCollectionNamesForDataClassName
AMSSetDesignatedProviderForDataClassName
 
  +
* AMSSetNewRecordCalendarName
AMSSetFilteredCollectionNamesForDataClassName
 
  +
* AMSSetNewRecordGroupName
AMSSetNewRecordCalendarName
 
  +
* AMSSubmitCrashReportsFromTarget
AMSSetNewRecordGroupName
 
  +
* AMSSyncConflictsSelections
AMSSubmitCrashReportsFromTarget
 
  +
* AMSUnregisterTarget
AMSSyncConflictsSelections
 
  +
* ASRServerHandleConnection
AMSUnregisterTarget
 
  +
* GoogleSyncConduitCopyUsername
ASRServerHandleConnection
 
  +
* GoogleSyncConduitRegisterClient
GoogleSyncConduitCopyUsername
 
  +
* GoogleSyncConduitSetUsernameAndPassword
GoogleSyncConduitRegisterClient
 
  +
* GoogleSyncConduitUnregisterClient
GoogleSyncConduitSetUsernameAndPassword
 
  +
* GoogleSyncConduitValidateUser
GoogleSyncConduitUnregisterClient
 
  +
* USBMuxConnectByPort
GoogleSyncConduitValidateUser
 
  +
* USBMuxListenForDevices
USBMuxConnectByPort
 
  +
* USBMuxListenerClose
USBMuxListenForDevices
 
  +
* USBMuxListenerCreate
USBMuxListenerClose
 
  +
* USBMuxListenerGetEvent
USBMuxListenerCreate
 
  +
* USBMuxListenerGetFD
USBMuxListenerGetEvent
 
  +
* USBMuxListenerHandleData
USBMuxListenerGetFD
 
  +
* USBMuxListenerSetDebug
USBMuxListenerHandleData
 
  +
* YahooConduitCopyYahooID
USBMuxListenerSetDebug
 
  +
* YahooConduitIsTokenValid
YahooConduitCopyYahooID
 
  +
* YahooConduitLastSyncError
YahooConduitIsTokenValid
 
  +
* YahooConduitRegister
YahooConduitLastSyncError
 
  +
* YahooConduitUnregister
YahooConduitRegister
 
  +
* kAMDMobileDeviceVersionNumber
YahooConduitUnregister
 
  +
* kLDErrorInvalidResponse
kAMDMobileDeviceVersionNumber
 
  +
* lockdown_activate
kLDErrorInvalidResponse
 
  +
* lockdown_connection_create
lockdown_activate
 
  +
* lockdown_connection_destroy
lockdown_connection_create
 
  +
* lockdown_get_value
lockdown_connection_destroy
 
  +
* lockdown_goodbye
lockdown_get_value
 
  +
* lockdown_pair
lockdown_goodbye
 
  +
* lockdown_remove_value
lockdown_pair
 
  +
* lockdown_service_start
lockdown_remove_value
 
  +
* lockdown_session_start
lockdown_service_start
 
  +
* lockdown_session_stop
lockdown_session_start
 
  +
* lockdown_set_value
lockdown_session_stop
 
lockdown_set_value
 
 
===Private Functions===
 
 
====How to find address of privates functions in iTunesMobileDevice.dll or MobileDevice.framework====
 
   
  +
=== Private Functions ===
  +
==== 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.
   
====Private Function Address List====
+
==== Private Function Address List ====
  +
===== OSX 10.6 - [[iTunes]] 9.0.2(25) =====
 
  +
unsigned int sendCommandToiBoot(struct am_recovery_device *rdev, CFStringRef command, int u);
=====OSX.6 - iTunes 9.0.2(25)=====
 
<pre>unsigned int sendCommandToiBoot(struct am_recovery_device *rdev, CFStringRef command, int u);</pre>
 
 
Address is obtainable by adding 868(0x364) to the address of AMRecoveryDeviceGetProductType(), a public symbol that you can obtain via nlist() or dlsym().
 
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
+
Address: <code>0x1000245ea</code>
   
 
Parameters
 
Parameters
1. rdev - the device you wish to send the command to.
+
# rdev - the device you wish to send the command to.
2. a CFStringRef of the command to send.
+
# a CFStringRef of the command to send.
3. 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.
   
<pre>unsigned int sendFileToiDevice(struct am_recovery_device *rdev, CFStringRef filename);</pre>
+
unsigned int sendFileToiDevice(struct am_recovery_device *rdev, 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: 0x100024969
+
Address: <code>0x100024969</code>
   
 
Parameters
 
Parameters
1. rdev - the device you wish to send the file to.
+
# rdev - the device you wish to send the file to.
2. a CFStringRef of the path to the file to send.
+
# a CFStringRef of the path to the file to send.
   
=====OSX.6 - iTunes 9.0.3(15)=====
+
===== OSX 10.6 - [[iTunes]] 9.0.3(15) =====
<pre>unsigned int sendCommandToiBoot(struct am_recovery_device *rdev, CFStringRef command, int u);</pre>
+
unsigned int sendCommandToiBoot(struct am_recovery_device *rdev, CFStringRef command, int u);
Addresss: AMRecoveryDeviceGetProductType() + 0x37f(895); full offset: 0x2a0ed
+
Addresss: <code>AMRecoveryDeviceGetProductType() + 0x37f(895); full offset: 0x2a0ed</code>
   
<pre>unsigned int sendFileToiDevice(struct am_recovery_device *rdev, CFStringRef filename);</pre>
+
unsigned int sendFileToiDevice(struct am_recovery_device *rdev, CFStringRef filename);
Address: AMRecoveryDeviceGetProductType()+0x6f3(1790); full offset: 0x2a46c
+
Address: <code>AMRecoveryDeviceGetProductType()+0x6f3(1790); full offset: 0x2a46c</code>
   
 
As of now, Apple has decided to make these functions public with the following names:
 
As of now, Apple has decided to make these functions public with the following names:
Line 1,009: Line 998:
 
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.
 
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.
   
===Libraries Implementations===
+
=== Libraries Implementations ===
  +
* MobileDevice Library for Windows with CoreFoundation support
 
* [http://www.libimobiledevice.org/ Libimobiledevice (provides the same functionality on GNU/Linux)]
 
* [http://www.libimobiledevice.org/ Libimobiledevice (provides the same functionality on GNU/Linux)]

Revision as of 17:42, 12 August 2011

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.

/* ----------------------------------------------------------------------------
 *   MobileDevice.h - interface to MobileDevice.framework 
 * ------------------------------------------------------------------------- */
#pragma once

#ifndef MOBILEDEVICE_H
#define MOBILEDEVICE_H

#ifdef __cplusplus
extern "C" {
#endif
	
#ifndef __GCC__
#pragma pack
#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
	 * am_device_notification_callback_info. */
#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 unsigned int afc_error_t;
	typedef unsigned int usbmux_error_t;
	
	struct am_recovery_device;
	
	struct am_device_notification_callback_info {
		struct am_device *dev;  /* 0    device */ 
		unsigned int msg;       /* 4    one of ADNCI_MSG_* */
               struct am_device_notification* subscription; 
	} __PACK;
	
	/* The type of the device restore notification callback functions.
	 * TODO: change to correct type. */
	typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
	
	/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
	struct am_recovery_device {
		unsigned char unknown0[8];                          /* 0 */
		am_restore_device_notification_callback callback;   /* 8 */
		void *user_info;                                    /* 12 */
		unsigned char unknown1[12];                         /* 16 */
		unsigned int readwrite_pipe;                        /* 28 */
		unsigned char read_pipe;                            /* 32 */
		unsigned char write_ctrl_pipe;                      /* 33 */
		unsigned char read_unknown_pipe;                    /* 34 */
		unsigned char write_file_pipe;                      /* 35 */
		unsigned char write_input_pipe;                     /* 36 */
	} __PACK;
	
	/* A CoreFoundation object of class AMRestoreModeDevice. */
	struct am_restore_device {
		unsigned char unknown[32];
		int port;
	} __PACK;
	
	/* The type of the device notification callback function. */
	typedef void(*am_device_notification_callback)(struct am_device_notification_callback_info *, int cookie);
	
	/* The type of the _AMDDeviceAttached function.
	 * TODO: change to correct type. */
	typedef void *amd_device_attached_callback;
	
	/* The type of the device restore notification callback functions.
	 * TODO: change to correct type. */
	typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);

	/* Structure that contains internal data used by AMDevice... functions. Never try 
        * to access its members directly! Use AMDeviceCopyDeviceIdentifier, 
        * AMDeviceGetConnectionID, AMDeviceRetain, AMDeviceRelease instead. */
	struct am_device {
		unsigned char unknown0[16]; /* 0 - zero */
		unsigned int device_id;     /* 16 */
		unsigned int product_id;    /* 20 - set to AMD_IPHONE_PRODUCT_ID */
		char *serial;               /* 24 - set to UDID, Unique Device Identifier */
		unsigned int unknown1;      /* 28 */
		unsigned int unknown2;      /* 32 - reference counter, increased by AMDeviceRetain, decreased by AMDeviceRelease*/
		unsigned int lockdown_conn; /* 36 */
		unsigned char unknown3[8];  /* 40 */
#if (__ITUNES_VER > 740)
		unsigned int unknown4;      /* 48 - used to store CriticalSection Handle*/
#endif
#if (__ITUNES_VER >= 800)
		unsigned char unknown5[24];  /* 52 */
#endif
	} __PACK;
	
	struct am_device_notification {
		unsigned int unknown0;                      /* 0 */
		unsigned int unknown1;                      /* 4 */
		unsigned int unknown2;                      /* 8 */
		am_device_notification_callback callback;   /* 12 */ 
		unsigned int cookie;                      /* 16 */
	} __PACK;
	
	struct afc_connection {
		unsigned int handle;            /* 0 */
		unsigned int unknown0;          /* 4 */
		unsigned char unknown1;         /* 8 */
		unsigned char padding[3];       /* 9 */
		unsigned int unknown2;          /* 12 */
		unsigned int unknown3;          /* 16 */
		unsigned int unknown4;          /* 20 */
		unsigned int fs_block_size;     /* 24 */
		unsigned int sock_block_size;   /* 28: always 0x3c */
		unsigned int io_timeout;        /* 32: from AFCConnectionOpen, usu. 0 */
		void *afc_lock;                 /* 36 */
		unsigned int context;           /* 40 */
	} __PACK;
	
	

	struct afc_device_info {
		unsigned char unknown[12];  /* 0 */
	} __PACK;

	struct afc_directory {
		unsigned char unknown[0];   /* size unknown */
	} __PACK;

	struct afc_dictionary {
		unsigned char unknown[0];   /* size unknown */
	} __PACK;
	
	typedef unsigned long long afc_file_ref;
	
	struct usbmux_listener_1 {                  /* offset   value in iTunes */
		unsigned int unknown0;                  /* 0        1 */
		unsigned char *unknown1;                /* 4        ptr, maybe device? */
		amd_device_attached_callback callback;  /* 8        _AMDDeviceAttached */
		unsigned int unknown3;                  /* 12 */
		unsigned int unknown4;                  /* 16 */
		unsigned int unknown5;                  /* 20 */
	} __PACK;
	
	struct usbmux_listener_2 {
		unsigned char unknown0[4144];
	} __PACK;
	
	struct am_bootloader_control_packet {
		unsigned char opcode;       /* 0 */
		unsigned char length;       /* 1 */
		unsigned char magic[2];     /* 2: 0x34, 0x12 */
		unsigned char payload[0];   /* 4 */
	} __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 acces 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(am_device_notification_callback callback, 
								unsigned int unused0, unsigned int unused1, 
								unsigned int cookie, 
								struct am_device_notification **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(am_device_notification* subscription);

	/*  Returns device_id field of am_device structure
	 */
	__DLLIMPORT unsigned int AMDeviceGetConnectionID(struct am_device *device);

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

	/*  Connects to the iPhone. Pass in the am_device 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 am_device *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 am_device *device);
	__DLLIMPORT mach_error_t AMDevicePair(struct am_device *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 am_device *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 am_device *device);


	/* Reads various device settings. One of domain or cfstring arguments should be NULL.
        *
        * Possible values for cfstring:
	 * ActivationState
	 * ActivationStateAcknowledged
	 * BasebandBootloaderVersion
	 * BasebandVersion
	 * BluetoothAddress
	 * BuildVersion
	 * DeviceCertificate
	 * DeviceClass
	 * DeviceName
	 * DevicePublicKey
	 * FirmwareVersion
	 * HostAttached
	 * IntegratedCircuitCardIdentity
	 * InternationalMobileEquipmentIdentity
	 * InternationalMobileSubscriberIdentity
	 * ModelNumber
	 * PhoneNumber
	 * ProductType
	 * ProductVersion
	 * ProtocolVersion
	 * RegionInfo
	 * SBLockdownEverRegisteredKey
	 * SIMStatus
	 * SerialNumber
	 * SomebodySetTimeZone
	 * TimeIntervalSince1970
	 * TimeZone
	 * TimeZoneOffsetFromUTC
	 * TrustedHostAttached
	 * UniqueDeviceID
	 * Uses24HourClock
	 * WiFiAddress
	 * iTunesHasConnected
        *
        * Possible values for domain:
        * com.apple.mobile.battery
	 */
	__DLLIMPORT CFStringRef AMDeviceCopyValue(struct am_device *device, CFStringRef domain, CFStringRef cfstring);
	
	/* 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 am_device *device, CFStringRef 
									  service_name, int *socket_fd);
	
	/* 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 am_device *device);
	
	/* Decrements reference counter and, if nothing left, releases resources hold 
	 * by connection, invalidates  pointer to device
	 */
	__DLLIMPORT void AMDeviceRelease(struct am_device *device);

	/* Increments reference counter
	 */
	__DLLIMPORT void AMDeviceRetain(struct am_device *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 afc_error_t AFCConnectionOpen(int socket_fd, unsigned int io_timeout,
								  struct afc_connection **conn);


       /* Copy an enviromental variable value from iBoot
       */
       __DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct am_recovery_device *rdev, CFStringRef var);
	
	/* 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 afc_error_t AFCDeviceInfoOpen(struct afc_connection *conn, struct
								  afc_dictionary **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 afc_error_t AFCDirectoryOpen(struct afc_connection *conn, char *path, struct
								 afc_directory **dir);
	
	/* 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 afc_error_t AFCDirectoryRead(struct afc_connection *conn, struct afc_directory *dir,
								 char **dirent);
	__DLLIMPORT afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
	__DLLIMPORT afc_error_t AFCDirectoryCreate(afc_connection *conn, char *dirname);
	__DLLIMPORT afc_error_t AFCRemovePath(afc_connection *conn, char *dirname);
	__DLLIMPORT afc_error_t AFCRenamePath(afc_connection *conn, char *oldpath, char *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 afc_error_t AFCLinkPath(struct afc_connection *conn, long long int linktype, const char *target, 
								                              const char *linkname);

#endif
	/* Opens file for reading or writing without locking it in any way. afc_file_ref 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 2 = read, mode 3 = write; unknown = 0 
	 * ref - receives file handle
	 */
	__DLLIMPORT afc_error_t AFCFileRefOpen(struct afc_connection *conn, char *path, unsigned
							   long long int mode, afc_file_ref *ref);
	/* Reads specified amount (len) of bytes from file into buf. Puts actual count of read bytes into len on return
	 */
	__DLLIMPORT afc_error_t AFCFileRefRead(struct afc_connection *conn, afc_file_ref ref,
							   void *buf, unsigned int *len);
	/* Writes specified amount (len) of bytes from buf into file.
	 */
	__DLLIMPORT afc_error_t AFCFileRefWrite(struct afc_connection *conn, afc_file_ref ref,
								void *buf, unsigned int len);
	/* 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 afc_error_t AFCFileRefSeek(struct afc_connection *conn, afc_file_ref ref,
							   unsigned long long offset, int origin, int unused);

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

	/*  Truncates a file at the specified offset.
	 */
	__DLLIMPORT afc_error_t AFCFileRefSetFileSize(struct afc_connection *conn, afc_file_ref ref,
							   unsigned long long offset);


	__DLLIMPORT afc_error_t AFCFileRefLock(struct afc_connection *conn, afc_file_ref ref);
	__DLLIMPORT afc_error_t AFCFileRefUnlock(struct afc_connection *conn, afc_file_ref ref);
	__DLLIMPORT afc_error_t AFCFileRefClose(struct afc_connection *conn, afc_file_ref ref);

	/* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo
	   to get the same information)
	*/
	__DLLIMPORT afc_error_t AFCFileInfoOpen(struct afc_connection *conn, 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 afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
								val);
	/* Closes dictionary
	*/
	__DLLIMPORT afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);

	
	/* Returns the context field of the given AFC connection. */
	__DLLIMPORT unsigned int AFCConnectionGetContext(struct afc_connection *conn);
	
	/* Returns the fs_block_size field of the given AFC connection. */
	__DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct afc_connection *conn);
	
	/* Returns the io_timeout field of the given AFC connection. In iTunes this is
	 * 0. */
	__DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct afc_connection *conn);
	
	/* Returns the sock_block_size field of the given AFC connection. */
	__DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct afc_connection *conn);
	
	/* Closes the given AFC connection. */
	__DLLIMPORT afc_error_t AFCConnectionClose(struct afc_connection *conn);
	
	/* 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 unsigned int AMRestoreRegisterForDeviceNotifications(
				am_restore_device_notification_callback dfu_connect_callback,
				am_restore_device_notification_callback recovery_connect_callback,
				am_restore_device_notification_callback dfu_disconnect_callback,
				am_restore_device_notification_callback recovery_disconnect_callback,
				unsigned int unknown0,
				void *user_info);
	
	/* 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 unsigned int AMRestoreEnableFileLogging(char *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 unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
				rdev, CFDictionaryRef opts, void *callback, void *user_info);
	__DLLIMPORT unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
				rdev, CFDictionaryRef opts, void *callback, void *user_info);
	__DLLIMPORT struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
				unsigned int connection_id, unsigned int unknown1);
	__DLLIMPORT unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
				CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
				unknown0, CFStringRef *firmware_dir_path, CFStringRef *
				kernelcache_restore_path, unsigned int unknown1, CFStringRef *
				ramdisk_path);
	__DLLIMPORT unsigned int AMRestoreModeDeviceReboot(struct am_restore_device *rdev);	// Added by JB 30.07.2008
	__DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct am_device *device);
	__DLLIMPORT mach_error_t AMDeviceDisconnect(struct am_device *device);


	/* 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);
	__DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket, CFStringRef  notification, CFStringRef userinfo);
	__DLLIMPORT mach_error_t AMDObserveNotification(SOCKET socket, CFSTR notification);
	__DLLIMPORT mach_error_t AMDListenForNotifications(SOCKET socket, NOTIFY_CALLBACK cb, USERDATA data);
	__DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
	
	/*edits by geohot*/
	__DLLIMPORT mach_error_t AMDeviceDeactivate(struct am_device *device);
	__DLLIMPORT mach_error_t AMDeviceActivate(struct am_device *device, CFDictionaryRef dict);
	__DLLIMPORT mach_error_t AMDeviceRemoveValue(struct am_device *device, unsigned int, CFStringRef cfstring);
	
	/* ----------------------------------------------------------------------------
	 *   Semi-private routines
	 * ------------------------------------------------------------------------- */
	
	/*  Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
	 *  pointer, which will be filled with the resulting usbmux_listener_2.
	 *
	 *  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 usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
										usbmux_listener_2 **eax_fp12);
	
	/* ----------------------------------------------------------------------------
	 *   Less-documented semi-private routines
	 * ------------------------------------------------------------------------- */
	__DLLIMPORT usbmux_error_t USBMuxListenerHandleData(void *);
	
	/* ----------------------------------------------------------------------------
	 *   Private routines - here be dragons
	 * ------------------------------------------------------------------------- */
	
	/* 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 am_restore_device *rdev,
	 CFDictionaryRef op) __attribute__ ((regparm(2)));
	 t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
	 */ 
	
	/* ----------------------------------------------------------------------------
	 *   Less-documented private routines
	 * ------------------------------------------------------------------------- */
	
	
	/*
	 typedef int (*t_socketForPort)(struct am_restore_device *rdev, unsigned int port)
	 __attribute__ ((regparm(2)));
	 t_socketForPort _socketForPort = (t_socketForPort)(void *)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 unsigned int (*t_sendControlPacket)(struct am_recovery_device *rdev, unsigned
	 int msg1, unsigned int msg2, unsigned int unknown0, unsigned int *unknown1,
	 unsigned char *unknown2) __attribute__ ((regparm(3)));
	 t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
	 
	 typedef unsigned int (*t_sendCommandToDevice)(struct am_recovery_device *rdev,
	 CFStringRef cmd) __attribute__ ((regparm(2)));
	 t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
	 
	 typedef unsigned int (*t_AMRUSBInterfaceReadPipe)(unsigned int readwrite_pipe, unsigned
	 int read_pipe, unsigned char *data, unsigned int *len);
	 t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
	 
	 typedef unsigned int (*t_AMRUSBInterfaceWritePipe)(unsigned int readwrite_pipe, unsigned
	 int write_pipe, void *data, unsigned int len);
	 t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
	 */
	
	int performOperation(am_restore_device *rdev, CFMutableDictionaryRef message);
	int socketForPort(am_restore_device *rdev, unsigned int portnum);
	int sendCommandToDevice(am_recovery_device *rdev, CFStringRef cfs, int block);
	int sendFileToDevice(am_recovery_device *rdev, CFStringRef filename); 
	

#ifdef __cplusplus
}
#endif

#endif

/* -*- mode:c; indent-tabs-mode:nil; c-basic-offset:2; tab-width:2; */

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:

afc_file_ref 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 flakey when you open/close it all the time.

Known Functions

  • 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

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.

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.
unsigned int sendFileToiDevice(struct am_recovery_device *rdev, 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 am_recovery_device *rdev, CFStringRef command, int u);

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

unsigned int sendFileToiDevice(struct am_recovery_device *rdev, 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.

Libraries Implementations