示例#1
0
 def test_send_file(self):
     files = [
         ('test.txt', 'text/plain'),
         ('test.gif', 'image/gif'),
         ('test.jpg', 'image/jpeg'),
         ('test.png', 'image/png'),
         ('test.html', 'text/html'),
         ('test.css', 'text/css'),
         ('test.js', 'application/javascript'),
         ('test.json', 'application/json'),
         ('test.bin', 'application/octet-stream'),
     ]
     for file, content_type in files:
         res = Response.send_file('tests/files/' + file)
         self.assertEqual(res.status_code, 200)
         self.assertEqual(res.headers['Content-Type'], content_type)
         fd = io.BytesIO()
         res.write(fd)
         response = fd.getvalue()
         self.assertEqual(response,
                          (b'HTTP/1.0 200 OK\r\nContent-Type: ' +
                           content_type.encode() + b'\r\n\r\nfoo\n'))
     res = Response.send_file('tests/files/test.txt',
                              content_type='text/html')
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers['Content-Type'], 'text/html')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertEqual(
         response,
         b'HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\nfoo\n')
示例#2
0
def create_new_account(account, pub_key, amount):
    creator = name('helloworld11').to_bytes()
    assert amount > 6_000, "not enough balance to create an account"

    packed_size = b'\x01'
    packed_zero_size = b'\x00'
    packed_key_weight = struct.pack('H', 1)  #uint16
    threshold = struct.pack('I', 1)  #uint32

    new_account = uio.BytesIO(102)
    auth = b''.join((threshold, packed_size, pub_key, packed_key_weight,
                     packed_zero_size, packed_zero_size))
    owner = auth
    active = auth

    new_account.write(creator)
    new_account.write(account)
    new_account.write(owner)
    new_account.write(active)
    print(new_account.tell())

    actor = name('helloworld11')
    permission = name('active')
    chain.send_inline(name('eosio'), name('newaccount'), actor, permission,
                      new_account.getvalue())

    # buyrambytes = creator + account + struct.pack('I', 64*1024)
    # chain.send_inline(name('uuos'), name('buyrambytes'), actor, permission, buyrambytes)

    payer = creator
    receiver = account
    buy_ram_amount = 5_000
    quantity = struct.pack('Q', buy_ram_amount) + RAW_TOKEN_SYMBOL

    buyram = uio.BytesIO(32)
    buyram.write(payer)
    buyram.write(receiver)
    buyram.write(quantity)
    buyram = buyram.getvalue()
    # buyram = b''.join((payer, receiver, quantity))
    chain.send_inline(name('eosio'), name('buyram'), actor, permission, buyram)

    stake_net_amount = 1_000
    stake_cpu_amount = amount - buy_ram_amount - stake_net_amount

    stake_net_quantity = struct.pack('Q', stake_net_amount) + RAW_TOKEN_SYMBOL
    stake_cpu_quantity = struct.pack('Q', stake_cpu_amount) + RAW_TOKEN_SYMBOL
    transfer = b'\x01'

    delegatebw = creator + account + stake_net_quantity + stake_cpu_quantity + transfer
    chain.send_inline(name('eosio'), name('delegatebw'), actor, permission,
                      delegatebw)
示例#3
0
def resource_stream(package, resource):
    return open(resource)  # hack, to get picoweb working

    if package not in c:
        try:
            if package:
                p = __import__(package + ".R", None, None, True)
            else:
                p = __import__("R")
            c[package] = p.R
        except ImportError:
            if package:
                p = __import__(package)
                d = p.__path__
            else:
                d = "."
#            if d[0] != "/":
#                import uos
#                d = uos.getcwd() + "/" + d
            c[package] = d + "/"

    p = c[package]
    if isinstance(p, dict):
        return uio.BytesIO(p[resource])
    return open(p + resource, "rb")
