#!/usr/bin/env python # Copyright (C) 2009 Pavel Pergamenshchik # All rights reserved. # # see http://xzrq.net/umux2007/ from twisted.internet import epollreactor epollreactor.install() from twisted.internet import reactor, stdio, protocol, tcp from twisted.python import log from twisted.protocols.basic import LineOnlyReceiver import os, sys, socket from ctypes import CDLL, Structure from ctypes import c_int, c_char, byref, POINTER log.startLogging(sys.stderr) class CopyProto(LineOnlyReceiver): stopped = False delimiter = '~' def __init__(self, what, peer = None, double_tilde = False): self.what = what self.peer = peer self.double_tilde = double_tilde def lineReceived(self, line): # log.msg('Got line from %s: %r' % (self.what, line)) if not line: return if self.double_tilde: self.peer.transport.write('~' + line + '~') else: self.peer.transport.write(line + '~') def connectionLost(self, reason): log.msg('Disconnected from %s (%s)' % (self.what, reason)) try: reactor.stop() except: pass class usbmuxd_device_info(Structure): _fields_ = [ ('handle', c_int), ('product_id', c_int), ('uuid', c_char * 41), ] def connect_to_usbmux(port): libc = CDLL('libc.so.6') lmux = CDLL('libusbmuxd.so.1') di = POINTER(usbmuxd_device_info)() count = lmux.usbmuxd_get_device_list(byref(di)) if count < 0: log.msg('Failed to get device list') return if count == 0 or not di or not di[0].handle: log.msg('No devices found') return dfd = lmux.usbmuxd_connect(di[0].handle, port) libc.free(di) if dfd < 0: log.msg('Failed to connect to device') return log.msg('usbmux connected (fd %s, pid %s)' % (dfd, os.getpid())) return dfd def connect_to_stdio(fd): skt = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) mux_proto = CopyProto('iphone') stdio_proto = CopyProto('stdio', mux_proto, True) mux_proto.peer = stdio_proto conn = tcp.Connection(skt, mux_proto) conn.connected = 1 conn.startReading() mux_proto.makeConnection(conn) stdio.StandardIO(stdio_proto) reactor.run() if __name__ == '__main__': fd = connect_to_usbmux(2007) connect_to_stdio(fd)