def run_client(server_address, server_port):
	# Ping a UDP pinger server running at the given address
	
	try:
		client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)

		# Time out after 1 second
		client_socket.settimeout(1.0)

		print("Pinging", str(server_address), "on port", server_port)

		for i in range(10):
			client_socket.sendto("".encode(), (server_address, server_port))

			try:
				time_start = time.time()
				_, _ = client_socket.recvfrom(1024)
				time_stop = time.time()
			except socket.timeout:
				print("Packet lost")
			else:
				print("RTT(Round trip time): {:.3f}ms".format((time_stop - time_start) * 1000))
	finally:
		client_socket.close()

	return 0
def send_mail(sender_address, mail_server, receiver_address, message):
	try:
		client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)

		# set a 1 second timeout
		client_socket.settimeout(1.0)

		# connect to mail server
		client_socket.connect((mail_server, 25))

		def send(string):
			"""Helper function: fix newlines, encode and send a string"""
			final = string.replace("\n", "\r\n").encode("ascii")
			print "Sending " + final + "..."
			client_socket.send(final)

			return 0

		def recv_and_check(expected=250):
			"""Helper function: recive reply and check it's ok"""
			reply = client_socket.recv(2048)
			print "Got: ", reply

			code = int(reply.rstrip().split()[0])
			if code != expected:
				raise Exception(reply)

			return 0

		# get initial message from server
		recv_and_check(220)

		# send greeting
		send("HELO {}\n".format(sender_address.split("@")[1]))
		recv_and_check()

		# set sender address
		send("MAIL FROM: {}\n".format(sender_address))
		recv_and_check()

		# set receiver address
		send("RCPT TO: {}\n".format(receiver_address))
		recv_and_check()

		# prepare to send message
		send("DATA\n")
		recv_and_check(354)

		# send the message itself followed by terminator
		send("{}\n.\n".format(message))
		recv_and_check()

		send("QUIT\n")
		recv_and_check(221)

	finally:
		client_socket.close()


	return 0
예제 #3
1
    def __demodulate(self, connection: socket.socket):
        connection.settimeout(0.1)
        time.sleep(self.TIMEOUT)

        total_data = []
        while True:
            try:
                data = connection.recv(65536)
                if data:
                    total_data.append(data)
                else:
                    break
            except socket.timeout:
                break

        if len(total_data) == 0:
            logger.error("Did not receive any data from socket.")

        arr = np.array(np.frombuffer(b"".join(total_data), dtype=np.complex64))
        signal = Signal("", "")
        signal._fulldata = arr
        pa = ProtocolAnalyzer(signal)
        pa.get_protocol_from_signal()
        return pa.plain_bits_str
예제 #4
0
class PyCashServer:
    HOST = ''                 # Symbolic name meaning all available interfaces
    PORT = 50007
    
    def __init__(self):
        self.s = Socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.HOST, self.PORT))
        self.s.listen(3)

    def receveObject(self):
        conn, addr = self.s.accept()
        conn.settimeout(5.0)
        
        data =  conn.recv(16)
        objString = ''
        while(data != None):
            objString += (data)
            conn.send(data)
            try:
                data =  conn.recv(16)
            except:
                data = None
    
    

        x =  json.loads(objString)
        return  obj(x)
예제 #5
0
파일: __init__.py 프로젝트: giflw/afn-tools
def main():
    register_builtin_interface()
    server = Socket()
    if len(sys.argv) > 1:
        server_port = int(sys.argv[1])
    else:
        server_port = DEFAULT_PORT
    print "Listening on port " + str(server_port)
    server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    server.bind(("", server_port))
    server.listen(50)
    
    Thread(target=process_event_queue).start()
    
    print "\nAutobus has successfully started up."
    
    try:
        while True:
            socket, address = server.accept()
            connection = Connection(socket, address)
            event_queue.put((connection.id, discard_args(connection.register)), block=True)
            connection.start()
    except KeyboardInterrupt:
        print "KeyboardInterrupt received, shutting down"
        event_queue.put((None, None), block=True)
        print "Event queue has been notified to shut down"
    except:
        print "Unexpected exception occurred in the main loop, shutting down. Stack trace:"
        print_exc()
        event_queue.put((None, None), block=True)
        print "Event queue has been notified to shut down"
    server.close()
예제 #6
0
 def new(cls, host, port, logger=None):
     logger = logger or logging.getLogger(__name__)
     sock = Socket()
     try:
         sock.connect((host, port))
     except socket.error:
         return None
     return Connection(sock, logger)
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        # Grab the banner
        if self.SHOULD_WAIT_FOR_SERVER_BANNER:
            sock.recv(2048)

        # Send Start TLS
        sock.send(self.START_TLS_CMD)
        if self.START_TLS_OK not in sock.recv(2048):
            raise StartTlsError(self.ERR_NO_STARTTLS)
예제 #8
0
async def udp_writer(s: socket, oqueue: Queue) -> None:
    """Forward packets to the UDP socket."""

    while True:
        peer, data = await oqueue.get()
        try:
            s.sendto(data, peer)
        finally:
            oqueue.task_done()