示例#4
0
    async def DownloadList(aUrl: str) -> bool:
        Buf = uio.BytesIO()
        try:
            await UrlLoad(aUrl, Buf)
            Data = Buf.getvalue().decode("utf-8")
            Data = json.loads(Data)
            Buf.close()
        except Exception as E:
            Log.Print(1, 'x', 'DownloadList()', E)
            return False

        Size = 0
        Root = aUrl.rsplit('/', 1)[0]
        Files = Data.get('Files', [])
        for File in Files:
            Arr = File.rsplit('/', 1)
            if (len(Arr) == 2):
                try:
                    os.mkdir(Arr[0])
                except:
                    pass

            Url = Root + '/' + File
            with open(File, "w") as hFile:
                await UrlLoad(Url, hFile)
                hFile.seek(0, 2)
                Size += hFile.tell()
        return (Data.get('Size', 0) == Size)
示例#5
0
def readall_from(source, into=None, timeout=None, chunk_size=64):
    """
    This function can be used to read from a socket or file-like object into another
    socket or file-like object. `timeout` is only relevant for socket objects.
    """

    if timeout is not None:
        if isinstance(source, socket.socket):
            source.settimeout(timeout)
        if isinstance(into, socket.socket):
            into.settimeout(timeout)

    if into is None:
        into = uio.BytesIO()

    data = b""
    while True:
        try:
            if isinstance(source, socket.socket):
                data = source.recv(chunk_size)
            else:
                data = source.read(chunk_size)
            if data:
                into.write(data)
            else:
                break
        except OSError as exc:
            if exc.args[0] == uerrno.ETIMEDOUT:
                if not data:
                    break  # will break on second timeout event
                data = b""
            else:
                raise exc

    return into
示例#6
0
def do_usb_command(cmd, args):
    # TESTING commands!
    # - only to be implemented on the simulator!!
    # - pleaes don't freak out, stay calm
    # - if you can trick us into running this, can run anything worse directly
    # - and we don't ship this code on the real product, only part of simulator

    if cmd == 'XKEY':
        from main import numpad
        try:
            numpad.inject(str(args, 'ascii'))
        except: pass
        return

    try:
        if cmd == 'EVAL':
            return b'biny' + repr(eval(str(args, 'utf8'))).encode()

        if cmd == 'EXEC':
            RV = uio.BytesIO()
            exec(str(args, 'utf8'), None, dict(RV=RV))
            return b'biny' + RV.getvalue()

    except BaseException as exc:
        tmp = uio.StringIO()
        sys.print_exception(exc, tmp)
        return b'biny' + tmp.getvalue().encode()

    return b'err_Unknown SIMULATOR cmd'
示例#7
0
    def log(self):
        self.init()
        log_head = self.log_db.load(0)
        total_log, pos = struct.unpack('ii', log_head.raw[:8])

        raw_log = chain.get_log()
        if not raw_log:
            return
        if len(raw_log) > 512:
            raw_log = raw_log[:512]
        buf = uio.BytesIO(512)
        buf.write(raw_log)
        buf.seek(512)
        buf.write(b'\x00')

        log = Log(buf.getvalue())
        pos += 1
        if pos > 10:
            pos = 1
        log.index = pos
        self.log_db.store(log)

        if total_log < 10:
            total_log += 1
        raw = struct.pack('ii', total_log, pos)
        log_head.raw = struct.pack('ii', total_log, pos)
        self.log_db.store(log_head)
示例#8
0
 def _set_buffer(self, line=b''):
     """
     Truncate buffer (Missing truncate function in uio.bytesIO object)
     """
     self._buffer = uio.BytesIO()
     self._buffer.write(line)
     gc.collect()
示例#9
0
    def read(self, s):
        """read in client request from socket"""

        data = s.read()
        if not data:
            # no data in the TCP stream, so close the socket
            self.close(s)
            return

        # add new data to the full request
        sid = id(s)
        self.request[sid] = self.request.get(sid, b"") + data

        # check if additional data expected
        if data[-4:] != b"\r\n\r\n":
            # HTTP request is not finished if no blank line at the end
            # wait for next read event on this socket instead
            return

        # get the completed request
        req = self.parse_request(self.request.pop(sid))

        if not self.is_valid_req(req):
            headers = (b"HTTP/1.1 307 Temporary Redirect\r\n"
                       b"Location: http://{:s}/\r\n".format(self.local_ip))
            body = uio.BytesIO(b"")
            self.prepare_write(s, body, headers)
            return

        # by this point, we know the request has the correct
        # host and a valid route
        body, headers = self.get_response(req)
        self.prepare_write(s, body, headers)
