Beispiel #1
0
    def onStart(self, event):
        if self.bbtether != None and self.bbtether.is_running():
            dlg = wx.MessageDialog(self, "The modem is already Connected.",
                                   "Warning!", wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return
        # ask config to use
        pppdconf = bb_prefs.get_def_string(bb_prefs.SECTION_MAIN,
                                           "pppd_config", "")
        # if none picked yet, ask and save in prefs for next time
        if pppdconf == "":
            choices = get_ppp_confs()
            choices.append("--Do not start PPPD--")
            evt = pickEvent(
                caption="PPP config to use (EX: tmobile) see conf/ folder.",
                choices=choices,
                default=pppdconf)
            pppconf = self.onPick(evt)
            print "pppconf:" + str(pppconf)
            if pppconf == None:
                # cancelled
                return
            if pppconf == "--Do not start PPPD--":
                pppconf = ""
            bb_prefs.set(bb_prefs.SECTION_MAIN, "pppd_config", pppconf)
            bb_prefs.save_prefs()

        fake_args = self.build_args_from_prefs()
        bb_messenging.log("Will run bbtether with args: " + str(fake_args))

        (options, args) = bb_tether.parse_cmd(fake_args)
        self.bbtether = BBTetherThread(options, args)
        self.bbtether.start()
Beispiel #2
0
def set_data_mode(device):
    bb_messenging.status("Switching Device to data only mode")
    try:
        buffer= [0,0]
        device.handle.controlMsg(0xc0, 0xa9, buffer, 0 , 1)
    except usb.USBError, error:
        bb_messenging.log("Error setting device to data mode "+str(error)+", continuing anyway.")
	def onStart(self, event):
		if self.bbtether!=None and self.bbtether.is_running():
			dlg = wx.MessageDialog(self, "The modem is already Connected.", "Warning!", wx.OK | wx.ICON_INFORMATION)
			dlg.ShowModal()
			dlg.Destroy()
			return
		# ask config to use
		pppdconf=bb_prefs.get_def_string(bb_prefs.SECTION_MAIN, "pppd_config", "")
		# if none picked yet, ask and save in prefs for next time
		if pppdconf == "":
			choices=get_ppp_confs()
			choices.append("--Do not start PPPD--")
			evt=pickEvent(caption="PPP config to use (EX: tmobile) see conf/ folder.",choices=choices,default=pppdconf)
			pppconf=self.onPick(evt)
			print "pppconf:"+str(pppconf)
			if pppconf==None:
				# cancelled
				return
			if pppconf == "--Do not start PPPD--":
				pppconf=""
			bb_prefs.set(bb_prefs.SECTION_MAIN,"pppd_config",pppconf)
			bb_prefs.save_prefs()

		fake_args=self.build_args_from_prefs()
		bb_messenging.log("Will run bbtether with args: "+str(fake_args))
		
		(options,args)=bb_tether.parse_cmd(fake_args)
		self.bbtether = BBTetherThread(options, args)
		self.bbtether.start()
Beispiel #4
0
def install_kextd():
	bb_messenging.status('Installing custom Kernel Ext. File')
	shutil.copytree(KEXT_FOLDER, "/System/Library/Extensions/libusbshield_rim.kext")
	subprocess.call(['chown', 'root:wheel', "/System/Library/Extensions/libusbshield_rim.kext"])
	subprocess.call(['kextload', '/System/Library/Extensions/libusbshield_rim.kext'])
	restart_kextd()
	bb_messenging.log("Warning: If the device still fails to claim an interface, you should reboot.")
Beispiel #5
0
def set_data_mode(device):
    bb_messenging.status("Switching Device to data only mode")
    try:
        buffer = [0, 0]
        device.handle.controlMsg(0xc0, 0xa9, buffer, 0, 1)
    except usb.USBError, error:
        bb_messenging.log("Error setting device to data mode " + str(error) +
                          ", continuing anyway.")
Beispiel #6
0
def usb_write(device,endpt,bytes,timeout=TIMEOUT,msg="\t-> "):
    bb_util.debug_bytes(bytes,msg)
    try:
        bb_util.debug2(">bulkwrite")
        device.handle.bulkWrite(endpt, bytes, timeout)
        bb_util.debug2("<bulkwrite")
    except usb.USBError, error:
        bb_util.debug2("<bulkwrite(exc)")
        # ! osx returns an empty error (no errorno) so we justcan't check anything :-(
        if str(error) != "No error" and not (bb_osx.is_osx() and error.errno == None):
            bb_messenging.log("error: "+str(error))
            raise
Beispiel #7
0
def read_prefs():
	config = ConfigParser.RawConfigParser()
	if os.path.isfile(PREF_FILE):
		bb_messenging.log("ARchivo de preferencias "+PREF_FILE)
		config.read(PREF_FILE)
	else:
		bb_messenging.log("Creando archivo de conf inicial "+PREF_FILE)
		config.add_section(SECTION_MAIN)
		# do not use save() to prevent recursion
		configfile=open(PREF_FILE, 'wb')
		config.write(configfile)
		configfile.close()
	return config
Beispiel #8
0
def usb_write(device, endpt, bytes, timeout=TIMEOUT, msg="\t-> "):
    bb_util.debug_bytes(bytes, msg)
    try:
        bb_util.debug2(">bulkwrite")
        device.handle.bulkWrite(endpt, bytes, timeout)
        bb_util.debug2("<bulkwrite")
    except usb.USBError, error:
        bb_util.debug2("<bulkwrite(exc)")
        # ! osx returns an empty error (no errorno) so we justcan't check anything :-(
        if str(error) != "No error" and not (bb_osx.is_osx()
                                             and error.errno == None):
            bb_messenging.log("error: " + str(error))
            raise
Beispiel #9
0
def read_prefs():
    config = ConfigParser.RawConfigParser()
    if os.path.isfile(PREF_FILE):
        bb_messenging.log("Reading prefs from " + PREF_FILE)
        config.read(PREF_FILE)
    else:
        bb_messenging.log("Creating initial config file " + PREF_FILE)
        config.add_section(SECTION_MAIN)
        # do not use save() to prevent recursion
        configfile = open(PREF_FILE, 'wb')
        config.write(configfile)
        configfile.close()
    return config
Beispiel #10
0
def read_prefs():
    config = ConfigParser.RawConfigParser()
    if os.path.isfile(PREF_FILE):
        bb_messenging.log("Reading prefs from "+PREF_FILE)
        config.read(PREF_FILE)
    else:
        bb_messenging.log("Creating initial config file "+PREF_FILE)
        config.add_section(SECTION_MAIN)
        # do not use save() to prevent recursion
        configfile=open(PREF_FILE, 'wb')
        config.write(configfile)
        configfile.close()
    return config
Beispiel #11
0
def usb_read(device,endpt,size=BUF_SIZE,timeout=TIMEOUT,msg="\t<- "):
    bytes=[]
    try:
        bb_util.debug2(">bulkread")
        bytes=device.handle.bulkRead(endpt, size, timeout)
        bb_util.debug2("<bulkread")
        bb_util.debug_bytes(bytes,msg)
    except usb.USBError, error:
        bb_util.debug2("<bulkread (exc)")
        # ! osx returns an empty error (no errorno) so we justcan't check anything :-(
        if str(error) != "No error" and not (bb_osx.is_osx() and error.errno == None):
            bb_messenging.log("error: "+str(error))
            raise
Beispiel #12
0
def install_kextd():
    bb_messenging.status('Installing custom Kernel Ext. File')
    shutil.copytree(KEXT_FOLDER,
                    "/System/Library/Extensions/libusbshield_rim.kext")
    subprocess.call([
        'chown', 'root:wheel',
        "/System/Library/Extensions/libusbshield_rim.kext"
    ])
    subprocess.call(
        ['kextload', '/System/Library/Extensions/libusbshield_rim.kext'])
    restart_kextd()
    bb_messenging.log(
        "Warning: If the device still fails to claim an interface, you should reboot."
    )
Beispiel #13
0
def usb_read(device, endpt, size=BUF_SIZE, timeout=TIMEOUT, msg="\t<- "):
    bytes = []
    try:
        bb_util.debug2(">bulkread")
        bytes = device.handle.bulkRead(endpt, size, timeout)
        bb_util.debug2("<bulkread")
        bb_util.debug_bytes(bytes, msg)
    except usb.USBError, error:
        bb_util.debug2("<bulkread (exc)")
        # ! osx returns an empty error (no errorno) so we justcan't check anything :-(
        if str(error) != "No error" and not (bb_osx.is_osx()
                                             and error.errno == None):
            bb_messenging.log("error: " + str(error))
            raise
Beispiel #14
0
def set_bb_power(device):
    '''
    Added try / expect blocks as I had reports of failure(which ?) on storm 9500
    '''
    bb_messenging.status("Increasing USB power - for charging")
    try:
        buffer= [0,0]
        device.handle.controlMsg(0xc0, 0xa5, buffer, 0 , 1)
        buffer = []
        device.handle.controlMsg(0x40, 0xA2, buffer, 0 , 1)
        # reset
        # reset()
        bb_messenging.status("Increased USB power")
    except usb.USBError, error:
        bb_messenging.log("Error increasing power "+str(error)+", continuing anyway.")
Beispiel #15
0
def set_mode(device, command, password=''):
    # TODO: always try ? but only send password if requested ?
    bb_messenging.status("Switching Device to Desktop mode")
    usb_write(device, device.writept, command)
    data=usb_read(device,device.readpt)
    if len(password) > 0:
        bb_messenging.log("Trying to send Desktop mode password.")
        usb_write(device, device.writept, COMMAND_PASS_START_CHLG)
        data=usb_read(device,device.readpt)
        if len(data) <=8 :
            bb_messenging.log("No seed sent by device, probably doesn't need a password.")
        else:
            seed=data[9:]
            digest=bb_modem.digest_password(seed,password)
            print("digest: "+str(digest))
Beispiel #16
0
def set_bb_power(device):
    '''
    Added try / expect blocks as I had reports of failure(which ?) on storm 9500
    '''
    bb_messenging.status("Increasing USB power - for charging")
    try:
        buffer = [0, 0]
        device.handle.controlMsg(0xc0, 0xa5, buffer, 0, 1)
        buffer = []
        device.handle.controlMsg(0x40, 0xA2, buffer, 0, 1)
        # reset
        # reset()
        bb_messenging.status("Increased USB power")
    except usb.USBError, error:
        bb_messenging.log("Error increasing power " + str(error) +
                          ", continuing anyway.")
Beispiel #17
0
def set_mode(device, command, password=''):
    # TODO: always try ? but only send password if requested ?
    bb_messenging.status("Switching Device to Desktop mode")
    usb_write(device, device.writept, command)
    data = usb_read(device, device.readpt)
    if len(password) > 0:
        bb_messenging.log("Trying to send Desktop mode password.")
        usb_write(device, device.writept, COMMAND_PASS_START_CHLG)
        data = usb_read(device, device.readpt)
        if len(data) <= 8:
            bb_messenging.log(
                "No seed sent by device, probably doesn't need a password.")
        else:
            seed = data[9:]
            digest = bb_modem.digest_password(seed, password)
            print("digest: " + str(digest))
	def run (self):
		bb_messenging.status("Starting Network Stats thread")
		modem=self.frame.bbtether.bbtether.modem;
		lastIn=0
		lastOut=0
		maxIn=0
		maxOut=0
		while(True):
			time.sleep(1)
			if modem==None or self.done:
				self.done=True
				break;
			try:
				totalDown=modem.red
				totalUp=modem.writ
				newIn=totalUp-lastIn
				newOut=totalDown-lastOut
				lastIn=totalUp
				lastOut=totalDown
				elapsed=time.time()-self.start_time
				if newIn > maxIn:
					maxIn=newIn
				if newOut > maxOut:
					maxOut=newOut
				evt = networkStatsEvent(
				#TODO: hours
					elapsed=elapsed,
					speedUp=newIn*8/1024,
					speedDown=newOut*8/1024,
					avgUp=totalUp*8/1024/elapsed,
					avgDown=totalDown*8/1024/elapsed,
					maxDown=maxOut*8/1024,
					maxUp=maxIn*8/1024,
					totalUp=totalUp/1024,
					totalDown=totalDown/1024
				)
				wx.PostEvent(self.frame, evt)
			except:
				raise
				bb_messenging.log("Network stats thread error.")
				self.done=True
		bb_messenging.log("Network stats thread completed.")
Beispiel #19
0
 def run(self):
     bb_messenging.status("Starting Network Stats thread")
     modem = self.frame.bbtether.bbtether.modem
     lastIn = 0
     lastOut = 0
     maxIn = 0
     maxOut = 0
     while (True):
         time.sleep(1)
         if modem == None or self.done:
             self.done = True
             break
         try:
             totalDown = modem.red
             totalUp = modem.writ
             newIn = totalUp - lastIn
             newOut = totalDown - lastOut
             lastIn = totalUp
             lastOut = totalDown
             elapsed = time.time() - self.start_time
             if newIn > maxIn:
                 maxIn = newIn
             if newOut > maxOut:
                 maxOut = newOut
             evt = networkStatsEvent(
                 #TODO: hours
                 elapsed=elapsed,
                 speedUp=newIn * 8 / 1024,
                 speedDown=newOut * 8 / 1024,
                 avgUp=totalUp * 8 / 1024 / elapsed,
                 avgDown=totalDown * 8 / 1024 / elapsed,
                 maxDown=maxOut * 8 / 1024,
                 maxUp=maxIn * 8 / 1024,
                 totalUp=totalUp / 1024,
                 totalDown=totalDown / 1024)
             wx.PostEvent(self.frame, evt)
         except:
             raise
             bb_messenging.log("Network stats thread error.")
             self.done = True
     bb_messenging.log("Network stats thread completed.")
Beispiel #20
0
def find_berry(userdev=None, userbus=None, verbose=True):
    '''
        Look on Bus for a RIM device
        (1 max for now)
        userdev,userbus : potential user provided device/bus to force-use
    '''
    device = None
    mybus = None

    bb_messenging.status("Looking for USB devices:")
    berry = None
    if userdev and userbus:
        if verbose:
            bb_messenging.log("Will use user provided bus/device: " + userbus +
                              "/" + userdev)
        for bus in usb.busses():
            if string.atoi(bus.dirname) == string.atoi(userbus):
                for dev in bus.devices:
                    if string.atoi(dev.filename) == string.atoi(userdev):
                        berry = dev
                        mybus = bus
    else:
        for bus in usb.busses():
            for dev in bus.devices:
                if (verbose):
                    bb_messenging.log("    Bus %s Device %s: ID %04x:%04x" %
                                      (bus.dirname, dev.filename, dev.idVendor,
                                       dev.idProduct))
                if (dev.idVendor == VENDOR_RIM):
                    berry = dev
                    mybus = bus

    if berry != None:
        device = bb_data.Device()
        device.usbdev = berry
        device.bus = mybus

    if verbose:
        bb_messenging.log("USB Device lookup finished")

    return device
Beispiel #21
0
def find_berry(userdev=None, userbus=None, verbose=True):
    '''
        Look on Bus for a RIM device
        (1 max for now)
        userdev,userbus : potential user provided device/bus to force-use
    '''
    device=None
    mybus=None

    bb_messenging.status("Looking for USB devices:")
    berry=None
    if userdev and userbus:
        if verbose :
            bb_messenging.log("Will use user provided bus/device: "+userbus+"/"+userdev)
        for bus in usb.busses():
            if string.atoi(bus.dirname) == string.atoi(userbus):
                for dev in bus.devices:
                    if string.atoi(dev.filename) == string.atoi(userdev):
                        berry=dev
                        mybus=bus
    else:
        for bus in usb.busses():
            for dev in bus.devices:
                if(verbose):
                    bb_messenging.log("    Bus %s Device %s: ID %04x:%04x" % (bus.dirname,dev.filename,dev.idVendor,dev.idProduct))
                if(dev.idVendor==VENDOR_RIM):
                    berry=dev
                    mybus=bus

    if berry != None:
        device=bb_data.Device()
        device.usbdev=berry
        device.bus=mybus

    if verbose :
        bb_messenging.log("USB Device lookup finished")

    return device
Beispiel #22
0
def read_bb_endpoints(device, userInterface):
    '''
    Read the device endpoints and stores them in the device data structure
    device was created from find_berry
    and device.open_handle should have been called already
    Once we found endpoints, we save them as some devices (esp. Bold) don't like being probed.
    '''

    #look for previously saved endpoints
    config = bb_prefs.get_prefs()
    if config.has_section(SECTION_SCANNED_EP):
        device.interface = bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,
                                                'interface', -1)
        device.readpt = bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,
                                             'readpt', -1)
        device.writept = bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,
                                              'writept', -1)
        device.modem_readpt = bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,
                                                   'modem_readpt', -1)
        device.modem_writept = bb_prefs.get_def_int(
            bb_prefs.SECTION_SCANNED_EP, 'modem_writept', -1)
        bb_messenging.log("Using saved EP data: " + str(device.interface) +
                          ", " + str(device.readpt) + ", " +
                          str(device.writept) + ", " +
                          str(device.modem_readpt) + ", " +
                          str(device.modem_writept))
        # return saved data if good (earlier version saved bad ones)
        if device.readpt != -1 and device.writept != -1:
            return device
        else:
            print "Invalid saved endpoints, will rescan."

    readpt = -1
    writept = -1
    modem_readpt = -1
    modem_writept = -1
    next_readpt = -1
    next_writept = -1
    # List device Infos for information and find USB endpair
    handle = device.handle
    berry = device.usbdev
    config = berry.configurations[0]
    type = ""
    if (berry.idProduct == PRODUCT_DATA):
        type = "Data Mode"
    if (berry.idProduct == PRODUCT_NEW_DUAL):
        type = "Dual Mode"
    if (berry.idProduct == PRODUCT_NEW_8120):
        type = "8120"
    if (berry.idProduct == PRODUCT_NEW_MASS_ONLY):
        type = "Storage Mode"

    bb_messenging.log("\nFound RIM device (" + type + ")")
    bb_messenging.log("    Manufacturer:" +
                      handle.getString(berry.iManufacturer, 100))
    bb_messenging.log("    Product:" + handle.getString(berry.iProduct, 100))
    #print "    Serial:",handle.getString(berry.iSerialNumber,100)
    bb_messenging.log("    Device:" + berry.filename)
    bb_messenging.log("    VendorId: %04x" % berry.idVendor)
    bb_messenging.log("    ProductId: %04x" % berry.idProduct)
    bb_messenging.log("    Version:" + berry.deviceVersion)
    bb_messenging.log("    Class:" + str(berry.deviceClass) + " " +
                      str(berry.deviceSubClass))
    bb_messenging.log("    Protocol:" + str(berry.deviceProtocol))
    bb_messenging.log("    Max packet size:" + str(berry.maxPacketSize))
    bb_messenging.log("    Self Powered:" + str(config.selfPowered))
    bb_messenging.log("    Max Power:" + str(config.maxPower))
    for inter in config.interfaces:
        if len(inter) == 0:
            bb_messenging.log("Skipping Interface -> empty array !")
            continue
        bb_messenging.log("\n    *Interface:" + str(inter[0].interfaceNumber))
        if userInterface != None and int(
                userInterface) != inter[0].interfaceNumber:
            bb_messenging.log("Skipping interface (-i flag used)")
            continue
        if readpt != -1:
            bb_messenging.log(
                "Skipping interface (valid endpoints already found), use -i flag to force"
            )
            continue
        try:
            try:
                handle.claimInterface(inter[0].interfaceNumber)
            except usb.USBError, error:
                bb_messenging.log("Failed to claim interface: " + str(error) +
                                  "\nMust be in use.")
                if not bb_osx.is_osx():
                    #Only implemented on libusb Linux !
                    #For mac we need the kext stuff.
                    bb_messenging.log("Will try to release it.")
                    detach_kernel_driver(device, inter[0].interfaceNumber)
                    try:
                        handle.claimInterface(inter[0].interfaceNumber)
                        bb_messenging.log("Interface is now claimed !")
                    except usb.USBError, error:
                        bb_messenging.log(
                            "Still could not claim the interface: " +
                            str(error))

            bb_messenging.log("        Interface class:" +
                              str(inter[0].interfaceClass) + "/" +
                              str(inter[0].interfaceSubClass))
            bb_messenging.log("        Interface protocol:" +
                              str(inter[0].interfaceProtocol))
            for att in inter:
                i = 0
                # check endpoint pairs
                while i < len(att.endpoints):
                    isDataPair = False
                    red = att.endpoints[i].address
                    writ = att.endpoints[i + 1].address
                    i += 2
                    bb_messenging.log("        EndPoint Pair:" + hex(red) +
                                      "/" + hex(writ))
                    try:
                        usb_write(device, writ, COMMAND_HELLO)
                        try:
                            bytes = usb_read(device, red)
                            if len(bytes) == 0:
                                raise usb.USBError
                            # on some devices, the modem replies to hello with (others, read fails):
                            # [0x7 0x0 0x0 0x0 0xc 0x0 0x0 0x0 0x78 0x56 0x34 0x12 ] [........xV4.]
                            if bb_util.is_same_tuple(bytes, MODEM_HELLO_REPLY):
                                if modem_readpt == -1:
                                    modem_readpt = red
                                    modem_writept = writ
                                    bb_messenging.log(
                                        "            Found Modem endpoints: " +
                                        hex(red) + "/" + hex(writ))

                            else:
                                if readpt == -1:
                                    # Use first valid data point found
                                    device.interface = inter[0].interfaceNumber
                                    bb_util.debug("Setting interface to: " +
                                                  str(device.interface))
                                    readpt = red
                                    writept = writ
                                    isDataPair = True
                                    bb_messenging.log(
                                        "            Found Data endpoints: " +
                                        hex(red) + "/" + hex(writ))
                        except usb.USBError:
                            bb_messenging.log(
                                "            Not Data Pair (Read failed)")
                    except usb.USBError:
                        bb_messenging.log(
                            "            Not Data Pair (Write failed)")

                    if (isDataPair
                            == False) and readpt != -1 and next_readpt == -1:
                        next_readpt = red
                        next_writept = writ
                        bb_messenging.log("            Next endpoints:" +
                                          hex(red) + "/" + hex(writ))

            handle.releaseInterface()