예제 #9
0
def _recv(sock: socket.socket, size: int) -> bytes:
    """Secondary function to receive a specified amount of data."""
    message = b''
    while len(message) < size:
        packet = sock.recv(size - len(message))
        if not packet:
            sock.close()
            raise OSError("Nothing else to read from socket")
        message += packet
    return message
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        sock.send(self.START_TLS_CMD)
        data = sock.recv(4)
        if not data or len(data) != 4 or data[:2] != b'\x03\x00':
            raise StartTlsError(self.ERR_NO_STARTTLS)
        packet_len = struct.unpack(">H", data[2:])[0] - 4
        data = sock.recv(packet_len)

        if not data or len(data) != packet_len:
            raise StartTlsError(self.ERR_NO_STARTTLS)
예제 #11
0
def handlerequest(clientsocket: socket.socket):
    conn = connecttodb()
    cursor = conn.cursor()
    tagid = bytes.decode(clientsocket.recv(3))
    query = 'select * from tagdata where id={0}'.format(tagid)
    cursor.execute(query)
    s=[]
    for (id, location, officehours, otherinfo, description) in cursor:
        s = [str(id)+','+location + ',', officehours + ',', otherinfo + ',', description]
        s.insert(0, str(len(''.join(s)))+',')
    clientsocket.send(bytes(''.join(s),encoding='utf8'))
    clientsocket.close()
예제 #12
0
    def _handle_connection(self, connection: socket.socket, address: Any) -> None:
        if self.ssl_options is not None:
            assert ssl, "Python 2.6+ and OpenSSL required for SSL"
            try:
                connection = ssl_wrap_socket(
                    connection,
                    self.ssl_options,
                    server_side=True,
                    do_handshake_on_connect=False,
                )
            except ssl.SSLError as err:
                if err.args[0] == ssl.SSL_ERROR_EOF:
                    return connection.close()
                else:
                    raise
            except socket.error as err:
                # If the connection is closed immediately after it is created
                # (as in a port scan), we can get one of several errors.
                # wrap_socket makes an internal call to getpeername,
                # which may return either EINVAL (Mac OS X) or ENOTCONN
                # (Linux).  If it returns ENOTCONN, this error is
                # silently swallowed by the ssl module, so we need to
                # catch another error later on (AttributeError in
                # SSLIOStream._do_ssl_handshake).
                # To test this behavior, try nmap with the -sT flag.
                # https://github.com/tornadoweb/tornado/pull/750
                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):
                    return connection.close()
                else:
                    raise
        try:
            if self.ssl_options is not None:
                stream = SSLIOStream(
                    connection,
                    max_buffer_size=self.max_buffer_size,
                    read_chunk_size=self.read_chunk_size,
                )  # type: IOStream
            else:
                stream = IOStream(
                    connection,
                    max_buffer_size=self.max_buffer_size,
                    read_chunk_size=self.read_chunk_size,
                )

            future = self.handle_stream(stream, address)
            if future is not None:
                IOLoop.current().add_future(
                    gen.convert_yielded(future), lambda f: f.result()
                )
        except Exception:
            app_log.error("Error in connection callback", exc_info=True)
def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('--port', '-p', default=8080, type=int,
	                    help='Port to use')
	args = parser.parse_args()

	try:
	    server_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
	    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	    # server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BUFFER_SIZE)

	    server_socket.bind(('', args.port))
	    server_socket.listen(1)

	    cache_dict = {}

	    print "Proxy server ready..."

	    while True:
	    	try:
	    		connection_socket = server_socket.accept()[0]

	    		t = Thread(target=handle_http, args=[cache_dict, connection_socket])
	    		t.setDaemon(1)
	    		t.start()
	    		t.join()
	    	except socket.error, e:
	    		print e
	    	finally:
	    		connection_socket.close()
예제 #14
0
파일: CoorNode.py 프로젝트: quanglys/BPA
def workWithUser(s : socket.socket):
    global parser
    global bUserConnect
    bUserConnect = True
    try:
        while 1:
            dataRecv = s.recv(1024).decode()
            if (dataRecv == ''):
                return
    except socket.error:
        return
    finally:
        bUserConnect = False
        s.close()
예제 #15
0
def run_server(server_port):
    """Run the UDP pinger server
    """

    # Create the server socket (to handle UDP requests using ipv4), make sure
    # it is always closed by using with statement.
    server_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)

    # The socket stays connected even after this script ends. So in order
    # to allow the immediate reuse of the socket (so that we can kill and
    # re-run the server while debugging) we set the following option. This
    # is potentially dangerous in real code: in rare cases you may get junk
    # data arriving at the socket.
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Set the server port
    server_socket.bind(("", server_port))

    # Start accepting ping requests
    print ("Ping server ready on port", server_port)
    while True:
        # Receive message and send one back
        _, client_address = server_socket.recvfrom(1024)
        server_socket.sendto("Pong".encode(), client_address)

    return 0
예제 #16
0
 def __init__(self, runner: 'BaseRunner', sock: socket.socket, *,
              shutdown_timeout: float=60.0,
              ssl_context: Optional[SSLContext]=None,
              backlog: int=128) -> None:
     super().__init__(runner, shutdown_timeout=shutdown_timeout,
                      ssl_context=ssl_context, backlog=backlog)
     self._sock = sock
     scheme = 'https' if self._ssl_context else 'http'
     if hasattr(socket, 'AF_UNIX') and sock.family == socket.AF_UNIX:
         name = '{}://unix:{}:'.format(scheme, sock.getsockname())
     else:
         host, port = sock.getsockname()[:2]
         name = str(URL.build(scheme=scheme, host=host, port=port))
     self._name = name
