Exemplo n.º 1
0
def play_stop(b, _id, stop_completion):
	res = None
	if 'setproctitle' in sys.modules:
		setproctitle.setproctitle('python TVMLServer (play wait {})'.format(_id))
	now = time.time()
	while not b.thread.stop and time.time() - now < 18000: #Max wait for 5 hours in case of stuck/aborted app
		try:
			r = b.thread.responses.get(False)
			print 'found response for {}'.format(r['id'])
			if r['id'] == _id:
				print 'received response to {}'.format(_id)
				res = r['response']
				break
			else:
				b.thread.responses.put(r)					
		except:
			gevent.sleep(1)
	b.play = None
	if time.time() - now < 18000:
		print 'detected player stop at time {}'.format(utils.b64decode(res))
		if stop_completion:
			print 'calling stop completion'
			stop_completion(utils.b64decode(res))
	else:
		print 'forced player stop due to unresponsiveness'
		if stop_completion:
			stop_completion(0)		
Exemplo n.º 2
0
def play_stop(b, _id, stop_completion):
    res = None
    if 'setproctitle' in sys.modules:
        setproctitle.setproctitle(
            'python TVMLServer (play wait {})'.format(_id))
    now = time.time()
    while not b.thread.stop and time.time(
    ) - now < 18000:  #Max wait for 5 hours in case of stuck/aborted app
        try:
            r = b.thread.responses.get(False)
            print 'found response for {}'.format(r['id'])
            if r['id'] == _id:
                print 'received response to {}'.format(_id)
                res = r['response']
                break
            else:
                b.thread.responses.put(r)
        except:
            gevent.sleep(1)
    b.play = None
    if time.time() - now < 18000:
        print 'detected player stop at time {}'.format(utils.b64decode(res))
        if stop_completion:
            print 'calling stop completion'
            stop_completion(utils.b64decode(res))
    else:
        print 'forced player stop due to unresponsiveness'
        if stop_completion:
            stop_completion(0)
Exemplo n.º 3
0
def _getEmptyOrB64(b, receiptId, reason):
    if not isinstance(b, string_types):
        raise MalformedReceiptException(receiptId, reason)
    try:
        return utils.b64decode(b.encode('utf-8'))
    except (TypeError, binascii.Error):
        raise MalformedReceiptException(receiptId, reason)
Exemplo n.º 4
0
 def parse(data):
     filename_el = data.find('filename')
     file_data_el = data.find('file_data')
     return {
         'filename': filename_el.text,
         'file_data': utils.b64decode(file_data_el.text)
     }
Exemplo n.º 5
0
def extract_image_from_element(el):
    filename_el = el.find('filename')
    file_data_el = el.find('file_data')
    return {
        'filename': filename_el.text,
        'file_data': utils.b64decode(file_data_el.text)
    }
Exemplo n.º 6
0
 def isReversal(self):
     """
     Determines if this receipt is a reversal.
     :return: True if the receipt is a reversal, False otherwise.
     """
     decCtr = utils.b64decode(self.encTurnoverCounter.encode("utf-8"))
     return decCtr == b'STO'
Exemplo n.º 7
0
 def isDummy(self):
     """
     Determines if this receipt is a dummy receipt.
     :return: True if the receipt is a dummy receipt, False otherwise.
     """
     decCtr = utils.b64decode(self.encTurnoverCounter.encode("utf-8"))
     return decCtr == b'TRA'
Exemplo n.º 8
0
    def to_ECDSA(klass, webkey):
        import ecdsa
        curves = {
            'P-256': ecdsa.NIST256p,
            'P-384': ecdsa.NIST384p,
            'P-521': ecdsa.NIST521p,
        }

        x = long(b64decode(webkey['x']))
        y = long(b64decode(webkey['y']))
        curve = curves[webkey['curve']]

        # the method ``from_public_point()`` takes an instance of
        # ellipticcurve.Point instance, which must be generated from an
        # instance of CurveFp, long x, and long y.
        point = ecdsa.ellipticcurve.Point(curve.curve, x, y)
        return ecdsa.VerifyingKey.from_public_point(point, curve)