Beispiel #23
0
def debug_object_attr(obj):
    attributes = dir(obj)
    for a in attributes:
        bb_messenging.log(a)
Beispiel #24
0
                            bb_messenging.log(
                                "            Not Data Pair (Read failed)")
                    except usb.USBError:
                        bb_messenging.log(
                            "            Not Data Pair (Write failed)")

                    if (isDataPair
                            == False) and readpt != -1 and next_readpt == -1:
                        next_readpt = red
                        next_writept = writ
                        bb_messenging.log("            Next endpoints:" +
                                          hex(red) + "/" + hex(writ))

            handle.releaseInterface()
        except usb.USBError:
            bb_messenging.log("Error while scanning interface: " +
                              str(inter[0].interfaceNumber) + " -> skipping")
            traceback.print_exc(file=sys.stdout)

    # if no specific modem port found, try the one after the data one
    if modem_readpt == -1:
        modem_readpt = next_readpt
        modem_writept = next_writept
        bb_messenging.log("Defaulted Modem endpoints: " + hex(modem_readpt) +
                          "/" + hex(modem_writept))

    device.readpt = readpt
    device.writept = writept
    device.modem_readpt = modem_readpt
    device.modem_writept = modem_writept

    #save scan results to file (only if found)
Beispiel #25
0
	def start(self, options, args):
		


		bb_messenging.verbose = options.verbose
		bb_messenging.veryVerbose = options.veryverbose
		if(options.rescan):
			prefs=bb_prefs.get_prefs()
			prefs.remove_section(bb_prefs.SECTION_SCANNED_EP)
			

		pppConfig = None
		if len(args) > 0:
			pppConfig = args[0]

		# Need to be root (unless udev or OSX)
		#if os.getuid() != 0:
		#	bb_messenging.log("\n!!!!!!!!!!!!!!!!!!!!!\nThis might will only work as root!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")

		bb_util.remove_berry_charge()
		bb_osx.prepare_osx()

		berry = None
		
		berry = bb_usb.find_berry(options.device, options.bus)

		if berry != None:
			# open the connection
			if berry.handle==None:
				berry.open_handle()

			#bb_usbfs.find_kernel_driver(berry)

			# lookup endpoints
			# IMPORTANT: We need to do this BEFORE RESET, otherwise modem will be screwed
			# folowing "test" hello packet (fail on Pearl, ok on storm)
			# all right on the Bold the hello packet also causes problem, but reset won't fix it :-(
			if not (options.drp and options.dwp and options.mrp and options.mwp):
				berry.read_endpoints(options.interface)

			if options.listonly:
				bb_messenging.warn(["Fin."])
				bb_osx.terminate_osx()
				os._exit(0)

			bb_util.remove_berry_charge()

			# set power & reset (only if '-c' requested)
			# Only needed with BB os < 4.5 ?
			if options.charge:
				bb_usb.set_bb_power(berry)
				bb_messenging.status("Waiting few seconds, for mode to change")
				time.sleep(1.5)

			# set to datamode (ony if requested)
			if options.dmode:
				bb_usb.set_data_mode(berry)

			#if options.password != None and len(options.password) > 0:
			#	bb_usb.set_desktop_mode(berry,options.password)

			# overwrite found endpoints with user endpoints if specified
			if options.drp:
				berry.readpt = int(options.drp, 16)
			if options.dwp:
				berry.writept = int(options.dwp, 16)
			if options.mrp:
				berry.modem_readpt = int(options.mrp, 16)
			if options.mwp:
				berry.modem_writept = int(options.mwp, 16)
			if options.interface:
				berry.interface = int(options.interface)

			if berry.readpt == -1:
				bb_messenging.warn(["\nNo good Data Endpoint pair, bailing out !"])
			else:
				bb_messenging.log("\nUsing Data Endpoint Pair:"+ hex(berry.readpt)+ "/"+ hex(berry.writept))
				bb_messenging.log("Using Modem pair: "+ hex(berry.modem_readpt)+ "/"+ hex(berry.modem_writept)+ "\n")
				
				bb_messenging.log("Atachando la interface "+str(berry.interface))
				berry.claim_interface()

				berry.read_infos()
				bb_messenging.log("Pin: "+ hex(berry.pin))
				bb_messenging.log("Description: "+ berry.desc)

				# Modem use does not require to be in desktop mode, so don't do it.
				self.modem = bb_modem.BBModem(berry)
				
				if options.password:
					self.modem.set_password(options.password)
				
				pppdCommand = "/usr/sbin/pppd";
				if options.pppd:
					pppdCommand = options.pppd

				# El desktop manager de windows hace esto, pero parce que es innecesario ya que igual funciona
				# asi que no lo voy a incluir en el paquete de datos
				#bb_usb.usb_write(berry, berry.writept, bb_modem.MODEM_BYPASS_PCKT)
				#bb_usb.usb_read(berry, berry.readpt)
				#bb_usb.usb_write(berry, berry.writept, [0,0,0x8,0,0xa,0x6,0,0xa])
				#bb_usb.usb_read(berry, berry.readpt)
				#bb_usb.usb_write(berry, berry.writept, [0x6,0,0xa,0,0x40,0,0,0x1,0,0])
				#bb_usb.usb_read(berry, berry.readpt)
				#bb_usb.usb_write(berry, berry.writept,[0x6,0,0x16,0,0x40,0x1,0x1,0x2,0,0,0,0xa,0x49,0,0,0,0,0x49,0,0,0,0x1])
				#bb_usb.usb_read(berry, berry.readpt)
				
				# This will run forever (until ^C)
				try:
					self.modem.start(pppConfig, pppdCommand)
				except KeyboardInterrupt:
					bb_messenging.log("KBD interrupt")
					# sometimes the KInterrupt will propagate here(if ^C before modem read thread started)
					# we don't want to crash and hang.
					if self.modem!=None:
						self.modem.do_shutdown()

				bb_messenging.status("MSG:Liberando la interfaz")
				berry.release_interface()
				bb_osx.terminate_osx()
				bb_messenging.status("END:LinBerryModem Finalizado")
				#os._exit(0)
		else:
			bb_messenging.warn(["\nERR:No hay BlackBerry Conectado!"])