예제 #17
0
파일: pyclip.py 프로젝트: hyshka/dotfiles
def listen_for_data(sock: socket.socket) -> None:
    """Make the socket listen for data forever."""
    host = 'localhost'
    port = 41401
    sock.bind((host, port))
    sock.listen(1)
    while True:
        print('Waiting...')
        conn, addr = sock.accept()
        print(f'Connection from {addr}')
        if addr[0] != '127.0.0.1':
            continue
        with conn:
            data = receive_all(conn)
            parse_data(data)
예제 #18
0
파일: CoorNode.py 프로젝트: quanglys/BPA
def addNewNode(s : socket.socket, orderNode):
    global lockCount
    global lockLst, eps, numNode, k, evnValidate, nodeRecv

    try:
        #receive name of the node
        dataRecv = s.recv(1024).decode()
        addNetworkIn(len(dataRecv))
        try:
            if (dataRecv != ''):
                arg = parser.parse_args(dataRecv.lstrip().split(' '))
                nameNode = arg.name[0]
                if (numNode == 0):
                    numNode = arg.num_node[0]
                    for i in range(numNode):
                        nodeRecv.append(False)
        except socket.error as e:
            print('Error: ' + str(e))
            return

        lockLst.acquire()
        lstSock.append(s)
        lstName.append(nameNode)
        lockLst.release()

        if (orderNode == NUMBER_NODE):
            evnInitComplete.set()

    except socket.error:
        pass
예제 #19
0
파일: __init__.py 프로젝트: giflw/afn-tools
 def connect(self, attempts=1):
     """
     Connects to the Autobus server. The specified number of attempts will
     be made to re-establish a connection, each time waiting an amount of
     time that increments itself up to 20 seconds. If attempts is None, an
     infinite number of attempts will be made. Once a connection has been
     established, this method returns. If it fails to establish a
     connection, an exception will be raised.
     """
     if attempts == 0:
         attempts = None
     progress = 0
     delay = 0.1
     delay_increment = 1.5
     while (attempts is None or progress < attempts) and not self.is_shut_down:
         progress += 1
         delay *= delay_increment
         if delay > 20:
             delay = 20
         self.socket = Socket()
         try:
             self.socket.connect((self.host, self.port))
         except:
             sleep(delay)
             continue
         with self.on_connect_lock:
             self.connection_established()
         return
     raise Exception("Couldn't connect")
예제 #20
0
def client_socket_thread(address, client_socket: socket.socket,
                         message_queue: queue.Queue,
                         new_observer_queue_queue: queue.Queue,
                         delete_observer_queue_queue: queue.Queue):
    next_state = ''
    tries = 0
    if kicked == 1:
        kick = 0		#reset kicking status
        return
    else:        
        nickname = address[0] + ':' + str(address[1])		#give them basic nickname of IP+port
        userlist.append(nickname)
        socketlist.append(client_socket)		#add name to both socket list and user list
        observer_queue = queue.Queue()
        new_observer_queue_queue.put((client_socket, observer_queue))
        client_sender(nickname, client_socket, message_queue, delete_observer_queue_queue)
    client_socket.close()
예제 #21
0
파일: rtkinter.py 프로젝트: hzmmzl/afn
def main():
    if len(sys.argv) <= 1:
        print "You need to specify the url of the application to display."
        return
    scheme, location = urlparse(sys.argv[1])[0:2]
    if scheme != "rtk":
        print ("Only rtk:// urls are supported for now. I might add an HTTP " "transport at some point in the future.")
    if ":" not in location:
        location += ":" + str(DEFAULT_PORT)
    host, port = location.split(":")
    port = int(port)
    socket = Socket()
    try:
        socket.connect((host, port))
    except SocketError, e:
        print "Error while connecting: " + str(e)
        return
def run_server(server_port):
	# Run UDP pinger server

	try:
		server_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

		server_socket.bind(('', server_port))

		print("Ping server ready on port", server_port)
		while True:
			_, client_address = server_socket.recvfrom(1024)
			server_socket.sendto("".encode(), client_address)
	finally:
		server_socket.close()

	return 0
예제 #23
0
파일: __init__.py 프로젝트: giflw/afn-tools
 def __init__(self, default_discoverers=True, default_publishers=True,
              port=None):
     """
     Creates a new bus. The bus will listen on the specified port; if none
     is specified (which is the usual case), a port will be chosen from the
     ports not currently in use on this computer.
     
     If default_discoverers is True (the default), a default set of
     discoverers will be installed, and likewise for default_publishers.
     Right now, this simply installs a autobus2.discovery.BroadcastPublisher
     and autobus2.discovery.BroadcastDiscoverer. Others might be added in
     the future.
     """
     # Number of times this bus has been __enter__'d. Allows it to be used
     # as a re-entrant context manager.
     self.context_enters = 0
     if port is None:
         port = 0
     # True once close() has been called
     self.closed = False
     # The TCP server that will listen for connections
     self.server = Socket()
     self.server.bind(("", port))
     # TODO: make the backlog configurable
     self.server.listen(100)
     self.port = self.server.getsockname()[1]
     # Lock that nearly everything bus-related locks on
     self.lock = RLock()
     # PropertyTable whose keys are service ids and whose values are
     # instances of autobus2.local.LocalService
     self.local_services = PropertyTable()
     self.local_services.global_watch(self.local_service_changed)
     # Map of ids of discovered services to DiscoveredService instances
     self.discovered_services = {}
     self.discovery_listeners = []
     # List of (filter, function) tuples, where filter is an info object
     # filter and function is a function to be notified when a matching
     # service is created or deleted
     self.service_listeners = []
     # Set of RemoteConnection instances that have been bound to a service
     self.bound_connections = set()
     # Set of discoverers registered on this bus
     self.discoverers = set()
     # Set of publishers registered on this bus
     self.publishers = set()
     if default_discoverers:
         self.install_discoverer(discovery.BroadcastDiscoverer())
     if default_publishers:
         self.install_publisher(discovery.BroadcastPublisher())
     Thread(name="autobus2.Bus.accept_loop", target=self.accept_loop).start()
     # Disable the introspection service for now. I'm seeing what would
     # happen if I have per-service introspection functions and objects, so
     # I'm disabling the bus-wide introspection service.
     # self._create_introspection_service()
     #
     # Register the bus as a service on itself.
     self.create_service({"type": "autobus.details", "pid": os.getpid()}, _IntrospectionService(self))
