Ejemplo n.º 1
0
 def _send_message_to_client(self, client, message):
     send_message(client.sock, message)
     log_info("sended {len} bytes to {client}: {data}".format(
         len=len(message),
         client=client,
         data=message
     ))
Ejemplo n.º 2
0
def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((server_addr, server_port))
    s.listen(10)

    while True:
        client, (client_addr, client_port) = s.accept()
        print("Client connected from %s") % client_addr

        try:
            (method, bodylen, methodparams) = protocol.read_firstpart(client)
            body = ""
            if method == "LIST" and bodylen > 0:
                print("malformed bodylength")
                client.close()
            else:
                if bodylen > 0:
                    body = protocol.read_body(client, bodylen)
                re = protocol.Message(method, methodparams, body)
                response = handle_request(re, client)
                protocol.send_message(client, response)
        except protocol.InvalidMethodException:
            print("received malformed header from the client")

        client.close()
Ejemplo n.º 3
0
    def _input_loop(self):
        # refactor this
        while True:
            # Linux epoll magic
            inputs_ready_to_read, _, _ = select.select([self.server_socket, sys.stdin], [], [])

            for sock in inputs_ready_to_read:
                if sock == self.server_socket:
                    data = recv_until_end_messages(sock)

                    if data:
                        offer_cid, kfrags = self._parse_response(data)
                        ciphertext, capsule = self.get_offer_from_blockchain(offer_cid)
                        self._get_raw_offer(ciphertext, capsule, kfrags)

                    else:
                        print("Disconnected from server")
                        sys.exit()
                else:
                    #data = sys.stdin.readline()[:-1]
                    pub_key = self.bobs_public_key.to_bytes()
                    eth_key = "~"

                    request = self._prepare_req(eth_key, pub_key)

                    send_message(self.server_socket, request)
Ejemplo n.º 4
0
def main():

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((server_addr, server_port))
    s.listen(5)

    def clean_exit(signal, frame):
        print "ctrl+c pressed"
        s.close()
        sys.exit()

    # when ctrl+c is pressed, call clean_exit function
    signal.signal(signal.SIGINT, clean_exit)

    while True:
        client, (client_addr, client_port) = s.accept()
        print "client connected from %s" % client_addr

        try:
            (method, bodylen, methodparams) = protocol.read_header(client)
            body = ""
            if bodylen > 0:
                body = protocol.read_body(client, bodylen)
            request = protocol.Message(method, methodparams, body)
            response = handle_request(request, client)
            protocol.send_message(response, client)
        except protocol.InvalidMethodException:
            print "received invalid method from %s, disconnecting the client..." % (client_addr)
        except protocol.MalformedHeaderException:
            print "received malformed header the %s, disconnecting the client" % (client_addr)

        client.close()
    def _handle_expression_request(self, exprRequest, sock):
        """Get all units from DB, matched by exprRequest and send response."""

        expr = exprRequest['Expression']
        object_type = exprRequest['Type']

        report = get_matched_records(object_type, expr)

        try:
            expressionsLenghtMes = ExpressionsLenghtMes()
            expressionsLenghtMes['Lenght'] = len(report)
            p.send_message(expressionsLenghtMes, sock)

            for record in report:
                uMes = ExpressionUnitMes()
                uMes['Agent'] = record[0]
                uMes['Space'] = record[1]
                uMes['Object'] = record[2]
                uMes['String'] = record[3]

                p.send_message(uMes, sock)
        except Exception as e:
            log.error("Can't send report: %s" % (e))
        finally:
            sock.close()
Ejemplo n.º 6
0
def _handle_red(game_state: GameState, connection: protocol.ConnectionInfo) -> GameState:
    col, move = _get_inputs(game_state)

    if move == 'p':
        game_state = connectfour.pop(game_state, col - 1)
        protocol.send_message(connection, 'POP ' + str(col))


    elif move == 'd':
        game_state = connectfour.drop(game_state, col - 1)
        protocol.send_message(connection, 'DROP ' + str(col))

    return game_state
Ejemplo n.º 7
0
def main():
    if len(sys.argv) < 2:
        print("not enough parameters")
        print("syntax: ADDRESS [PORT]")
        sys.exit()

    server_addr = sys.argv[1]
    server_port = 0

    if len(sys.argv) == 2:
        server_port = 65432
    else:
        server_port = int(sys.argv[2])

    while True:
        choice = main_menu()
        print("Connecting to %s %d") % (server_addr, server_port)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((server_addr, server_port))

        if choice == MAIN_MENU_CHOICE_DOWNLOAD:
            filename = raw_input("Filename: ")
            request = protocol.Message("DOWNLOAD", filename, "")
            protocol.send_message(s, request)

            (method, bodylen, methodparams) = protocol.read_firstpart(s)

            if method == "FILE":
                f = open(filename, "w")
                shutil.copyfileobj(s.makefile(), f)
                f.close()
                print("File downloaded succesfully!!")
            else:
                print("An error occured")

        if choice == MAIN_MENU_CHOICE_LIST:
            filepath = raw_input("Filepath: ")
            request = protocol.Message("LIST", filepath, "")
            protocol.send_message(s, request)

            (method, bodylen, methodparams) = protocol.read_firstpart(s)

            if method == "LISTRESPONSE":
                print(s.recv(1024))
            else:
                print("An error occured")