Beispiel #26
0
def debug_object_attr(obj):
	attributes = dir(obj)
	for a in attributes:
		bb_messenging.log(a)
Beispiel #27
0
    def start(self, options, args):
        bb_messenging.verbose = options.verbose
        bb_messenging.veryVerbose = options.veryverbose
        if (options.rescan):
            prefs = bb_prefs.get_prefs()
            prefs.remove_section(bb_prefs.SECTION_SCANNED_EP)

        pppConfig = None
        if len(args) > 0:
            pppConfig = args[0]

        # Need to be root (unless udev or OSX)
        if os.getuid() != 0:
            bb_messenging.log(
                "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nThis might will only work as root!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
            )

        bb_util.remove_berry_charge()
        bb_osx.prepare_osx()

        berry = None

        berry = bb_usb.find_berry(options.device, options.bus)

        if berry != None:
            # open the connection
            if berry.handle == None:
                berry.open_handle()

            #bb_usbfs.find_kernel_driver(berry)

            # lookup endpoints
            # IMPORTANT: We need to do this BEFORE RESET, otherwise modem will be screwed
            # folowing "test" hello packet (fail on Pearl, ok on storm)
            # all right on the Bold the hello packet also causes problem, but reset won't fix it :-(
            if not (options.drp and options.dwp and options.mrp
                    and options.mwp):
                berry.read_endpoints(options.interface)

            if options.listonly:
                bb_messenging.warn(["Listing only requested, stopping here."])
                bb_osx.terminate_osx()
                os._exit(0)

            bb_util.remove_berry_charge()

            # set power & reset (only if '-c' requested)
            # Only needed with BB os < 4.5 ?
            if options.charge:
                bb_usb.set_bb_power(berry)
                bb_messenging.status("Waiting few seconds, for mode to change")
                time.sleep(1.5)

            # set to datamode (ony if requested)
            if options.dmode:
                bb_usb.set_data_mode(berry)

            #if options.password != None and len(options.password) > 0:
            #    bb_usb.set_desktop_mode(berry,options.password)

            # overwrite found endpoints with user endpoints if specified
            if options.drp:
                berry.readpt = int(options.drp, 16)
            if options.dwp:
                berry.writept = int(options.dwp, 16)
            if options.mrp:
                berry.modem_readpt = int(options.mrp, 16)
            if options.mwp:
                berry.modem_writept = int(options.mwp, 16)
            if options.interface:
                berry.interface = int(options.interface)

            if berry.readpt == -1:
                bb_messenging.warn(
                    ["\nNo good Data Endpoint pair, bailing out !"])
            else:
                bb_messenging.log("\nUsing Data Endpoint Pair:" +
                                  hex(berry.readpt) + "/" + hex(berry.writept))
                bb_messenging.log("Using Modem pair: " +
                                  hex(berry.modem_readpt) + "/" +
                                  hex(berry.modem_writept) + "\n")

                bb_messenging.log("Claiming interface " + str(berry.interface))
                berry.claim_interface()

                berry.read_infos()
                bb_messenging.log("Pin: " + hex(berry.pin))
                bb_messenging.log("Description: " + berry.desc)

                # Modem use does not require to be in desktop mode, so don't do it.
                self.modem = bb_modem.BBModem(berry)

                if options.password:
                    self.modem.set_password(options.password)

                pppdCommand = "/usr/sbin/pppd"
                if options.pppd:
                    pppdCommand = options.pppd

                # Windows does this, however it does not seem to be required (seem to crash usb at times too)
                #bb_usb.usb_write(berry, berry.writept, bb_modem.MODEM_BYPASS_PCKT)
                #bb_usb.usb_read(berry, berry.readpt)
                #bb_usb.usb_write(berry, berry.writept, [0,0,0x8,0,0xa,0x6,0,0xa])
                #bb_usb.usb_read(berry, berry.readpt)
                #bb_usb.usb_write(berry, berry.writept, [0x6,0,0xa,0,0x40,0,0,0x1,0,0])
                #bb_usb.usb_read(berry, berry.readpt)
                #bb_usb.usb_write(berry, berry.writept, [0x6,0,0x16,0,0x40,0x1,0x1,0x2,0,0,0,0xa,0x49,0,0,0,0,0x49,0,0,0,0x1])
                #bb_usb.usb_read(berry, berry.readpt)

                # This will run forever (until ^C)
                try:
                    self.modem.start(pppConfig, pppdCommand)
                except KeyboardInterrupt:
                    bb_messenging.log("KBD interrupt")
                    # sometimes the KInterrupt will propagate here(if ^C before modem read thread started)
                    # we don't want to crash and hang.
                    if self.modem != None:
                        self.modem.do_shutdown()

                bb_messenging.status("Releasing interface")
                berry.release_interface()
                bb_osx.terminate_osx()
                bb_messenging.status("bbtether completed.")
                #os._exit(0)
        else:
            bb_messenging.warn(["\nNo RIM device found"])