def _initialize_telnet(connection: socket.socket) -> None:
    logger.info('Initializing telnet connection')

    # Iac Do Linemode
    connection.send(IAC + DO + LINEMODE)

    # Suppress Go Ahead. (This seems important for Putty to do correct echoing.)
    # This will allow bi-directional operation.
    connection.send(IAC + WILL + SUPPRESS_GO_AHEAD)

    # Iac sb
    connection.send(IAC + SB + LINEMODE + MODE + int2byte(0) + IAC + SE)

    # IAC Will Echo
    connection.send(IAC + WILL + ECHO)

    # Negotiate window size
    connection.send(IAC + DO + NAWS)
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        # Get the SMTP banner
        sock.recv(2048)

        # Send a EHLO and wait for the 250 status
        sock.send(b'EHLO sslyze.scan\r\n')
        if b'250 ' not in sock.recv(2048):
            raise StartTlsError(self.ERR_SMTP_REJECTED)

        # Send a STARTTLS
        sock.send(b'STARTTLS\r\n')
        if b'220' not in sock.recv(2048):
            raise StartTlsError(self.ERR_NO_SMTP_STARTTLS)
예제 #26
0
 def original_addr(self, csock: socket.socket):
     ip, port = csock.getpeername()[:2]
     ip = re.sub(r"^::ffff:(?=\d+.\d+.\d+.\d+$)", "", ip)
     ip = ip.split("%", 1)[0]
     with self.lock:
         try:
             write((ip, port), self.wfile)
             addr = read(self.rfile)
             if addr is None:
                 raise RuntimeError("Cannot resolve original destination.")
             return tuple(addr)
         except (EOFError, socket.error):
             self._connect()
             return self.original_addr(csock)
예제 #27
0
 def __init__(self, write_function, port, bus, service_extra={}):
     """
     Creates a new sixjet server. write_function is the function to use to
     write data to the parallel port. port is the port on which the native
     protocol listener should listen. service_extra is an optionally-empty
     set of values that will be added to the Autobus 2's service info
     dictionary. (Keys such as type will be added automatically, but such
     keys present in service_extra will override the ones added
     automatically.)
     
     bus is the Autobus bus to use. You can usually just use:
     
     from autobus2 import Bus
     with Bus() as bus:
         server = SixjetServer(..., bus, ...)
         ...
     
     and things will work.
     
     If write_function is None, a new parallel.Parallel instance will be
     created, and its setData method used.
     """
     Thread.__init__(self)
     if write_function is None:
         import parallel
         self._parallel = parallel.Parallel()
         write_function = self._parallel.setData
     else:
         self._parallel = None
     # The event queue. Events can be pushed from any thread, but can only
     # be read and processed from the SixjetServer's run method.
     self.queue = Queue()
     # The list of remote native-protocol connections. This must only be
     # read and modified from the event thread.
     self.connections = []
     # The current states of all of the jets. This must only be read and
     # modified from the event thread.
     self.jet_states = [False] * 16
     # True to shut down the server. This shouldn't be modified; instead,
     # stop() should be called, which will post an event that sets this to
     # True.
     self.shut_down = False
     # The server socket listening on the native protocol port
     self.socket = Socket()
     self.socket.bind(("", port))
     # The Autobus service we're publishing
     self.service = self.bus.create_service(
             {"type": "sixjet", "sixjet.native_port": port},
             from_py_object=AutobusService(self))
예제 #28
0
 def listen(self):
     """
     Bind and listen.
     :return: The open socket.
     :rtype: socket.socket
     """
     address = (self.host, self.port)
     socket = Socket(AF_INET, SOCK_STREAM)
     socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
     socket.bind(address)
     socket.listen(5)
     log.info('listening on: %d', self.port)
     return socket
예제 #29
0
파일: tcp.py 프로젝트: mnot/thor
    def __init__(self, sock: socket.socket, host: bytes, port: int, loop: LoopBase = None) -> None:
        EventSource.__init__(self, loop)
        self.socket = sock
        self.host = host
        self.port = port
        self.tcp_connected = True  # we assume a connected socket
        self._input_paused = True  # we start with input paused
        self._output_paused = False
        self._closing = False
        self._write_buffer = []  # type: list[bytes]

        self.register_fd(sock.fileno())
        self.on("fd_readable", self.handle_readable)
        self.on("fd_writable", self.handle_writable)
        self.on("fd_close", self._handle_close)