Exemplo n.º 9
0
Arquivo: aes.py Projeto: stryku/hb
    def decrypt(self, enc):
        if len(enc) == 0:
            return b''

        enc = utils.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(
            enc[AES.block_size:])).decode('utf-8')
Exemplo n.º 10
0
 def __init__(self, dir, limit=0):
     if not os.path.isdir(dir):
         raise Exception('dir must be a directory')
     self.cache = {}
     self.size = 0
     self.dir = dir
     self.limit = limit
     for f in os.listdir(self.dir):
         try:
             self.add(utils.b64decode(f), os.path.join(self.dir, f))
         except:
             continue
Exemplo n.º 11
0
def main():
	if request.method == 'POST':
		favs = json.loads(utils.b64decode(request.form.keys()[0]))
                new_favs = []
                for id in favs:
                    matching = [p for p in PLUGINS if p.id == id]
                    if matching:
                       new_favs.append(matching[0]) 
		favs = new_favs
	else:
		favs = []
	return render_template('main.xml', menu=PLUGINS, favs=favs, url=request.full_path)
Exemplo n.º 12
0
    def toOCRCode(self, algorithmPrefix):
        """
        Converts the receipt to an OCR code string.
        :param algorithmPrefix: The ID of the algorithm class used as a string.
        :return The receipt as an OCR code string.
        """
        if not self.signed:
            raise Exception(_("You need to sign the receipt first."))

        segments = [
            b'_' + algorithmPrefix.encode("utf-8") + b'-' +
            self.zda.encode("utf-8")
        ]
        segments.append(self.registerId.encode("utf-8"))
        segments.append(self.receiptId.encode("utf-8"))
        segments.append(self.dateTimeStr.encode("utf-8"))
        segments.append(self.sumAStr.encode("utf-8"))
        segments.append(self.sumBStr.encode("utf-8"))
        segments.append(self.sumCStr.encode("utf-8"))
        segments.append(self.sumDStr.encode("utf-8"))
        segments.append(self.sumEStr.encode("utf-8"))

        encTurnoverCounter = self.encTurnoverCounter.encode("utf-8")
        encTurnoverCounter = utils.b64decode(encTurnoverCounter)
        segments.append(base64.b32encode(encTurnoverCounter))

        segments.append(self.certSerial.encode("utf-8"))

        previousChain = self.previousChain.encode("utf-8")
        previousChain = utils.b64decode(previousChain)
        segments.append(base64.b32encode(previousChain))

        signature = utils.restoreb64padding(self.signature).encode("utf-8")
        signature = utils.urlsafe_b64decode(signature)
        segments.append(base64.b32encode(signature))

        return b'_'.join(segments).decode("utf-8")
Exemplo n.º 13
0
def main():
    if request.method == 'POST':
        favs = json.loads(utils.b64decode(request.form.keys()[0]))
        new_favs = []
        for id in favs:
            matching = [p for p in PLUGINS if p.id == id]
            if matching:
                new_favs.append(matching[0])
        favs = new_favs
    else:
        favs = []
    return render_template('main.xml',
                           menu=PLUGINS,
                           favs=favs,
                           url=request.full_path)
Exemplo n.º 14
0
 def inputdialog(self,
                 title,
                 description='',
                 placeholder='',
                 button='OK',
                 secure=False):
     """Shows an input dialog to the user with text field. Returns the text the user typed or None if user aborted"""
     s = self._message(
         {
             'type': 'inputdialog',
             'title': title,
             'description': description,
             'placeholder': placeholder,
             'button': button,
             'secure': secure
         }, True)
     return utils.b64decode(s) if s else None
Exemplo n.º 15
0
    def recv(self, token):
        count = 0
        stack = []
        relation = {}
        finish_url = None
        try:
            token = utils.b64decode(token)
            if self.mask_key:
                token = utils.decrypt_by_key(token, self.mask_key)
            view_name, args, kwargs, count = utils.token_decode(token)
            finish_url, stack, relation = self.storage.get()

        except (IndexError, KeyError, ValueError, TypeError):
            return None

        finally:
            self.stack = stack
            self.relation = dict((k, stack[v]) for k, v in relation.items())
            self.index = count
            self.finish_url = finish_url or reverse(self.default)
            return lambda request, **kw: kw.update(kwargs) or self.views[view_name](request, *args, **kw)