Beispiel #28
0
	def __init__(self):
		bb_messenging.log("")
Beispiel #29
0
	def __init__(self):
		bb_messenging.log("--------------------------------")
		bb_messenging.log("BBTether " + VERSION)
		bb_messenging.log("Israel Marrero - 2009")
		bb_messenging.log("Israel Marrero")
		bb_messenging.log("Use '-h' flag for more informations : 'python bbtether.py -h'.")
		bb_messenging.log("--------------------------------\n")
Beispiel #30
0
 def run(self):
     bb_messenging.status("Starting Modem thread")
     # runs "forever"
     self.bbtether = bb_tether.BBTether()
     self.bbtether.start(self.options, self.args)
     bb_messenging.log("BBTether Thread completed.")
Beispiel #31
0
                                    writept=writ
                                    isDataPair=True
                                    bb_messenging.log("            Found Data endpoints: "+hex(red)+"/"+hex(writ))
                        except usb.USBError:
                            bb_messenging.log("            Not Data Pair (Read failed)")
                    except usb.USBError:
                        bb_messenging.log("            Not Data Pair (Write failed)")

                    if (isDataPair==False) and readpt != -1 and next_readpt == -1:
                        next_readpt=red
                        next_writept=writ
                        bb_messenging.log("            Next endpoints:"+hex(red)+"/"+hex(writ))

            handle.releaseInterface()
        except usb.USBError:
            bb_messenging.log("Error while scanning interface: "+str(inter[0].interfaceNumber)+" -> skipping")
            traceback.print_exc(file=sys.stdout)

    # if no specific modem port found, try the one after the data one
    if modem_readpt==-1:
        modem_readpt=next_readpt
        modem_writept=next_writept
        bb_messenging.log("Defaulted Modem endpoints: "+hex(modem_readpt)+"/"+hex(modem_writept))

    device.readpt=readpt
    device.writept=writept
    device.modem_readpt=modem_readpt
    device.modem_writept=modem_writept

    #save scan results to file (only if found)
    if writept!=-1:
