Ejemplo n.º 1
0
kern_return_t test_apple_AFCOperationCreateGetConnectionInfo(struct am_device *apple, CFTypeRef *response) {
	kern_return_t apple_return = kAMDUndefinedError;
	kern_return_t result = AMDeviceConnect(apple);
	if (SDM_MD_CallSuccessful(result)) {
		result = AMDeviceStartSession(apple);
		if (SDM_MD_CallSuccessful(result)) {
			service_conn_t test_apple_afc_conn;
			result = AMDeviceStartService(apple, CFSTR(AMSVC_AFC), &test_apple_afc_conn, NULL);
			if (SDM_MD_CallSuccessful(result)) {
				struct afc_connection *afc = NULL;
				result = AFCConnectionOpen(test_apple_afc_conn, 0, &afc);
				if (afc) {
					afc_operation conn_info = AFCOperationCreateGetConnectionInfo(kCFAllocatorDefault, NULL);
					result = AFCConnectionProcessOperation(afc, conn_info, 0);
					if (SDM_MD_CallSuccessful(result)) {
						CFTypeRef test = AFCOperationGetResultObject(conn_info);
						if (test) {
							*response = test;
							apple_return = kAMDSuccess;
						}
					}
					AFCConnectionClose(afc);
				}
			}
			AMDeviceStopSession(apple);
		}
		AMDeviceDisconnect(apple);
	}
	return apple_return;
}
kern_return_t test_apple_AMDeviceCopyValue(struct am_device *apple, CFTypeRef *value) {
	kern_return_t apple_return = kAMDUndefinedError;
	CFTypeRef apple_value = NULL;
	kern_return_t result = AMDeviceConnect(apple);
	if (SDM_MD_CallSuccessful(result)) {
		
		if (SDMMD_AMDeviceGetInterfaceType((SDMMD_AMDeviceRef)apple) == kAMDInterfaceConnectionTypeIndirect) {
			AMDeviceStartSession(apple);
		}
		
		apple_value = AMDeviceCopyValue(apple, NULL, CFSTR(kUniqueDeviceID));
		if (apple_value == NULL || CFStringCompare(apple_value, CFSTR("GetProhibited"), 0) == kCFCompareEqualTo) {
			printf("\t\tAMDeviceCopyValue: GetProhibited\n");
			apple_return = kAMDGetProhibitedError;
			CFSafeRelease(apple_value);
		}
		else {
			*value = apple_value;
			apple_return = kAMDSuccess;
		}
		
		if (SDMMD_AMDeviceGetInterfaceType((SDMMD_AMDeviceRef)apple) == kAMDInterfaceConnectionTypeIndirect) {
			AMDeviceStopSession(apple);
		}
		
		AMDeviceDisconnect(apple);
	}
	return apple_return;
}
kern_return_t test_apple_AMDeviceConnect(struct am_device *apple) {
	kern_return_t apple_return = AMDeviceConnect(apple);
	if (apple_return != kAMDSuccess) {
		printf("\t\tAMDeviceConnect: %08x %s\n",apple_return,SDMMD_AMDErrorString(apple_return));
	}
	else {
		AMDeviceDisconnect(apple);
	}
	return apple_return;
}
kern_return_t test_apple_AMDeviceDisconnect(struct am_device *apple) {
	kern_return_t apple_return = kAMDUndefinedError;
	kern_return_t result = AMDeviceConnect(apple);
	if (SDM_MD_CallSuccessful(result)) {
		apple_return = AMDeviceDisconnect(apple);
		if (apple_return != kAMDSuccess) {
			printf("\t\tAMDeviceDisconnect: %08x %s\n",apple_return,SDMMD_AMDErrorString(apple_return));
		}
	}
	return apple_return;
}
kern_return_t test_apple_AMDeviceValidatePairing(struct am_device *apple) {
	kern_return_t apple_return = kAMDUndefinedError;
	kern_return_t result = AMDeviceConnect(apple);
	if (SDM_MD_CallSuccessful(result)) {
		apple_return = AMDeviceValidatePairing(apple);
		if (apple_return != kAMDSuccess) {
			printf("\t\tAMDeviceValidatePairing: %i\n",apple_return);
		}
		AMDeviceDisconnect(apple);
	}
	return apple_return;
}
Ejemplo n.º 6
0
service_conn_t start_afc_service(AMDeviceRef device) {
    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    service_conn_t afcFd;
    assert(AMDeviceStartService(device, AMSVC_AFC, &afcFd, NULL) == 0);

    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);
    return afcFd;
}
Ejemplo n.º 7
0
service_conn_t start_install_proxy_service(AMDeviceRef device) {
    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    service_conn_t installFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.mobile.installation_proxy"), &installFd, NULL) == 0);

    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);

    return installFd;
}
 bool Disconnect()
 {
     bool Result = false;
     // close the session
     int32 rc = AMDeviceStopSession(DeviceHandle);
     if (!rc)
     {
         // disconnect from the device
         rc = AMDeviceDisconnect(DeviceHandle);
         Result = !rc;
     }
     else
     {
         UE_LOG(LogTemp, Display, TEXT("Couldn't stop session"));
     }
     return Result;
 }