Exemplo n.º 16
0
	def formdialog(self, title, fields=[], sections={}, cont=False):
		"""Show a custom form dialog with custom fields
			A field is an object with a type, a label, a value (initial) and other attributes depending on its type.
			Available types are: textfield, yesno and selection
			textfield:
				displayed as a label. when clicked, user is presented with an input form to modify the field. Additional optional attributes: description, placeholder, button and secure.
			yesno:
				value must be a boolean. displayed as a label with 'Yes' or 'No' depending on the value. Clicking on it changes the value between 'Yes' and 'No'. Has no other attributes.
			selection:
				displayed exactly like yesno, but clicking rotates the field on values from the list. possible values are passed via the 'choices' attribute. Initial value must be one of the choices.
				
			There are 2 ways you can call this function: With a list of fields passed with the fields parameter, or a dict of sections where key is the title, and value is a list of fields
			
			cont is a boolean whether to continue receiving messages after form has been dismissed
			returns a dict with keys as field labels and values as their (modified) value
			"""
		if fields:
			s = self._message({'type':'formdialog', 'title':title, 'sections':{'General':fields}, 'cont':cont}, True)
		elif sections:
			s = self._message({'type':'formdialog', 'title':title, 'sections':sections, 'cont':cont}, True)
		else:
			raise Exception('Must have either fields or sections')
		return json.loads(utils.b64decode(s)) if s else None
Exemplo n.º 17
0
    def decryptTurnoverCounter(self, key, algorithm):
        """
        Decrypts the encrypted turnover counter using the given key and
        algorithm. The receipt must not be a dummy receipt or a reversal in
        order for this to work.
        :param key: The key to decrypt the counter as a byte list.
        :param algorithm: The algorithm to use as an algorithm object.
        :return: The decrypted turnover counter as int.
        :throws: InvalidKeyException
        """
        if self.isDummy():
            raise Exception(
                _("Can't decrypt turnover counter, this is a dummy receipt."))
        if self.isReversal():
            raise Exception(
                _("Can't decrypt turnover counter, this is a reversal receipt."
                  ))

        if not algorithm.verifyKey(key):
            raise InvalidKeyException(self.receiptId)

        ct = utils.b64decode(self.encTurnoverCounter.encode("utf-8"))
        return algorithm.decryptTurnoverCounter(self, ct, key)
Exemplo n.º 18
0
    def formdialog(self, title, fields=[], sections={}, cont=False):
        """Show a custom form dialog with custom fields
			A field is an object with a type, a label, a value (initial) and other attributes depending on its type.
			Available types are: textfield, yesno and selection
			textfield:
				displayed as a label. when clicked, user is presented with an input form to modify the field. Additional optional attributes: description, placeholder, button and secure.
			yesno:
				value must be a boolean. displayed as a label with 'Yes' or 'No' depending on the value. Clicking on it changes the value between 'Yes' and 'No'. Has no other attributes.
			selection:
				displayed exactly like yesno, but clicking rotates the field on values from the list. possible values are passed via the 'choices' attribute. Initial value must be one of the choices.
				
			There are 2 ways you can call this function: With a list of fields passed with the fields parameter, or a dict of sections where key is the title, and value is a list of fields
			
			cont is a boolean whether to continue receiving messages after form has been dismissed
			returns a dict with keys as field labels and values as their (modified) value
			"""
        if fields:
            s = self._message(
                {
                    'type': 'formdialog',
                    'title': title,
                    'sections': {
                        'General': fields
                    },
                    'cont': cont
                }, True)
        elif sections:
            s = self._message(
                {
                    'type': 'formdialog',
                    'title': title,
                    'sections': sections,
                    'cont': cont
                }, True)
        else:
            raise Exception('Must have either fields or sections')
        return json.loads(utils.b64decode(s)) if s else None