Beispiel #32
0
    def start(self, options, args):
        bb_messenging.verbose = True
        # Need to be root (unless udev or OSX)
        if os.getuid() != 0:
            bb_messenging.log(
                "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nThis might will only work as root!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
            )

        bb_util.remove_berry_charge()
        bb_osx.prepare_osx()
        berry = None
        berry = bb_usb.find_berry(None, None)

        if berry != None:
            # open the connection
            if berry.handle == None:
                berry.open_handle()

            berry.read_endpoints(None)

            bb_util.remove_berry_charge()

            if berry.readpt == -1:
                bb_messenging.warn(
                    ["\nNo good Data Endpoint pair, bailing out !"])
            else:
                bb_messenging.log("\nUsing Data Endpoint Pair:" +
                                  hex(berry.readpt) + "/" + hex(berry.writept))
                bb_messenging.log("Using Modem pair: " +
                                  hex(berry.modem_readpt) + "/" +
                                  hex(berry.modem_writept) + "\n")

                bb_messenging.log("Claiming interface " + str(berry.interface))
                berry.claim_interface()

                berry.read_infos()
                bb_messenging.log("Pin: " + hex(berry.pin))
                bb_messenging.log("Description: " + berry.desc)

                bb_usb.set_mode(berry, bb_usb.COMMAND_MODE_DESKTOP)
                bb_usb.usb_read(berry, berry.readpt)
                bb_usb.usb_write(berry, berry.writept,
                                 [00, 00, 0x7, 00, 0xa, 04, 00])
                bb_usb.usb_read(berry, berry.readpt)
                bb_usb.usb_write(
                    berry, berry.writept,
                    [04, 00, 0xc, 00, 0x40, 00, 00, 00, 0x25, 0x80, 0x8, 00])
                bb_usb.usb_read(berry, berry.readpt)
                time.sleep(2)
                bb_usb.usb_read(berry, berry.readpt)

        else:
            bb_messenging.warn(["\nNo RIM device found"])