Ejemplo n.º 9
0
// Used to send files to app-specific sandbox (Documents dir)
service_conn_t start_house_arrest_service(AMDeviceRef device) {
    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    service_conn_t houseFd;

    CFStringRef cf_bundle_id = CFStringCreateWithCString(NULL, bundle_id, kCFStringEncodingASCII);
    if (AMDeviceStartHouseArrestService(device, cf_bundle_id, 0, &houseFd, 0) != 0)
    {
        PRINT("Unable to find bundle with id: %s\n", bundle_id);
        exit(1);
    }

    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);
    CFRelease(cf_bundle_id);

    return houseFd;
}
Ejemplo n.º 10
0
kern_return_t test_apple_AFCConnectionCreate(struct am_device *apple) {
	kern_return_t apple_return = kAMDUndefinedError;
	kern_return_t result = AMDeviceConnect(apple);
	if (SDM_MD_CallSuccessful(result)) {
		result = AMDeviceStartSession(apple);
		if (SDM_MD_CallSuccessful(result)) {
			service_conn_t test_apple_afc_conn;
			result = AMDeviceStartService(apple, CFSTR(AMSVC_AFC), &test_apple_afc_conn, NULL);
			if (SDM_MD_CallSuccessful(result)) {
				struct afc_connection *afc = NULL;
				result = AFCConnectionOpen(test_apple_afc_conn, 0, &afc);
				if (afc) {
					apple_return = kAMDSuccess;
					AFCConnectionClose(afc);
				}
			}
			AMDeviceStopSession(apple);
		}
		AMDeviceDisconnect(apple);
	}
	return apple_return;
}
kern_return_t test_apple_Sessioned_AMDeviceCopyValue(struct am_device *apple, CFTypeRef *value) {
	kern_return_t apple_return = kAMDUndefinedError;
	CFTypeRef apple_value = NULL;
	kern_return_t result = AMDeviceConnect(apple);
	if (SDM_MD_CallSuccessful(result)) {
		result = AMDeviceStartSession(apple);
		if (SDM_MD_CallSuccessful(result)) {
			apple_value = AMDeviceCopyValue(apple, CFSTR(kInternationalDomain), CFSTR(kLanguage));
			if (apple_value == NULL || CFStringCompare(apple_value, CFSTR("GetProhibited"), 0) == kCFCompareEqualTo) {
				printf("\t\tappleMD_AMDeviceCopyValue (w/ Session): GetProhibited\n");
				apple_return = kAMDGetProhibitedError;
				CFSafeRelease(apple_value);
			}
			else {
				*value = apple_value;
				apple_return = kAMDSuccess;
			}
			AMDeviceStopSession(apple);
		}
		AMDeviceDisconnect(apple);
	}
	return apple_return;
}
Ejemplo n.º 12
0
void handle_device(AMDeviceRef device) {
    if (found_device) return; // handle one device only

    CFStringRef found_device_id = AMDeviceCopyDeviceIdentifier(device);

    if (device_id != NULL) {
        if(strcmp(device_id, CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding())) == 0) {
            found_device = true;
        } else {
            return;
        }
    } else {
        found_device = true;
    }

    CFRetain(device); // don't know if this is necessary?

    printf("[  0%%] Found device (%s), beginning install\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    CFStringRef path = CFStringCreateWithCString(NULL, app_path, kCFStringEncodingASCII);
    CFURLRef relative_url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, false);
    CFURLRef url = CFURLCopyAbsoluteURL(relative_url);

    CFRelease(relative_url);

    service_conn_t afcFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.afc"), &afcFd, NULL) == 0);
    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);
    assert(AMDeviceTransferApplication(afcFd, path, NULL, transfer_callback, NULL) == 0);

    close(afcFd);

    CFStringRef keys[] = { CFSTR("PackageType") };
    CFStringRef values[] = { CFSTR("Developer") };
    CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    service_conn_t installFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.mobile.installation_proxy"), &installFd, NULL) == 0);

    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);

    mach_error_t result = AMDeviceInstallApplication(installFd, path, options, install_callback, NULL);
    if (result != 0)
    {
       printf("AMDeviceInstallApplication failed: %d\n", result);
        exit(1);
    }

    close(installFd);

    CFRelease(path);
    CFRelease(options);

    printf("[100%%] Installed package %s\n", app_path);

    if (!debug) exit(0); // no debug phase

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    printf("------ Debug phase ------\n");

    mount_developer_image(device);      // put debugserver on the device
    start_remote_debug_server(device);  // start debugserver
    write_gdb_prep_cmds(device, url);   // dump the necessary gdb commands into a file

    CFRelease(url);

    printf("[100%%] Connecting to remote debug server\n");
    printf("-------------------------\n");

    signal(SIGHUP, gdb_ready_handler);
    signal(SIGINT, killed);
    signal(SIGTERM, killed);

    pid_t parent = getpid();
    int pid = fork();
    if (pid == 0) {
        CFStringRef path = copy_xcode_path_for(CFSTR("Platforms/iPhoneOS.platform/Developer/usr/libexec/gdb"), CFSTR("gdb-arm-apple-darwin"));
        if (path == NULL) {
            printf("[ !! ] Unable to locate GDB.\n");
            kill(parent, SIGHUP);
            exit(1);
        } else {
            CFStringRef gdb_cmd = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ %@ %s"), path, CFSTR(GDB_SHELL), gdb_args);
 
            // Convert CFStringRef to char* for system call
            const char *char_gdb_cmd = CFStringGetCStringPtr(gdb_cmd, kCFStringEncodingMacRoman);

            system(char_gdb_cmd);      // launch gdb
        }
        kill(parent, SIGHUP);  // "No. I am your father."
        _exit(0);
    }
}
Ejemplo n.º 13
0
void handle_device(AMDeviceRef device) {
    if (found_device) return; // handle one device only

    CFStringRef found_device_id = AMDeviceCopyDeviceIdentifier(device);

    if (device_id != NULL) {
        if(strcmp(device_id, CFStringGetCStringPtr(found_device_id, kCFStringEncodingMacRoman)) == 0) {
            found_device = true;
        } else {
            return;
        }
    } else {
        found_device = true;
    }

    CFRetain(device); // don't know if this is necessary?

    printf("[  0%%] Found device (%s), beginning install\n", CFStringGetCStringPtr(found_device_id, kCFStringEncodingMacRoman));

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    CFStringRef path = CFStringCreateWithCString(NULL, app_path, kCFStringEncodingASCII);
    CFURLRef relative_url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, false);
    CFURLRef url = CFURLCopyAbsoluteURL(relative_url);

    CFRelease(relative_url);

    int afcFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.afc"), &afcFd, NULL) == 0);
    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);
    assert(AMDeviceTransferApplication(afcFd, path, NULL, transfer_callback, NULL) == 0);

    close(afcFd);

    CFStringRef keys[] = { CFSTR("PackageType") };
    CFStringRef values[] = { CFSTR("Developer") };
    CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    int installFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.mobile.installation_proxy"), &installFd, NULL) == 0);

    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);

    mach_error_t result = AMDeviceInstallApplication(installFd, path, options, install_callback, NULL);
    if (result != 0)
    {
       printf("AMDeviceInstallApplication failed: %d\n", result);
       if (result == -402620388) {
        printf("Please check code signing or something else your app.");
       }
        exit(1);
    }

    close(installFd);

    CFRelease(path);
    CFRelease(options);

    printf("[100%%] Installed package %s\n", app_path);

    if (!debug) exit(0); // no debug phase
    AMDeviceConnect(device);

    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    printf("------ Debug phase ------\n");

    mount_developer_image(device);      // put debugserver on the device
    start_remote_debug_server(device);  // start debugserver
    write_gdb_prep_cmds(device, url);   // dump the necessary gdb commands into a file

    CFRelease(url);

    printf("[100%%] Connecting to remote debug server\n");
    printf("-------------------------\n");

    signal(SIGHUP, gdb_ready_handler);

    pid_t parent = getpid();
    int pid = fork();
    if (pid == 0) {
        system(GDB_SHELL);      // launch gdb
        kill(parent, SIGHUP);  // "No. I am your father."
        _exit(0);
    }
}
Ejemplo n.º 14
0
static void DeviceNotificationCallback(am_device_notification_callback_info *info, void *unknown)
{
    struct am_device *device = info->dev;
    switch (info->msg) {
        case ADNCI_MSG_CONNECTED: {
            if (debug) {
                CFStringRef deviceId = AMDeviceCopyDeviceIdentifier(device);
                CFStringRef str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("deviceconsole connected: %@"), deviceId);
                CFRelease(deviceId);
                CFShow(str);
                CFRelease(str);
            }
            if (requiredDeviceId) {
                CFStringRef deviceId = AMDeviceCopyDeviceIdentifier(device);
                Boolean isRequiredDevice = CFEqual(deviceId, requiredDeviceId);
                CFRelease(deviceId);
                if (!isRequiredDevice)
                    break;
            }
            if (AMDeviceConnect(device) == MDERR_OK) {
                if (AMDeviceIsPaired(device) && (AMDeviceValidatePairing(device) == MDERR_OK)) {
                    if (AMDeviceStartSession(device) == MDERR_OK) {
                        service_conn_t connection;
                        if (AMDeviceStartService(device, AMSVC_SYSLOG_RELAY, &connection, NULL) == MDERR_OK) {
                            CFSocketRef socket = CFSocketCreateWithNative(kCFAllocatorDefault, connection, kCFSocketDataCallBack, SocketCallback, NULL);
                            if (socket) {
                                CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
                                if (source) {
                                    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes);
                                    AMDeviceRetain(device);
                                    DeviceConsoleConnection *data = malloc(sizeof *data);
                                    data->connection = connection;
                                    data->socket = socket;
                                    data->source = source;
                                    CFDictionarySetValue(liveConnections, device, data);
                                    return;
                                }
                                CFRelease(source);
                            }
                        }
                        AMDeviceStopSession(device);
                    }
                }
            }
            AMDeviceDisconnect(device);
            break;
        }
        case ADNCI_MSG_DISCONNECTED: {
            if (debug) {
                CFStringRef deviceId = AMDeviceCopyDeviceIdentifier(device);
                CFStringRef str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("deviceconsole disconnected: %@"), deviceId);
                CFRelease(deviceId);
                CFShow(str);
                CFRelease(str);
            }
            DeviceConsoleConnection *data = (DeviceConsoleConnection *)CFDictionaryGetValue(liveConnections, device);
            if (data) {
                CFDictionaryRemoveValue(liveConnections, device);
                AMDeviceRelease(device);
                CFRunLoopRemoveSource(CFRunLoopGetMain(), data->source, kCFRunLoopCommonModes);
                CFRelease(data->source);
                CFRelease(data->socket);
                free(data);
                AMDeviceStopSession(device);
                AMDeviceDisconnect(device);
            }
            break;
        }
        default:
            break;
    }
}
Ejemplo n.º 15
0
void handle_device(AMDeviceRef device) {
    if (found_device) return; // handle one device only

    CFStringRef found_device_id = AMDeviceCopyDeviceIdentifier(device);

    PRINT ("found device id\n");
    if (device_id != NULL) {
        if(strcmp(device_id, CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding())) == 0) {
            found_device = true;
        } else {
            return;
        }
    } else {
        if (operation == OP_LIST_DEVICES) {
            printf ("%s\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));
            CFRetain(device); // don't know if this is necessary?
            return;
        }
        found_device = true;
    }

    CFRetain(device); // don't know if this is necessary?

    PRINT("[  0%%] Found device (%s), beginning install\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    CFStringRef path = CFStringCreateWithCString(NULL, app_path, kCFStringEncodingASCII);
    CFURLRef relative_url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, false);
    CFURLRef url = CFURLCopyAbsoluteURL(relative_url);

    CFRelease(relative_url);

    int afcFd;
	int startServiceAFCRetval = AMDeviceStartService(device, CFSTR("com.apple.afc"), (service_conn_t *) &afcFd, NULL);
	printf("trying to start com.apple.afc : %d\n", startServiceAFCRetval);
	
	if( startServiceAFCRetval )
	{
		sleep(1);
		//printf("trying to start com.apple.afc\n");
		startServiceAFCRetval = AMDeviceStartService(device, CFSTR("com.apple.afc"), (service_conn_t *) &afcFd, NULL);
	}
	printf("trying to start com.apple.afc : %d\n", startServiceAFCRetval);
    assert(startServiceAFCRetval == 0);
    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);

    if (operation == OP_INSTALL) {
        assert(AMDeviceTransferApplication(afcFd, path, NULL, transfer_callback, NULL) == 0);
        close(afcFd);
    }

    CFStringRef keys[] = { CFSTR("PackageType") };
    CFStringRef values[] = { CFSTR("Developer") };
    CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    int installFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.mobile.installation_proxy"), (service_conn_t *) &installFd, NULL) == 0);

    //assert(AMDeviceStopSession(device) == 0);
    //assert(AMDeviceDisconnect(device) == 0);

    if (operation == OP_INSTALL) {
        mach_error_t result = AMDeviceSecureInstallApplication(0, device, url, options, &operation_callback, 0);
        //mach_error_t result = AMDeviceInstallApplication(installFd, path, options, operation_callback, NULL);
        if (result != 0)
        {
			PRINT("AMDeviceInstallApplication failed: %d\n", result);
			exit(EXIT_FAILURE);
        }
    }
	else if (operation == OP_UNINSTALL) {
        mach_error_t result = AMDeviceUninstallApplication (installFd, path, NULL, operation_callback, NULL);
        if (result != 0)
        {
			PRINT("AMDeviceUninstallApplication failed: %d\n", result);
			exit(EXIT_FAILURE);
        }
    }
    
    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);


    close(installFd);

    CFRelease(path);
    CFRelease(options);

    if (operation == OP_INSTALL)
        PRINT("[100%%] Installed package %s\n", app_path);
    else if (operation == OP_UNINSTALL)
        PRINT("[100%%] Uninstalled package %s\n", app_path);


    if (!debug) exit(EXIT_SUCCESS); // no debug phase

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    PRINT("------ Debug phase ------\n");

    mount_developer_image(device);      // put debugserver on the device
    start_remote_debug_server(device);  // start debugserver
    write_gdb_prep_cmds(device, url);   // dump the necessary gdb commands into a file

    CFRelease(url);

    PRINT("[100%%] Connecting to remote debug server\n");
    PRINT("-------------------------\n");

    signal(SIGHUP, gdb_ready_handler);

    pid_t parent = getpid();
    int pid = fork();
    if (pid == 0) {
        system(GDB_SHELL);      // launch gdb
        kill(parent, SIGHUP);  // "No. I am your father."
        _exit(EXIT_SUCCESS);
    }
}
Ejemplo n.º 16
0
Archivo: mux.c Proyecto: dzhshf/ssh-rd
void* THREADPROCATTR wait_for_device(void* arg)
{
	int iphonePort = (int)(intptr_t)arg;
	int ret;
	int handle = -1;
	restore_dev_t restore_dev;
    
	while (1) {
		int new_sock;

		if (s_target_device == NULL) {
			Sleep(100);
			continue;
		}
        
		{
            struct sockaddr_in sockAddrin;
            socklen_t len = sizeof(sockAddrin);
            new_sock = accept(sock, (struct sockaddr*) &sockAddrin , &len);
        }
		
		if (new_sock == -1) {
			fprintf(stderr, "accept() error\n"); fflush(stderr);
			continue;
		}
		
		fprintf(stderr, "Info: New connection...\n"); fflush(stderr);
		
		if (muxConn == 0)
		{
            ret = AMDeviceConnect(s_target_device);
			fprintf(stderr, "AMDeviceConnect() = 0x%x\n", ret); fflush(stderr);
            
            if (ret == ERR_SUCCESS) {
				muxConn = AMDeviceGetConnectionID(s_target_device);
			} else if (ret == -402653144) { // means recovery mode .. I think
				muxconn_t mux_tmp = AMDeviceGetConnectionID(s_target_device);
               fprintf(stderr, "muxConnTmp = %X\n", mux_tmp);
                muxConn = mux_tmp;
//                restore_dev = AMRestoreModeDeviceCreate(0, mux_tmp, 0);
//                fprintf(stderr, "restore_dev = %p\n", restore_dev);
//                if (restore_dev != NULL) {
//                    AMRestoreModeDeviceReboot(restore_dev);
//                    Sleep(5 * 1000);
//                } 
			} else if (ret == -402653083) { // after we call 'reboot', api host is down
                muxconn_t mux_tmp = AMDeviceGetConnectionID(s_target_device);
                fprintf(stderr, "muxConnTmp = %X\n", mux_tmp);
                muxConn = mux_tmp;
            } else {
				fprintf(stderr, "AMDeviceConnect = %i\n", ret);
				goto error_connect;
			}
		}                               
		fprintf(stderr, "Device connected\n"); fflush(stderr);
        
		ret = USBMuxConnectByPort(muxConn, htons(iphonePort), &handle);
		if (ret != ERR_SUCCESS) {
			fprintf(stderr, "USBMuxConnectByPort = %x, handle=%x\n", ret, handle);
			goto error_service;
		}
        
		fprintf(stderr, "USBMuxConnectByPort OK\n");
		{		
			conn_struc* connection1;
			conn_struc* connection2;
			int lpThreadId;
			int lpThreadId2;
			pthread_t thread1;
			pthread_t thread2;

			connection1 = (conn_struc*)malloc(sizeof(conn_struc));
			if (!connection1) {
				fprintf(stderr, "Malloc failed!\n");
				continue;
			}
			connection2 = (conn_struc*)malloc(sizeof(conn_struc));    
			if (!connection2) {
				fprintf(stderr, "Malloc failed!\n");
				continue;
			}
		
			connection1->from_handle = new_sock;
			connection1->to_handle = handle;
			connection2->from_handle = handle;
			connection2->to_handle = new_sock;
		
			fprintf(stderr, "sock handle newsock:%d iphone:%d\n", new_sock, handle);
		
			lpThreadId = pthread_create(&thread1, NULL, conn_forwarding_thread, (void*)connection1);
			lpThreadId2 = pthread_create(&thread2, NULL, conn_forwarding_thread, (void*)connection2);
		
			pthread_detach(thread2);
			pthread_detach(thread1);
        
			Sleep(100);
		}
		fflush(stderr);
		continue;
        
    error_connect:
		fprintf(stderr, "Error: Device Connect\n");
		AMDeviceDisconnect(s_target_device);
		Sleep(1000);
		
		fflush(stderr);
		continue;
		
    error_service:
		fprintf(stderr, "Error: Device Service\n");
		AMDeviceDisconnect(s_target_device);
		Sleep(1000);
		fflush(stderr);
		continue;
		
	}
	return NULL;
}