示例#10
0
    def pack_code(self, code):
        buf = uio.BytesIO()
        self.write_uint(code.mpy_stacksize, buf)
        self.write_uint(code.mpy_excstacksize, buf)
        buf.write(
            bytes([
                code.co_flags, code.co_argcount, code.co_kwonlyargcount,
                code.mpy_def_pos_args
            ]))

        # Apparently, uPy's code_info_size includes the size of the field itself, but it's varlen field!!
        # reported as https://github.com/micropython/micropython/issues/4378
        self.write_uint(1 + 4 + len(code.co_lnotab), buf)

        # co_name qstr, will be filled in on load
        buf.write(bytes([0, 0]))
        # co_filename qstr, will be filled in on load
        buf.write(bytes([0, 0]))

        buf.write(code.co_lnotab)

        buf.write(bytes(code.co_cellvars))
        buf.write(bytes([0xff]))

        buf.write(code.co_code)

        return buf
示例#11
0
    def test_write_only(self):
        output = uio.BytesIO()
        writer = uhttp.ResponseWriter(output)

        data = b'This is a buffer that will be written'
        writer.write(data)

        output.seek(0)
        statusLine = output.readline()
        self.assertEqual(statusLine.decode().strip(), 'HTTP/1.1 200 OK')
        got_headers = uhttp._parse_headers(output)
        want_len = len(data)

        # Default headers should be there
        self.assertTrue('server' in got_headers, 'No server header')
        self.assertTrue('connection' in got_headers, 'No connection header')

        self.assertEqual(
            got_headers, {
                'server': got_headers['server'],
                'connection': got_headers['connection'],
                'content-length': str(want_len)
            })
        got_data = output.read(want_len)
        self.assertEqual(got_data, data)
示例#12
0
    def test_write_header_custom_headers(self):
        output = uio.BytesIO()
        writer = uhttp.ResponseWriter(output)
        writer.headers['X-Header-1'] = 'value1'
        writer.headers['X-Header-2'] = 'value2'
        writer.write_header(534, 'Custom Reason Phrase')
        output.write('\n\n')
        output.seek(0)
        output.readline()
        got_headers = uhttp._parse_headers(output)

        pythonName = sys.implementation.name
        pythonVersion = '.'.join(map(str, sys.implementation.version))
        self.assertEqual(
            got_headers, {
                'server':
                'uhttp/0.1 %s/%s %s' %
                (pythonName, pythonVersion, sys.platform),
                'connection':
                'close',
                'x-header-1':
                'value1',
                'x-header-2':
                'value2'
            })
示例#13
0
    def test_write_header_known_status(self):
        output = uio.BytesIO()
        writer = uhttp.ResponseWriter(output)

        writer.write_header(uhttp.HTTP_STATUS_OK)
        output.seek(0)
        status_line = output.readline()
        self.assertEqual(b"HTTP/1.1 200 OK", status_line.rstrip())

        output.seek(0)
        writer.write_header(uhttp.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE)
        output.seek(0)
        status_line = output.readline()
        self.assertEqual(b"HTTP/1.1 415 Unsupported Media Type",
                         status_line.rstrip())
        self.assertEqual(writer.status,
                         uhttp.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE)

        output.seek(0)
        writer.write_header(uhttp.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
                            'Custom reason phrase 123321')
        output.seek(0)
        status_line = output.readline()
        self.assertEqual(b"HTTP/1.1 415 Custom reason phrase 123321",
                         status_line.rstrip())