Exemplo n.º 19
0
	def inputdialog(self, title, description='', placeholder='', button='OK', secure=False):
		"""Shows an input dialog to the user with text field. Returns the text the user typed or None if user aborted"""
		s = self._message({'type':'inputdialog', 'title':title, 'description':description, 'placeholder':placeholder, 'button':button, 'secure':secure}, True)
		return utils.b64decode(s) if s else None
Exemplo n.º 20
0
def subtitles(msg):
	msg = utils.b64decode(msg)
	print msg
Exemplo n.º 21
0
def catalog(pluginid, url=None, process=None):
	try:
		if not url:
			decoded_url = ''
		elif url == 'fake':
			decoded_url = ''
		else:
			decoded_url = utils.b64decode(url)
		decoded_id = utils.b64decode(pluginid)
		if request.full_path.startswith('/catalog'):
			print 'catalog {}, {}, {}'.format(decoded_id, decoded_url, process)
		else:
			print 'menu {}, {}'.format(decoded_id, process)
		plugin = [p for p in PLUGINS if p.id == decoded_id][0]
		if not plugin:
			return render_template('alert.xml', title='Communication error', description="Failed to load page.\nThis could mean the server had a problem, or the request dialog timed-out\nPlease try again")
		
		global PROCESSES
		if process:
			if not process in PROCESSES:
				return render_template('alert.xml', title='Fatal error', description="Failed to load page.\nSomething has gone terribly wrong.\nPlease try to restart the App")
			p = PROCESSES[process]
		else:
			if request.full_path.startswith('/catalog'):
				p = Process(target=get_items, args=(plugin.id, decoded_url, CONTEXT, PLUGINS))
			else:
				p = Process(target=get_menu, args=(plugin.id, decoded_url))	
			print 'saving process id {}'.format(p.id)		
			PROCESSES[p.id] = p
			def stop():
				time.sleep(5) #close bridge after 5s
				global PROCESSES
				del PROCESSES[p.id]
			#b.thread.onStop = stop
			p.start()
		print 'entering while alive'
		while p.is_alive():
			try:
				msg = p.messages.get(False)
			except:
				gevent.sleep(0.1)
				continue
			try:		
				method = getattr(messages, msg['type'])
				if msg['type'] == 'end' or msg['type'] == 'load':
					global PROCESSES
					del PROCESSES[p.id]
					#p.join()
					#p.terminate()
					print 'PROCESS {} TERMINATED'.format(p.id)
				return_url = None
				if process:
					#return on same url for more
					return_url = request.url
				elif url or request.full_path.startswith('/menu'):
					#add response bridge
					return_url = '{}/{}'.format(request.url, p.id)
				else:
					#No url and no response so add 'fake' url
					return_url = '{}/{}/{}'.format(request.url, 'fake', p.id)
				return method(plugin, msg, return_url)
			except:
				traceback.print_exc(file=sys.stdout)
		print 'exiting while alive and entering 2s wait'
		#Check for possible last message which could have appeared after the thread has died. This could happen if message was sent during time.sleep in while and loop exited immediately afterwards
		start = 0
		while start < 5: #wait at most 5 seconds
			try:
				msg = p.messages.get(False)
			except:
				gevent.sleep(0.1)
				start+=0.1
				continue
			try:
				method = getattr(messages, msg['type'])
				if msg['type'] == 'end' or msg['type'] == 'load':				
					global PROCESSES
					del PROCESSES[p.id]
					#p.join()
					#p.terminate()
					print 'PROCESS {} TERMINATED'.format(p.id)
				return method(plugin, msg, request.url) if process else method(plugin, msg, '{}/{}'.format(request.url, p.id))	
			except:
				traceback.print_exc(file=sys.stdout)
		print 'finished 5 sec wait'
		#if we got here, this means thread has probably crashed.
		global PROCESSES
		del PROCESSES[p.id]
		p.join()
		p.terminate()
		print 'PROCESS {} CRASHED'.format(p.id)