Beispiel #33
0
 def __init__(self):
     bb_messenging.log("--------------------------------")
     bb_messenging.log("BBTether " + VERSION)
     bb_messenging.log("Thibaut Colar - 2009")
     bb_messenging.log("More infos: http://wiki.colar.net/bbtether")
     bb_messenging.log("Use '-h' flag for more informations : 'python bbtether.py -h'.")
     bb_messenging.log("--------------------------------\n")
Beispiel #34
0
	def start(self, options, args):
		bb_messenging.verbose = True
		# Need to be root (unless udev or OSX)
		if os.getuid() != 0:
			bb_messenging.log("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nThis might will only work as root!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")

		bb_util.remove_berry_charge()
		bb_osx.prepare_osx()
		berry = None
		berry = bb_usb.find_berry(None,None)

		if berry != None:
			# open the connection
			if berry.handle==None:
				berry.open_handle()

			berry.read_endpoints(None)

			bb_util.remove_berry_charge()

			if berry.readpt == -1:
				bb_messenging.warn(["\nNo good Data Endpoint pair, bailing out !"])
			else:
				bb_messenging.log("\nUsing Data Endpoint Pair:"+ hex(berry.readpt)+ "/"+ hex(berry.writept))
				bb_messenging.log("Using Modem pair: "+ hex(berry.modem_readpt)+ "/"+ hex(berry.modem_writept)+ "\n")
				
				bb_messenging.log("Claiming interface "+str(berry.interface))
				berry.claim_interface()

				berry.read_infos()
				bb_messenging.log("Pin: "+ hex(berry.pin))
				bb_messenging.log("Description: "+ berry.desc)

				bb_usb.set_mode(berry,bb_usb.COMMAND_MODE_DESKTOP)
				bb_usb.usb_read(berry,berry.readpt)
				bb_usb.usb_write(berry,berry.writept,[00,00,0x7,00,0xa,04,00])
				bb_usb.usb_read(berry,berry.readpt)
				bb_usb.usb_write(berry,berry.writept,[04,00,0xc,00,0x40,00,00,00,0x25,0x80,0x8,00])
				bb_usb.usb_read(berry,berry.readpt)
				time.sleep(2)
				bb_usb.usb_read(berry,berry.readpt)

		else:
			bb_messenging.warn(["\nNo RIM device found"])