示例#14
0
    def body(self):
        if self._body != None:
            return self._body

        if not 'content-length' in self.headers:
            raise HTTPException(
                HTTP_STATUS_LENGTH_REQUIRED,
                HTTP_REASON_PHRASE[HTTP_STATUS_LENGTH_REQUIRED])
        content_length = self.headers['content-length']
        if not content_length.isdigit():
            raise HTTPException(
                HTTP_STATUS_LENGTH_REQUIRED,
                HTTP_REASON_PHRASE[HTTP_STATUS_LENGTH_REQUIRED])
        content_length = int(content_length)

        body = uio.BytesIO(content_length)

        bytes_received = 0
        while bytes_received < content_length:
            fetched = self._input.read(content_length - bytes_received)
            bytes_received += len(fetched)
            body.write(fetched)

        body.seek(0)
        self._body = body
        return body
示例#15
0
 def test_req_body_empty(self):
     input = uio.BytesIO(('POST /some-resource?qs=value HTTP/1.1\n'
                          'Host: domain.com\n'
                          'Content-Length: 0\n'
                          '\n'))
     req = uhttp.Request(input)
     body = req.body().read(1024)
     self.assertEqual(b'', body)
示例#16
0
def resolve(domain, is_ipv6):
    buf = uio.BytesIO(48)
    udnspkt.make_req(buf, "google.com", is_ipv6)
    v = buf.getvalue()
    print("query: ", v)
    s.sendto(v, dns_addr)

    resp = s.recv(1024)
    print("resp:", resp)
    buf = uio.BytesIO(resp)

    addr = udnspkt.parse_resp(buf, is_ipv6)
    print("bin addr:", addr)
    print(
        "addr:",
        usocket.inet_ntop(usocket.AF_INET6 if is_ipv6 else usocket.AF_INET,
                          addr))
示例#17
0
 def test_req_body(self):
     body = 'body line 1\nbody line 2\n'
     input = uio.BytesIO(('POST /some-resource?qs=value HTTP/1.1\n'
                          'Host: domain.com\n' +
                          'Content-Length: %d\n\n' % len(body) + body))
     req = uhttp.Request(input)
     got_body = req.body().read(1024)
     self.assertEqual(body, got_body.decode())
示例#18
0
def loads(payload, **kwargs):
    """
    Deserialize an object from a bytestring.
    :param bytes payload: the bytestring to serialize
    :param kwargs: keyword arguments passed to :class:`~.CBORDecoder`
    :return: the deserialized object
    """
    fp = uio.BytesIO(payload)
    return CBORDecoder(fp, **kwargs).decode()
示例#19
0
 def test_req_body_json(self):
     json_payload = ('{\n' '"key":"value"' '}\n')
     input = uio.BytesIO(
         ('POST /some-resource?qs=value HTTP/1.1\n'
          'Host: domain.com\n' +
          'Content-Length: %d\n\n' % len(json_payload) + json_payload))
     req = uhttp.Request(input)
     body = ujson.load(req.body())
     self.assertEqual({'key': 'value'}, body)
示例#20
0
 def __init__(self):
     self.buf = uio.BytesIO()
     self.co_names = []
     self.co_consts = []
     self.labels = []
     self.stk_ptr = 0
     self.stk_use = 0
     self.exc_stk_ptr = 0
     self.exc_stk_use = 0
     self.only_for_mpy = False
示例#21
0
    def get_response(self, req):
        """generate a response body and headers, given a route"""

        headers = b"HTTP/1.1 200 OK\r\n"
        route = self.routes.get(req.path, None)

        if type(route) is bytes:
            # expect a filename, so return contents of file
            return open(route, "rb"), headers

        if callable(route):
            # call a function, which may or may not return a response
            response = route(req.params)
            body = response[0] or b""
            headers = response[1] or headers
            return uio.BytesIO(body), headers

        headers = b"HTTP/1.1 404 Not Found\r\n"
        return uio.BytesIO(b""), headers
示例#22
0
 def test_create_with_status_and_reason(self):
     res = Response('not found', 404, reason='NOT FOUND')
     self.assertEqual(res.status_code, 404)
     self.assertEqual(res.headers, {})
     self.assertEqual(res.reason, 'NOT FOUND')
     self.assertEqual(res.body, b'not found')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertIn(b'HTTP/1.0 404 NOT FOUND\r\n', response)