예제 #30
0
    def recv(self, skt: socket.socket, nbytes: int, buf: bytes) -> Tuple[bytes, bytes]:
        while len(buf) < nbytes:
            data: bytes = b''
            try:
                data = skt.recv(max(nbytes - len(buf), 4096))
            except socket.timeout:
                logging.error("error: recv socket.timeout")
            except Exception as e:
                logging.error(f'error: recv exception: {e!s}')

            if data == b'':
                return b'', b''
            buf += data

        return buf[:nbytes], buf[nbytes:]
예제 #31
0
def read_socket(sock: socket) -> bytes:
    length = sock.recv(LEN_SIZE).decode()
    return sock.recv(int(length))
예제 #32
0
def _send(s: socket.socket, message: str) -> None:
    s.sendall(struct.pack('>Q', len(message)))
    s.sendall(message.encode())
    return
예제 #33
0
 def handle(self, soc: socket.socket):
     data = soc.recv(1048576)
     request = Request(data)
     res = b''
     if request.path == b'/sse':
         # sse protocol
         headers = {
             b'Content-Type': b'text/event-stream',
             b'Cache-Control': b'no-cache',
             b'Connection': b'keep-alive',
             b'Access-Control-Allow-Origin': b'*',
         }
         head = response(b'', headers)
         soc.send(head)
         while True:
             soc.send(b'data: ' + self.md5 + b'\n\n')
             time.sleep(1)
         soc.close()
         return
     elif request.path == b'/pmd':
         # push markdown
         self.content = request.body
         pd = parse.unquote(request.pathdata.decode("utf-8"))
         pt = os.path.dirname(pd[5:])
         self.title = os.path.basename(pd[5:]).encode("utf-8")
         self.scans.append(pt)
         self.md5 = hashlib.md5(self.content).hexdigest().encode("utf-8")
         res = response(b'OK')
     elif request.path == b'/title':
         res = response(self.title)
     elif request.path == b'/gmd':
         # get markdown
         res = response(self.content)
     elif request.path == b'/':
         body = self.getResources("/index.html")
         res = response(body,
                        {b'Content-Type': b'text/html; charset=UTF-8'})
     else:
         res = response(
             self.getResources(parse.unquote(request.path.decode("utf-8"))))
     soc.send(res)
     soc.close()
예제 #34
0
def modbusClose(sock: socket.socket) -> None:
    sock.close()
예제 #35
0
 def udt_send(self,newsocket:socket.socket,msg:Msg,rate = 0.95):
     # randnum = random.randint(0,100)
     # if randnum < rate * 100:
     newsocket.send(Msg.encode(msg))
예제 #36
0
def run_qemu(s1: socket.socket, s2: socket.socket,
             args: argparse.Namespace) -> None:
    argv = ['qemu-arm-static']

    if args.debug:
        argv += ['-g', '1234', '-singlestep']

    argv += [launcher_path]

    if args.trace:
        argv += ['-t']

    if args.model is not None:
        argv += ['-m', args.model]

    argv += ['-k', str(args.sdk)]

    # load cxlib only if available for the specified sdk
    cxlib = pkg_resources.resource_filename(
        __name__, f"/cxlib/{args.model}-cx-{args.sdk}.elf")
    if os.path.exists(cxlib):
        argv += ['-c', cxlib]

    extra_ram = ''
    app_path = getattr(args, 'app.elf')
    for lib in [f'main:{app_path}'] + args.library:
        name, lib_path = lib.split(':')
        load_offset, load_size, stack, stack_size, ram_addr, ram_size = get_elf_infos(
            lib_path)
        # Since binaries loaded as libs could also declare extra RAM page(s), collect them all
        if (ram_addr, ram_size) != (0, 0):
            arg = f'{ram_addr:#x}:{ram_size:#x}'
            if extra_ram and arg != extra_ram:
                logger.error(
                    "different extra RAM pages for main app and/or libraries!")
                sys.exit(1)
            extra_ram = arg
        argv.append(
            f'{name}:{lib_path}:{load_offset:#x}:{load_size:#x}:{stack:#x}:{stack_size:#x}'
        )

    if args.model == 'blue':
        if args.rampage:
            extra_ram = args.rampage
        if extra_ram:
            argv.extend(['-r', extra_ram])

    pid = os.fork()
    if pid != 0:
        return

    # ensure qemu is killed when this Python script exits
    set_pdeath(signal.SIGTERM)

    s2.close()

    # replace stdin with the socket
    os.dup2(s1.fileno(), sys.stdin.fileno())

    # handle both BIP39 mnemonics and hex seeds
    if args.seed.startswith("hex:"):
        seed = bytes.fromhex(args.seed[4:])
    else:
        seed = mnemonic.Mnemonic.to_seed(args.seed)

    os.environ['SPECULOS_SEED'] = binascii.hexlify(seed).decode('ascii')

    if args.deterministic_rng:
        os.environ['RNG_SEED'] = args.deterministic_rng

    logger.debug(f"executing qemu: {argv}")
    try:
        os.execvp(argv[0], argv)
    except FileNotFoundError:
        logger.error('failed to execute qemu: "%s" not found' % argv[0])
        sys.exit(1)
    sys.exit(0)
예제 #37
0
def socket_receive(sock: socket.socket, bufsize: int = BUFFERSIZE) -> str:
    # return socket.recv(bufsize)  # Python 2
    return sock.recv(bufsize).decode('ascii')  # Python 3