Ejemplo n.º 8
0
def send_waiting_messages(writeable_sockets):
    for message_block in MESSAGES_TO_SEND:
        """
        CR (misha): 
            WTF!!!!!!!!! are you seriously modify a list while iterating over it????????
            This is a huge problem!!!!!!!!!
            
            IN[1]: a = [1,2,3,4,5]
            IN[2]: for b in a:
              ...:     a.remove(b)
              ...:     print(b)
              ...:     
            OUT[2]:1
                   3
                   5
        """
        """
        CR (misha): I couldn't find easy documentation of how a message should look like
        """
        sender, message, recipient = message_block
        """
        CR (misha): here `formatted_message` should is a better name
        
        also dont use string cat, use format instead 
        """
        message = datetime.now().strftime("%H:%M:%S") + " " + message

        if recipient:
            if sender == "server":
                protocol.send_message(recipient, message)
                continue
            if recipient not in writeable_sockets:
                continue

            protocol.send_message(recipient, message)

            if PRINT_PRIVATE_MESSAGES:
                print_private_messages(recipient, message)
            """
            CR (misha):
                Should this continue be here?

                EDIT:
                Ohh f**k, reading the rest of the function made it clear
                this entire 'if' is for privet messages, consider making it an helper function
                (keep the continue
            """
            continue

        """
        CR (misha): Why is there a comma?
        """
        print message

        for sock in writeable_sockets:
            if sock == CLIENTS.get(sender):
                continue
            protocol.send_message(sock, message)
    global MESSAGES_TO_SEND
    MESSAGES_TO_SEND = []
def handleConnection(c):
    name = threading.currentThread().getName()
    while True:

        try:
            # false is returned from protocol if client closes connection
            parts = protocol.read_firstpart(c)
            if parts != False:
                if parts[0] == "LIST" and parts[1] > 0:
                    print("malformed bodylength")
                    c.close()
                else:
                    if parts[0] == "LIST":
                        response = listItems(c, name)
                        protocol.send_message(c, response)

                    elif parts[0] == "ADD":
                        body = protocol.read_body(c, parts[1])
                        response = addItem(c, body, name)
                        protocol.send_message(c, response)

                    elif parts[0] == "DONE":
                        response = removeItem(c, int(parts[2][0]), name)
                        protocol.send_message(c, response)
            else:
                break

        except protocol.InvalidMethodException:
            print("Received malformed header from the client")

    print("Closing client connection to %s" % name)
    c.close()
Ejemplo n.º 10
0
    def call(self, dest, method, **args):
        # How to detect socket errors? how to resend message and reconnect
        # socket?
        # Connect socket

        if dest not in self._locks:
            self._locks[dest] = thread.allocate_lock()
        self._locks[dest].acquire()

        if dest not in self._sockets:
            self._connect(dest)

        # Pack message
        req = OODict()
        req.method = method
        for k, v in args.items():
            req[k] = v

        # Lock id here
        self._id_lock.acquire()
        req._id = self._id
        self._id += 1
        self._id_lock.release()

        retry = 0
        while True:
            try:
                protocol.send_message(self._sockets[dest], req)
                break
            except socket.error, err:
                # There must be something wrong with this socket
                # Create a new one
                self._connect(dest)
                # Only retry when connected, 
                if retry >= self._send_error_retry:
                    self._locks[dest].release()
                    raise exception.NoMoreRetryError('socket send error')
                # Do not need sleep here
                retry += 1
Ejemplo n.º 11
0
    def send(self, message):

        protocol.send_message(self.client, message)
Ejemplo n.º 12
0
 def _send_message_to_client(self, client, message):
     # TODO old fn
     data = pickle.dumps(message)
     send_message(client.sock, data)
     log_info("sended {len} bytes to {client}: {data}".format(
         len=len(message), client=client, data=message))
Ejemplo n.º 13
0
def main():
	if len(sys.argv) < 2:
		print "not enough parameters."
		print "usage: %s ADDRESS [PORT]"
		sys.exit(1)

	server_addr = sys.argv[1]
	server_port = 0

	if len(sys.argv) == 2:
		server_port = 1234
	else:
		server_port = int(sys.argv[2])

	while True:
		choice = main_menu()
		print "Connecting to %s:%d..." % (server_addr, server_port)
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((server_addr, server_port))

		if choice == MAIN_MENU_CHOICE_LIST:
			folder = "."
			request = protocol.Message("LIST", folder, "")
			protocol.send_message(request, s)

			(method, bodylen, methodparams) = protocol.read_header(s)

			if method == "LISTRESPONSE":
				body = ""
				if bodylen > 0:
					body = protocol.read_body(s, bodylen)

				files = body.split("\r\n")
				print "files:"
				i = 1;
				for file in files:
					print i , " %s" % file
					i=i+1
			else:
				print "an error occured: %s" % methodparams[0]

		elif choice == MAIN_MENU_CHOICE_DOWNLOAD:
			filename = raw_input("filename: ")
			request = protocol.Message("DOWNLOAD", filename, "")
			protocol.send_message(request, s)

			(method, bodylen, methodparams) = protocol.read_header(s)

			if method == "FILE":
				# write the body to a file of the same name
				print "Sana lisatty"
			else:
				print "an error occured: %s" % methodparams[0]
		elif choice == MAIN_MENU_CHOICE_DELETE:
			filename = raw_input("filename: ")
			request = protocol.Message("DELETE", filename, "")
			protocol.send_message(request, s)

			(method, bodylen, methodparams) = protocol.read_header(s)

			if method == "DELETERESPONSE":
				# write the body to a file of the same name
				print "Sana poistettu"
			else:
				print "an error occured: %s" % methodparams[0]

		s.close()
Ejemplo n.º 14
0
    def send(self, message):

        protocol.send_message(self.socket, message)