示例#23
0
 def test_create_with_reason(self):
     res = Response('foo', reason='ALL GOOD!')
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers, {})
     self.assertEqual(res.reason, 'ALL GOOD!')
     self.assertEqual(res.body, b'foo')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertIn(b'HTTP/1.0 200 ALL GOOD!\r\n', response)
示例#24
0
 def test_create_from_none(self):
     res = Response(None)
     self.assertEqual(res.status_code, 204)
     self.assertEqual(res.body, b'')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertIn(b'HTTP/1.0 204 N/A\r\n', response)
     self.assertIn(b'Content-Length: 0\r\n', response)
     self.assertIn(b'Content-Type: text/plain\r\n', response)
     self.assertTrue(response.endswith(b'\r\n\r\n'))
示例#25
0
def dumps(obj, **kwargs):
    """
    Serialize an object to a bytestring.
    :param obj: the object to serialize
    :param kwargs: keyword arguments passed to :class:`~.CBOREncoder`
    :return: the serialized output
    :rtype: bytes
    """
    fp = uio.BytesIO()
    dump(obj, fp, **kwargs)
    return fp.getvalue()
示例#26
0
 def test_create_from_bytes(self):
     res = Response(b'foo')
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers, {})
     self.assertEqual(res.body, b'foo')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertIn(b'HTTP/1.0 200 OK\r\n', response)
     self.assertIn(b'Content-Length: 3\r\n', response)
     self.assertIn(b'Content-Type: text/plain\r\n', response)
     self.assertTrue(response.endswith(b'\r\n\r\nfoo'))
示例#27
0
 def test_create_empty(self):
     res = Response(headers={'X-Foo': 'Bar'})
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers, {'X-Foo': 'Bar'})
     self.assertEqual(res.body, b'')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertIn(b'HTTP/1.0 200 OK\r\n', response)
     self.assertIn(b'X-Foo: Bar\r\n', response)
     self.assertIn(b'Content-Length: 0\r\n', response)
     self.assertIn(b'Content-Type: text/plain\r\n', response)
     self.assertTrue(response.endswith(b'\r\n\r\n'))
示例#28
0
    def test_process_client_handle_unhandled_handler_errors(self):
        def handler(w, req):
            raise Exception('Something happened')

        server = uhttp.HTTPServer(
            handler=handler,
            port=8080,
            logger=logger.TestLogger(),
        )
        client = uio.BytesIO(('GET /some-resource?qs=value HTTP/1.1\n'
                              'Host: domain.com\n'
                              '\n'))
        output = uio.BytesIO()
        writer = uhttp.ResponseWriter(output)
        server._process_client(writer, client)

        output.seek(0)
        self.assertEqual(
            output.readline().decode().strip(), 'HTTP/1.1 %s %s' %
            (uhttp.HTTP_STATUS_INTERNAL_SERVER_ERROR, uhttp.HTTP_REASON_PHRASE[
                uhttp.HTTP_STATUS_INTERNAL_SERVER_ERROR]))
        server.stop()
示例#29
0
 def __init__(self, codeobjs_off=-1):
     self.buf = uio.BytesIO()
     self.co_names = []
     self.mpy_consts = []
     self.mpy_codeobjs = []
     self.codeobj_off = codeobjs_off
     self.labels = []
     self.stk_ptr = 0
     self.stk_use = 0
     self.exc_stk_ptr = 0
     self.exc_stk_use = 0
     self.co_flags = 0
     self.only_for_mpy = False
示例#30
0
 def test_send_file_small_buffer(self):
     original_buffer_size = Response.send_file_buffer_size
     Response.send_file_buffer_size = 2
     res = Response.send_file('tests/files/test.txt',
                              content_type='text/html')
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers['Content-Type'], 'text/html')
     fd = io.BytesIO()
     res.write(fd)
     response = fd.getvalue()
     self.assertEqual(
         response,
         b'HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\nfoo\n')
     Response.send_file_buffer_size = original_buffer_size