# 		def restart():
# 			print 'restarting app'
# 			global http_server
# 			http_server.stop()
# 			try:
# 				p = psutil.Process(os.getpid())
# 				for handler in p.get_open_files() + p.connections():
# 					os.close(handler.fd)
# 			except Exception, e:
# 				print e
# 			python = sys.executable
# 			os.execl(python, python, *sys.argv)
# 		Timer(1, restart, ()).start()
		return render_template('alert.xml', title='Communication error', description="Failed to load page.\nThis could mean the server had a problem, or the request dialog timed-out\nPlease try again")
	except:
		traceback.print_exc(file=sys.stdout)
		return render_template('alert.xml', title='Communication error', description="Failed to load page.\nThis could mean the server had a problem, or the request dialog timed-out\nPlease try again")
Exemplo n.º 22
0
 def to_RSA(klass, webkey):
     from Crypto.PublicKey import RSA
     exp = long(b64decode(webkey['exponent']))
     mod = long(b64decode(webkey['modulus']))
     return RSA.construct((exp, mod,))
Exemplo n.º 23
0
    def fromBasicCode(basicCode):
        """
        Creates a receipt object from a QR code string.
        :param basicCode: The QR code string to parse.
        :return: The new, signed receipt object.
        :throws: MalformedReceiptException
        :throws: UnknownAlgorithmException
        """
        if not isinstance(basicCode, string_types):
            raise MalformedReceiptException(
                basicCode, _('Invalid machine-readable code.'))

        segments = basicCode.split('_')
        if len(segments) != 14 or len(segments[0]) != 0:
            raise MalformedReceiptException(
                basicCode,
                _('Machine-readable code does not contain 13 elements.'))

        algorithmPrefixAndZda = segments[1].split('-')
        if len(algorithmPrefixAndZda) != 2:
            raise MalformedReceiptException(
                basicCode,
                _('Machine-readable code does not contain algorithm and ZDA IDs.'
                  ))
        algorithmPrefix = algorithmPrefixAndZda[0]
        zda = algorithmPrefixAndZda[1]

        if algRegex.match(algorithmPrefix) is None:
            raise MalformedReceiptException(
                basicCode,
                _('Algorithm ID \"{}\" invalid.').format(algorithmPrefix))
        if algorithmPrefix not in algorithms.ALGORITHMS:
            raise UnknownAlgorithmException(basicCode)
        header = algorithms.ALGORITHMS[algorithmPrefix].jwsHeader()

        registerId = segments[2]
        receiptId = segments[3]
        dateTime = segments[4]
        sumA = segments[5]
        sumB = segments[6]
        sumC = segments[7]
        sumD = segments[8]
        sumE = segments[9]
        turnoverCounter = segments[10]
        certSerial = segments[11]
        previousChain = segments[12]

        signature = None
        try:
            signature = utils.b64decode(segments[13].encode("utf-8"))
        except (TypeError, binascii.Error):
            raise MalformedReceiptException(
                basicCode,
                _('Signature \"{}\" not Base 64 encoded.').format(
                    segments[13]))
        signature = base64.urlsafe_b64encode(signature).replace(b'=', b'')
        signature = signature.decode("utf-8")

        # __init__ does not perform the latter two checks
        if not isinstance(turnoverCounter, string_types) \
                or not turnoverCounter.replace('=', ''):
            raise MalformedReceiptException(
                basicCode,
                _('Encrypted turnover counter \"{}\" invalid.').format(
                    turnoverCounter))
        if not isinstance(previousChain, string_types) \
                or not previousChain.replace('=', ''):
            raise MalformedReceiptException(
                basicCode,
                _('Chaining value \"{}\" invalid.').format(previousChain))

        receipt = Receipt(zda, registerId, receiptId, dateTime, sumA, sumB,
                          sumC, sumD, sumE, turnoverCounter, certSerial,
                          previousChain)
        receipt.sign(header, signature)

        return receipt, algorithmPrefix
Exemplo n.º 24
0
def subtitles(msg):
    msg = utils.b64decode(msg)
    print msg