예제 #38
0
    def __thread_connection(conn: socket.socket) -> None:
        """Inbound connection handler"""

        with conn:
            conn.sendall(b"\nStack CLI...\n\n")

            while True:
                message = conn.recv(1024).lower().strip()

                if message == b"exit":
                    break

                if message == b"":
                    continue
                """
                if message.lower().strip() == b"show tcp sessions":
                    message = b"\n"
                    for session in stack.tcp_sessions:
                        message += bytes(str(session), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)
                """

                if message.lower().strip() == b"show ipv6 host":
                    message = b"\n"
                    for ip6_host in stack.packet_handler.ip6_host:
                        message += bytes(str(ip6_host), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                elif message.lower().strip() == b"show ipv6 unicast":
                    message = b"\n"
                    for ip6_unicast in stack.packet_handler.ip6_unicast:
                        message += bytes(str(ip6_unicast), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                elif message.lower().strip() == b"show ipv6 multicast":
                    message = b"\n"
                    for ip6_multicast in stack.packet_handler.ip6_multicast:
                        message += bytes(str(ip6_multicast), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                elif message.lower().strip() == b"show ipv4 host":
                    message = b"\n"
                    for ip4_host in stack.packet_handler.ip4_host:
                        message += bytes(str(ip4_host), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                elif message.lower().strip() == b"show ipv4 unicast":
                    message = b"\n"
                    for ip4_unicast in stack.packet_handler.ip4_unicast:
                        message += bytes(str(ip4_unicast), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                elif message.lower().strip() == b"show ipv4 mulicast":
                    message = b"\n"
                    for ip4_multicast in stack.packet_handler.ip4_multicast:
                        message += bytes(str(ip4_multicast), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                elif message.lower().strip() == b"show ipv4 broadcast":
                    ip4_broadcast = b"\n"
                    for address in stack.packet_handler.ip4_broadcast:
                        message += bytes(str(ip4_broadcast), "utf-8") + b"\n"
                    message += b"\n"
                    conn.sendall(message)

                else:
                    conn.sendall(b"Syntax error...\n")
예제 #39
0
def write_object(obj: Any, conn: socket.socket) -> None:
    dump = dumps(obj)
    conn.sendall(dump + b"\r\n")
예제 #40
0
 def __init__(self, host, port, blocking=False):
     socket = Socket()
     socket.connect((host, port))
     super().__init__(connection=socket, blocking=blocking)
예제 #41
0
async def async_accept(sock: socket.socket) -> Tuple[socket.socket, Address]:
    await Can(Action.READ, sock)
    return sock.accept()
예제 #42
0
 def read(conn: socket.socket):
     res = AuthResponse()
     res.ver = conn.recv(1)
     res.method = conn.recv(1)
     return res
예제 #43
0
async def async_send(sock: socket.socket, data: bytes) -> int:
    await Can(Action.WRITE, sock)
    return sock.send(data)
예제 #44
0
def socket_sendall(sock: socket.socket, data: str) -> None:
    # return socket.sendall(data)  # Python 2
    return sock.sendall(data.encode('ascii'))  # Python 3
예제 #45
0
 def send_obj(sock: socket.socket, data: Dict[str, Any]):
     str_data: str = json.dumps(data) + " " + END_FLAG
     sock.sendall(str_data.encode())
예제 #46
0
def socket_send(sock: socket.socket, data: str) -> int:
    # return socket.send(data)  # Python 2
    return sock.send(data.encode('ascii'))  # Python 3
예제 #47
0
def modbusSend(sock: socket.socket, data: bytes) -> None:
    sock.sendall(data)
예제 #48
0
def tcp_send(data, conn: socket.socket, delimiter: bytes = b'\n'):
    data_byte = str(data).encode()

    data_length = len(data_byte)
    conn.send(str(data_length).encode() + delimiter + data_byte)
예제 #49
0
 def rdt_rcv(self, newsocket: socket.socket, rcvpkt:list):
     msg = newsocket.recv(65510)
     ## not allow me to use Msg here
     newmsg = Msg.decode(msg)
     rcvpkt.append(newmsg)
예제 #50
0
파일: debug.py 프로젝트: tklapperich/zulip
def tracemalloc_listen_sock(sock: socket.socket) -> None:
    logger.debug('pid {}: tracemalloc_listen_sock started!'.format(
        os.getpid()))
    while True:
        sock.recv(1)
        tracemalloc_dump()
예제 #51
0
 def recvMsg(self, conn: socket.socket):
     msgLen = conn.recv(self.HEADER).decode(self.FORMAT)
     if msgLen != '':
         return conn.recv(int(msgLen)).decode(self.FORMAT)
     else:
         return ''
예제 #52
0
 def recive_time(self, socket_: socket.socket) -> None:
     """ Получить время от сервера"""
     payload = socket_.recv(1024)
     socket_.close()
     print('Received time is {}'.format(payload.decode('ascii')))
예제 #53
0
def write_message(conn: socket.socket, message: bytes):
    """ Send length prefixed frame """
    message_header = len(message).to_bytes(length=4, byteorder='big', signed=False)
    # print("Write Message Header:", message_header, "Len:", len(message), "headerLen:", len(message_header))
    # print("Expected:", int.from_bytes(message_header, byteorder='big', signed=False))
    conn.sendall(message_header + message)
예제 #54
0
파일: server.py 프로젝트: agdsn/hades
    def _receive(
        self,
        request: socket.socket,
    ) -> Tuple[Tuple[TextIO, TextIO, TextIO], List[bytes], Dict[bytes, bytes]]:
        streams: List[TextIO] = []
        # Offset of the buffer relative to the input stream
        offset = 0
        # Number of filled bytes in the buffer
        available = 0
        # Initialize parser
        buffer = self.buffer
        buffer.seek(0, os.SEEK_SET)
        parser = self.parse_request(buffer, 0)
        needed = next(parser)
        with contextlib.ExitStack() as stack:
            while needed:
                # Prepare buffer for refill
                parsed = buffer.tell()
                offset += parsed
                buffer.move(0, parsed, available - parsed)
                buffer.seek(0, os.SEEK_SET)
                available -= parsed
                if needed > self.max_packet_size:
                    parser.throw(
                        BufferTooSmallError(
                            needed,
                            self.max_packet_size,
                            offset=offset,
                        ))
                # Leave space for a trailing zero byte
                size, ancdata, msg_flags, _ = request.recvmsg_into(
                    (memoryview(buffer)[available:-1], ),
                    socket.CMSG_LEN(3 * SIZEOF_INT),
                    socket.MSG_CMSG_CLOEXEC,
                )
                available += size
                # Ensure that a trailing zero byte exists
                buffer[available] = 0

                streams.extend(
                    stack.enter_context(stream)
                    for stream in self.parse_ancillary_data(
                        ancdata, ["r", "w", "w"]))

                if msg_flags & socket.MSG_CTRUNC:
                    raise ProtocolError("Truncated ancillary data")

                try:
                    needed = parser.send((buffer, available))
                except StopIteration as e:
                    _, _, (argv, environ) = e.value
                    if buffer.tell() < available:
                        raise ProtocolError(
                            "{} byte(s) left over after parsing".format(
                                available - buffer.tell()))
                    needed = 0
                except BaseParseError as e:
                    raise e.with_offset(offset + buffer.tell())
                else:
                    # Remote end closed/shut down writing
                    if needed > 0 and size == 0:
                        # Raise an error in the parser to produce an error with
                        # proper message
                        parser.throw(
                            UnexpectedEOFError(
                                needed,
                                available,
                                offset=offset + buffer.tell(),
                            ))

            if not streams:
                raise ProtocolError("No file descriptors received")
            if len(streams) != 3:
                raise ProtocolError(
                    "Expected to receive exactly 3 file descriptors")
            stdin = ensure_stream_readable(streams[0], 'stdin')
            stdout = ensure_stream_writable(streams[1], 'stdout')
            stderr = ensure_stream_writable(streams[2], 'stderr')
            # Clear the stack
            stack.pop_all()
            return (stdin, stdout, stderr), argv, environ
예제 #55
0
def write_socket(sock: socket, msg: str or bytes) -> None:
    if isinstance(msg, str):
        sock.send(
            str(len(msg.encode())).zfill(LEN_SIZE).encode() + msg.encode())
    else:
        sock.send(str(len(msg)).zfill(LEN_SIZE).encode() + msg)
예제 #56
0
    def shakehands(self, client:socket.socket, addr:tuple)->Connection:
        '''完成socks握手过程
        '''
        # 客户端握手
        ver, l = struct.unpack('!BB', client.recv(2))
        assert ver in (self.SOCKS_VERSION_4, self.SOCKS_VERSION_5), f"Unsupported protocol type `{ver}`"
        assert l > 0, "Wrong nmethods"
        methods = struct.unpack("!"+"B"*l, client.recv(l)) # 备用

        # 无验证方式
        client.sendall(struct.pack('!BB', ver, 0))

        # 处理客户端转发请求
        ver, cmd, rsv, atyp = struct.unpack('!BBBB', client.recv(4))
        assert ver in (self.SOCKS_VERSION_4, self.SOCKS_VERSION_5), f"Unsupported protocol type `{ver}`"
        assert rsv == 0, f"Reserved field must be 0, actually `{rsv}`"
        dst_addr = ''
        dst_port = 0
        if atyp == self.ATYP_IPV4:
            dst_addr = socket.inet_ntoa(client.recv(4))
        elif atyp == self.ATYP_IPV6:
            dst_addr = socket.inet_ntop(socket.AF_INET6, client.recv(16))
        elif atyp == self.ATYP_FQDN:
            l = struct.unpack("!B", client.recv(1))[0]
            assert l > 0, f"ATYP is FQDN, but domain length `{l}` is invalid"
            dst_addr = self._handle_domain(client.recv(l).decode())
        else:
            raise AssertionError(f"Unknown atyp `{atyp}`")
        dst_port = struct.unpack('!H', client.recv(2))[0]

        conn = Connection(client, dst_addr, dst_port, addr[0], addr[1], 
            6 if atyp == self.ATYP_IPV6 else 4, self)
        if cmd == self.CMD_CONNECT:
            code = conn.exec_action(Connection.ACTION_CONNECT)
            if code == 0:# 转发成功
                client.sendall(struct.pack("!BBBB", ver, 0, rsv, self.ATYP_IPV4)+
                    socket.inet_pton(socket.AF_INET, self.host)+struct.pack("!H", self.port))
                client.setblocking(False) # 设置非阻塞模式
                return conn
            else:
                client.sendall(struct.pack("!BBBB", ver, code, rsv, self.ATYP_IPV4)+
                    socket.inet_pton(socket.AF_INET, self.host)+struct.pack("!H", self.port))
                raise AssertionError("Connection forward failed!")
        elif cmd == self.CMD_BIND:
            pass
        elif cmd == self.CMD_UDP_ASSOCIATE:
            pass
        else:
            raise AssertionError(f"Unknown cmd `{cmd}`")

        return None
예제 #57
0
def recv(sock: socket.socket):
    while True:
        msg = sock.recv(1024)
        print(f'\nrecv >> {msg.decode(ENCODING)}')
예제 #58
0
def http_handle(connection, address):

    request_string = connection.recv(1024).decode('ascii')
    print( request_string )
    print( address )

    response = ""

    assert not isinstance(request_string, bytes)

    host = ""
    request_data = {}


    try:

        request_split = request_string.split("\r\n")

        request_data["request_type"] = request_split[0]

        for index in range(1, len(request_split)):
            if (request_split[index] == ""):
                continue
            request_data[request_split[index].split(": ")[0]] = request_split[index].split(": ")[1]

        host += request_data["request_type"].split(" ")[1]
        #port_num = request_data["Host"].split(":")[1]


    except:

        response += "HTTP/1.0 400 Bad Request\n"
        response += "Content-Type: text/html; encoding=ascii\n"
        response += "Content-Length: %d\n" % len( "<html><body><h1>400: Bad Request </h1></body></html>")
        response += "Connection: close\n"
        response += "\n"
        response += "<html><body><h1>400: Bad Request </h1></body></html>"
        connection.send(response.encode("ascii"))
        connection.close()
        return


    if (not "GET" in request_data["request_type"]):

        if (not "HEAD" in request_data["request_type"] and \
            not "POST" in request_data["request_type"] and \
            not "PUT" in request_data["request_type"] and \
            not "DELETE" in request_data["request_type"] and \
            not "TRACE" in request_data["request_type"] and \
            not "CONNECT" in request_data["request_type"]):

            response += "HTTP/1.0 400 Bad Request\n"
            response += "Content-Type: text/html; encoding=ascii\n"
            response += "Content-Length: %d\n" % len( "<html><body><h1>400: Bad Request </h1></body></html>")
            response += "Connection: close\n"
            response += "\n"
            response += "<html><body><h1>400: Bad Request </h1></body></html>"

        else:

            response += "HTTP/1.0 501 Not Implemented\n"
            response += "Content-Type: text/html; encoding=ascii\n"
            response += "Content-Length: %d\n" % len( "<html><body><h1>501: Not Implemented </h1></body></html>")
            response += "Connection: close\n"
            response += "\n"
            response += "<html><body><h1>501: Not Implemented </h1></body></html>"

        connection.send(response.encode("ascii"))
        connection.close()
        return

    '''
    removed from webserver

    # try:
    #     new_connection = Socket(socket.AF_INET, socket.SOCK_STREAM)
    #     new_connection.connect((host, 80))
    #     new_connection.sendall("GET / HTTP/1.0\r\n\r\n")
    #     request_string = new_connection.recv(1024)
    #     new_connection.close()
    #
    #     temp_host = host.replace("http://", "")
    #     if ("/" in temp_host):
    #         path = temp_host[temp_host.find("/")+1 ::]
    #     else:
    #         raise FileNotFoundError
    #
    #     file = open(path, 'r')
    #     file_data = file.read()
    #     file.close()
    #
    #     response += "HTTP/1.0 200 OK\n"
    #     response += "Content-Type: text/html; encoding=ascii\n"
    #     response += "Content-Length: %d\n" % len(file_data)
    #     response += "Connection: close\n"
    #     response += "\n"
    #     response += file_data
    #
    # except FileNotFoundError:
    #     response += "HTTP/1.0 404 Not Found\n"
    #     response += "Content-Type: text/html; encoding=ascii\n"
    #     response += "Content-Length: %d\n" % len( "<html><body><h1>404: Not Found</h1></body></html>")
    #     response += "Connection: close\n"
    #     response += "\n"
    #     response += "<html><body><h1>404: Not Found</h1></body></html>"
    '''

    try:
        print( host )
        new_connection = Socket(socket.AF_INET, socket.SOCK_STREAM)
        new_connection.connect((host.replace("http://", "").replace("https://", ""), 80))
        new_connection.sendall(str.encode("GET /index.html HTTP/1.0\r\nHost: %s\r\n\r\n" % host.replace("http://", "").replace("https://", "")))
        request_string = new_connection.recv(1024).decode("ascii")
        new_connection.close()

        response += request_string

        connection.send(response.encode("ascii"))
        connection.close()
        return

    except:
        response += "HTTP/1.0 400 Bad Request\n"
        response += "Content-Type: text/html; encoding=ascii\n"
        response += "Content-Length: %d\n" % len( "<html><body><h1>400: Bad Request </h1></body></html>")
        response += "Connection: close\n"
        response += "\n"
        response += "<html><body><h1>400: Bad Request </h1></body></html>"
        connection.send(response.encode("ascii"))
        connection.close()
        return
예제 #59
0
async def async_recv(sock: socket.socket, num: int) -> bytes:
    await Can(Action.READ, sock)
    return sock.recv(num)
예제 #60
0
def lector(socket_cliente: socket.socket):
    datos_cliente = socket_cliente.recv(100)
    os.write(archivo, datos_cliente)
    socket_cliente.shutdown(socket.SHUT_RDWR)