Beispiel #35
0
def read_bb_endpoints(device, userInterface):
    '''
    Read the device endpoints and stores them in the device data structure
    device was created from find_berry
    and device.open_handle should have been called already
    Once we found endpoints, we save them as some devices (esp. Bold) don't like being probed.
    '''

    #look for previously saved endpoints
    config=bb_prefs.get_prefs()
    if config.has_section(SECTION_SCANNED_EP):
        device.interface=bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,'interface',-1)
        device.readpt=bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,'readpt',-1)
        device.writept=bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,'writept',-1)
        device.modem_readpt=bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,'modem_readpt',-1)
        device.modem_writept=bb_prefs.get_def_int(bb_prefs.SECTION_SCANNED_EP,'modem_writept',-1)
        bb_messenging.log("Using saved EP data: "+str(device.interface)+", "+str(device.readpt)+", "+str(device.writept)+", "+str(device.modem_readpt)+", "+str(device.modem_writept))
        # return saved data if good (earlier version saved bad ones)
        if device.readpt != -1 and device.writept !=-1:
            return device
        else:
            print "Invalid saved endpoints, will rescan."

    readpt=-1
    writept=-1
    modem_readpt=-1
    modem_writept=-1
    next_readpt=-1
    next_writept=-1
    # List device Infos for information and find USB endpair
    handle=device.handle
    berry=device.usbdev
    config=berry.configurations[0]
    type=""
    if(berry.idProduct == PRODUCT_DATA):
        type="Data Mode"
    if(berry.idProduct == PRODUCT_NEW_DUAL):
        type="Dual Mode"
    if(berry.idProduct == PRODUCT_NEW_8120):
        type="8120"
    if(berry.idProduct == PRODUCT_NEW_MASS_ONLY):
        type="Storage Mode"

    bb_messenging.log("\nFound RIM device ("+type+")")
    bb_messenging.log("    Manufacturer:"+handle.getString(berry.iManufacturer,100))
    bb_messenging.log("    Product:"+handle.getString(berry.iProduct,100))
    #print "    Serial:",handle.getString(berry.iSerialNumber,100)
    bb_messenging.log("    Device:"+berry.filename)
    bb_messenging.log("    VendorId: %04x" % berry.idVendor)
    bb_messenging.log("    ProductId: %04x" % berry.idProduct)
    bb_messenging.log("    Version:"+berry.deviceVersion)
    bb_messenging.log("    Class:"+str(berry.deviceClass)+" "+str(berry.deviceSubClass))
    bb_messenging.log("    Protocol:"+str(berry.deviceProtocol))
    bb_messenging.log("    Max packet size:"+str(berry.maxPacketSize))
    bb_messenging.log("    Self Powered:"+str(config.selfPowered))
    bb_messenging.log("    Max Power:"+str(config.maxPower))
    for inter in config.interfaces:
        if len(inter) == 0:
            bb_messenging.log("Skipping Interface -> empty array !")
            continue
        bb_messenging.log("\n    *Interface:"+str(inter[0].interfaceNumber))
        if userInterface!=None and int(userInterface)!=inter[0].interfaceNumber:
            bb_messenging.log("Skipping interface (-i flag used)")
            continue
        if readpt != -1:
            bb_messenging.log("Skipping interface (valid endpoints already found), use -i flag to force")
            continue
        try:
            try:
                handle.claimInterface(inter[0].interfaceNumber)
            except usb.USBError, error:
                bb_messenging.log("Failed to claim interface: "+str(error)+"\nMust be in use.")
                if not bb_osx.is_osx():
                    #Only implemented on libusb Linux !
                    #For mac we need the kext stuff.
                    bb_messenging.log("Will try to release it.")
                    detach_kernel_driver(device,inter[0].interfaceNumber)
                    try:
                        handle.claimInterface(inter[0].interfaceNumber)
                        bb_messenging.log("Interface is now claimed !")
                    except usb.USBError, error:
                        bb_messenging.log("Still could not claim the interface: "+str(error))

            bb_messenging.log("        Interface class:"+str(inter[0].interfaceClass)+"/"+str(inter[0].interfaceSubClass))
            bb_messenging.log("        Interface protocol:"+str(inter[0].interfaceProtocol))
            for att in inter:
                i=0
                # check endpoint pairs
                while i < len(att.endpoints):
                    isDataPair=False
                    red=att.endpoints[i].address
                    writ=att.endpoints[i+1].address
                    i+=2
                    bb_messenging.log("        EndPoint Pair:"+hex(red)+"/"+hex(writ))
                    try:
                        usb_write(device,writ,COMMAND_HELLO)
                        try:
                            bytes=usb_read(device,red)
                            if len(bytes) == 0:
                                raise usb.USBError
                            # on some devices, the modem replies to hello with (others, read fails):
                            # [0x7 0x0 0x0 0x0 0xc 0x0 0x0 0x0 0x78 0x56 0x34 0x12 ] [........xV4.]
                            if bb_util.is_same_tuple(bytes, MODEM_HELLO_REPLY):
                                if modem_readpt==-1:
                                    modem_readpt=red
                                    modem_writept=writ
                                    bb_messenging.log("            Found Modem endpoints: "+hex(red)+"/"+hex(writ))

                            else:
                                if readpt == -1 :
                                    # Use first valid data point found
                                    device.interface=inter[0].interfaceNumber
                                    bb_util.debug("Setting interface to: "+str(device.interface))
                                    readpt=red
                                    writept=writ
                                    isDataPair=True
                                    bb_messenging.log("            Found Data endpoints: "+hex(red)+"/"+hex(writ))
                        except usb.USBError:
                            bb_messenging.log("            Not Data Pair (Read failed)")
                    except usb.USBError:
                        bb_messenging.log("            Not Data Pair (Write failed)")

                    if (isDataPair==False) and readpt != -1 and next_readpt == -1:
                        next_readpt=red
                        next_writept=writ
                        bb_messenging.log("            Next endpoints:"+hex(red)+"/"+hex(writ))

            handle.releaseInterface()
	def run (self):
		bb_messenging.status("Starting Modem thread")
		# runs "forever"
		self.bbtether = bb_tether.BBTether()
		self.bbtether.start(self.options, self.args)
		bb_messenging.log("BBTether Thread completed.")
Beispiel #37
0
 def __init__(self):
     bb_messenging.log("--------------------------------")
     bb_messenging.log("BBTether " + VERSION)
     bb_messenging.log("Thibaut Colar - 2009")
     bb_messenging.log("More infos: http://wiki.colar.net/bbtether")
     bb_messenging.log(
         "Use '-h' flag for more informations : 'python bbtether.py -h'.")
     bb_messenging.log("--------------------------------\n")