Exemplo n.º 25
0
def catalog(pluginid, url=None, process=None):
    try:
        if not url:
            decoded_url = ''
        elif url == 'fake':
            decoded_url = ''
        else:
            decoded_url = utils.b64decode(url)
        decoded_id = utils.b64decode(pluginid)
        if request.full_path.startswith('/catalog'):
            print 'catalog {}, {}, {}'.format(decoded_id, decoded_url, process)
        else:
            print 'menu {}, {}'.format(decoded_id, process)
        plugin = [p for p in PLUGINS if p.id == decoded_id][0]
        if not plugin:
            return render_template(
                'alert.xml',
                title='Communication error',
                description=
                "Failed to load page.\nThis could mean the server had a problem, or the request dialog timed-out\nPlease try again"
            )

        global PROCESSES
        if process:
            if not process in PROCESSES:
                return render_template(
                    'alert.xml',
                    title='Fatal error',
                    description=
                    "Failed to load page.\nSomething has gone terribly wrong.\nPlease try to restart the App"
                )
            p = PROCESSES[process]
        else:
            if request.full_path.startswith('/catalog'):
                p = Process(target=get_items,
                            args=(plugin.id, decoded_url, CONTEXT, PLUGINS))
            else:
                p = Process(target=get_menu, args=(plugin.id, decoded_url))
            print 'saving process id {}'.format(p.id)
            PROCESSES[p.id] = p

            def stop():
                time.sleep(5)  #close bridge after 5s
                global PROCESSES
                del PROCESSES[p.id]

            #b.thread.onStop = stop
            p.start()
        print 'entering while alive'
        while p.is_alive():
            try:
                msg = p.messages.get(False)
            except:
                gevent.sleep(0.1)
                continue
            try:
                method = getattr(messages, msg['type'])
                if msg['type'] == 'end' or msg['type'] == 'load':
                    global PROCESSES
                    del PROCESSES[p.id]
                    #p.join()
                    #p.terminate()
                    print 'PROCESS {} TERMINATED'.format(p.id)
                return_url = None
                if process:
                    #return on same url for more
                    return_url = request.url
                elif url or request.full_path.startswith('/menu'):
                    #add response bridge
                    return_url = '{}/{}'.format(request.url, p.id)
                else:
                    #No url and no response so add 'fake' url
                    return_url = '{}/{}/{}'.format(request.url, 'fake', p.id)
                return method(plugin, msg, return_url)
            except:
                traceback.print_exc(file=sys.stdout)
        print 'exiting while alive and entering 2s wait'
        #Check for possible last message which could have appeared after the thread has died. This could happen if message was sent during time.sleep in while and loop exited immediately afterwards
        start = 0
        while start < 5:  #wait at most 5 seconds
            try:
                msg = p.messages.get(False)
            except:
                gevent.sleep(0.1)
                start += 0.1
                continue
            try:
                method = getattr(messages, msg['type'])
                if msg['type'] == 'end' or msg['type'] == 'load':
                    global PROCESSES
                    del PROCESSES[p.id]
                    #p.join()
                    #p.terminate()
                    print 'PROCESS {} TERMINATED'.format(p.id)
                return method(plugin, msg, request.url) if process else method(
                    plugin, msg, '{}/{}'.format(request.url, p.id))
            except:
                traceback.print_exc(file=sys.stdout)
        print 'finished 5 sec wait'
        #if we got here, this means thread has probably crashed.
        global PROCESSES
        del PROCESSES[p.id]
        p.join()
        p.terminate()
        print 'PROCESS {} CRASHED'.format(p.id)
        # 		def restart():
        # 			print 'restarting app'
        # 			global http_server
        # 			http_server.stop()
        # 			try:
        # 				p = psutil.Process(os.getpid())
        # 				for handler in p.get_open_files() + p.connections():
        # 					os.close(handler.fd)
        # 			except Exception, e:
        # 				print e
        # 			python = sys.executable
        # 			os.execl(python, python, *sys.argv)
        # 		Timer(1, restart, ()).start()
        return render_template(
            'alert.xml',
            title='Communication error',
            description=
            "Failed to load page.\nThis could mean the server had a problem, or the request dialog timed-out\nPlease try again"
        )
    except:
        traceback.print_exc(file=sys.stdout)
        return render_template(
            'alert.xml',
            title='Communication error',
            description=
            "Failed to load page.\nThis could mean the server had a problem, or the request dialog timed-out\nPlease try again"
        )