Ejemplo n.º 1
0
 def unpack(self, u: xdrlib.Unpacker):
     last = u.unpack_uint() + u.get_position()
     if u.get_position() < last:
         self.time_A = struct.unpack('>Q', u.unpack_fopaque(8))[0]
     if u.get_position() < last:
         self.time_B = struct.unpack('>Q', u.unpack_fopaque(8))[0]
     u.set_position(last)
Ejemplo n.º 2
0
    def unpack(self, u: xdrlib.Unpacker):
        last = u.unpack_uint() + u.get_position()
        ret = ReturnCode.unpack(u)

        if ret == ReturnCode.OK:
            last2 = u.unpack_uint() + u.get_position()
            if u.get_position() < last2:
                self.digest = u.unpack_fopaque(20)
            if u.get_position() < last2:
                self.salt = u.unpack_fopaque(8)
            u.set_position(last2)
        u.set_position(last)
Ejemplo n.º 3
0
 def run(self):
     while self.server_running:
         potential_read = [self.server_socket]
         if self.client is not None:
             potential_read.append(self.client)
         try:
             ready_to_read, ready_to_write, in_erro = select.select(
                 potential_read, [], [])
             if self.server_socket in ready_to_read:
                 conn, addr = self.server_socket.accept()
                 self.client = conn
                 print('New connection from ', addr)
             elif self.client in ready_to_read:
                 # self.client.recv_into(self.buffer, 512)
                 recv = self.client.recv(128)
                 self.buffer += recv
                 if len(recv) == 0:
                     print('Disconnection from client')
                     self.client.close()
                     self.client = None
                     self.buffer = ''
                     continue
                 unpack = Unpacker(self.buffer)
                 if len(self.buffer) >= unpack.unpack_int():
                     unpack.set_position(0)
                     size = unpack.unpack_int()
                     cmd = unpack.unpack_int()
                     if cmd == ServerMouseController.PACKET_MOVE:
                         # Mouse move control
                         x = unpack.unpack_float()
                         y = unpack.unpack_float()
                         print(size, cmd, x, y)
                         self.mouse_controller.move(
                             self.mouse_controller.position()[0] - x,
                             self.mouse_controller.position()[1] - y)
                     elif cmd == ServerMouseController.PACKET_CLICK:
                         # Mouse click control
                         button = unpack.unpack_int()
                         nb_click = unpack.unpack_int()
                         print(size, cmd, button, nb_click)
                         self.mouse_controller.click(
                             self.mouse_controller.position()[0],
                             self.mouse_controller.position()[1],
                             button,
                             nb_click)
                     elif cmd == ServerMouseController.PACKET_SCROLL:
                         # Mouse scrolling
                         x = unpack.unpack_float()
                         y = unpack.unpack_float()
                         print(size, cmd, x, y)
                         self.mouse_controller.scroll(
                             vertical=int(y), horizontal=int(x))
                     self.buffer = self.buffer[unpack.get_position():]
         except select.error as e:
             print(e)
     if self.client is not None:
         self.client.close()
     self.server_socket.close()
     print('Server stop')
Ejemplo n.º 4
0
 def get_tlv(wrapped_message):
     unpacker = Unpacker(wrapped_message)
     tag = unpacker.unpack_uint()
     message = unpacker.unpack_string()
     pos = unpacker.get_position()
     buff = unpacker.get_buffer()
     rest = buff[pos:]
     return tag, message, rest
Ejemplo n.º 5
0
    def unpack(self, u: xdrlib.Unpacker):
        self.needs_attention = u.unpack_bool()
        self.fixing = u.unpack_bool()
        self.wwn = u.unpack_opaque()
        self.management_class_name = u.unpack_string()
        self.storage_array_label = u.unpack_string().decode('utf-16be')
        self.boot_time = struct.unpack('>Q', u.unpack_fopaque(8))[0]
        self.fw_version = u.unpack_fopaque(4)
        self.app_version = u.unpack_fopaque(4)
        self.boot_version = u.unpack_fopaque(4)
        self.nvsram_version = u.unpack_string()
        self.fw_prefix = u.unpack_string()
        self.chassis_serial_number = u.unpack_string()
        self.event_configuration_data_version = u.unpack_string()

        self.array_attributes = []
        nb = u.unpack_uint()
        for i in range(nb):
            self.array_attributes.append(u.unpack_uint())
        self.res4 = []
        nb = u.unpack_uint()
        for i in range(nb):
            self.res4.append(u.unpack_uint())
        self.res5 = []
        nb = u.unpack_uint()
        for i in range(nb):
            self.res5.append(u.unpack_uint())
        self.res6 = []
        nb = u.unpack_uint()
        for i in range(nb):
            self.res6.append(u.unpack_uint())
        self.res7 = u.unpack_opaque()

        last = u.unpack_int()
        if last > 0:
            this.reserved1 = u.get_opaque()
            u.set_position(u.get_position() + last)
Ejemplo n.º 6
0
    def unpack(self, u: xdrlib.Unpacker):
        last = u.unpack_uint() + u.get_position()
        if u.get_position() < last:
            last2 = u.unpack_uint()
            self.canditate_selection_type = CandidateSelectionType(
                u.unpack_uint())
            if self.canditate_selection_type == CandidateSelectionType.CANDIDATE_SEL_MANUAL:
                last3 = u.unpack_uint() + u.get_position()
                if u.get_position() < last3:
                    nb = u.unpack_uint()
                    self.drive_refs = []
                    for i in range(nb):
                        self.drive_refs.append(u.unpack_fopaque(20))
                u.set_position(last3)
            u.set_position(last2)

        if u.get_position() < last:
            self.raid_level = RaidLevel(u.unpack_int())
        if u.get_position() < last:
            self.phyiscal_drive_type = PhysicalDriveType(u.unpack_int())
Ejemplo n.º 7
0
class trrParser:
    """ Parses .trr Gromacs trajectory file """
    def __init__(self, file):

        self.nframes = 0
        self.headers = []
        ##         header = {
        ##             "ir_size":None,
        ##             "e_size": None,
        ##             "box_size" :None,
        ##             "vir_size": None,
        ##             "pres_size": None,
        ##             "top_size ": None,
        ##             "sym_size ": None,
        ##             "x_size ": None,
        ##             "v_size ": None,
        ##             "f_size ": None,
        ##             "natoms ": None,
        ##             "step ": None,
        ##             "nre ": None,
        ##             "version":'GMX_trn_file',
        ##             "magicnum" :1993,
        ##             "bDouble ": None,
        ##             }
        self.file = file
        self.coords = []
        self.velocities = {}
        self.forces = {}

    def nFloatSize(self, h):

        nflsize = 0
        if h["box_size"]:
            nflsize = h["box_size"] / (DIM * DIM)
        elif h["x_size"]:
            nflsize = h["x_size"] / (h["natoms"] * DIM)
        elif h["v_size"]:
            nflsize = h["v_size"] / (h["natoms"] * DIM)
        elif h["f_size"]:
            nflsize = h["f_size"] / (h["natoms"] * DIM)
        else:
            print("Can not determine precision of trr file")

        if (nflsize != calcsize("f")) and (nflsize != calcsize("d")):
            print("Float size %d. Maybe different CPU?" % nflsize)

        return nflsize

    def read(self):
        fext = os.path.splitext(self.file)[-1]
        assert fext == ".trr"
        fp = open(self.file, "rb")
        self.data = data = fp.read()
        self.coords = []
        self.v = {}
        self.f = {}
        self.up = Unpacker(data)
        curpos = self.up.get_position()
        datasize = len(data)
        nframe = 0
        #each frame begins with a header
        while curpos < datasize:
            #print "current position:", curpos
            h = self.readHeader(nframe)
            self.headers.append(h)
            self.readData(nframe)
            nframe = nframe + 1
            curpos = self.up.get_position()
        #print "end of readTraj, cur position : %d, datazize: %d" %(self.up.get_position(), datasize)
        self.nframes = nframe
        if self.nframes:
            return 1
        else:
            return 0

    def readHeader(self, nframe):
        #print "reading header, frame %d" %nframe
        up = self.up
        header = {}
        header["magicnum"] = up.unpack_int()
        #print "magicnum: ", header["magicnum"]
        #1993
        i1 = up.unpack_int()
        #13
        version = up.unpack_string()
        #'GMX_trn_file'
        header["version"] = version
        #print "version:", version
        header["ir_size"] = up.unpack_int()
        #print "ir_size=", header["ir_size"]
        header["e_size"] = up.unpack_int()
        #print "e_size=", header["e_size"]
        header["box_size"] = up.unpack_int()
        #print "box_size=", header["box_size"]
        header["vir_size"] = up.unpack_int()
        #print "vir_size=", header["vir_size"]
        header["pres_size"] = up.unpack_int()
        #print "pres_size=", header["pres_size"]
        header["top_size"] = up.unpack_int()
        #print "top_size=", header["top_size"]

        header["sym_size"] = up.unpack_int()
        #print "sym_size=", header["sym_size"]

        header["x_size"] = up.unpack_int()
        #print "x_size=", header["x_size"]

        header["v_size"] = up.unpack_int()
        #print "v_size=", header["v_size"]

        header["f_size"] = up.unpack_int()
        #print "f_size=", header["f_size"]

        header["natoms"] = up.unpack_int()
        #print "natoms=", header["natoms"]
        header["step"] = up.unpack_int()
        #print "step=", header["step"]
        header["nre"] = up.unpack_int()
        #print "nre=", header["nre"]

        if self.nFloatSize(header) == calcsize("d"):
            header["bDouble"] = True
        else:
            header["bDouble"] = False

        if header["bDouble"]:
            header["time"] = up.unpack_double()
            header["lam"] = up.umpack_double()
        else:
            header["time"] = up.unpack_float()
            header["lam"] = up.unpack_float()

        #print "time = ", header["time"]
        #print "lambda = ", header["lam"]
        #print "natoms=%10d  step=%10d  time=%10g  lambda=%10g"% (header["natoms"],header["step"],header["time"],header["lam"])
        #print "current position:",  up.get_position()
        return header

    def readData(self, nframe):
        up = self.up
        h = self.headers[nframe]
        box = []
        if h["box_size"] != 0:
            for i in range(3):
                box.append(up.unpack_farray(3, up.unpack_float))
            #print " box (3x3):"
            #print box
            self.headers[nframe]["box"] = box
        pv = []
        if h["vir_size"] != 0:
            for i in range(3):
                pv.append(up.unpack_farray(3, up.unpack_float))
            #print "pv:"
            #print pv
            self.headers[nframe]["pv"] = pv
        if h["pres_size"] != 0:
            pv.append(up.unpack_farray(3, up.unpack_float))
            #print "pv:"
            #print pv
            self.headers[nframe]["pv"] = pv
        natoms = h["natoms"]
        if h["x_size"] != 0:
            x = []
            for i in range(natoms):
                x.append(up.unpack_farray(3, up.unpack_float))
            #self.coords["frame%d"%nframe] = x
            self.coords.append(x)

        if h["v_size"] != 0:
            v = []
            for i in range(natoms):
                v.append(up.unpack_farray(3, up.unpack_float))
            self.velocities["frame%d" % nframe] = v
        if h["f_size"] != 0:
            f = []
            for i in range(natoms):
                f.append(up.unpack_farray(3, up.unpack_float))
            self.forces["frame%d" % nframe] = f
Ejemplo n.º 8
0
Archivo: mesgen.py Proyecto: zooko/egtp
    def parse(self, wired_string):
        """
        @returns (counterparty_pub_key_sexp, cleartext,)

        @raises SessionInvalidated if the incoming message was an "invalidate session" message \000\000\000\002.
        @raises UnknownSession error if the incoming message did not identify a known session key.

        @precondition `wired_string' must be a string.: type(wired_string) == types.StringType: "wired_string: %s :: %s" % (hr(wired_string), hr(type(wired_string)))
        @postcondition `counterparty_pub_key_sexp' is a public key.: MojoKey.publicRSAKeyForCommunicationSecurityIsWellFormed(counterparty_pub_key_sexp): "counterparty_pub_key_sexp: %s" % hr(counterparty_pub_key_sexp)
        """
        assert type(wired_string) == types.StringType, "precondition: `wired_string' must be a string." + " -- " + "wired_string: %s :: %s" % (hr(wired_string), hr(type(wired_string)))
        session = None

        try:
            u = Unpacker(wired_string)
            mtype = u.unpack_fstring(4)
            if mtype == '\000\000\000\000':   # a message with a full PK header
                header = u.unpack_string()
                iv = u.unpack_fstring(8)
                prefix = wired_string[:u.get_position()]
                encrypted = u.unpack_string()
                u.done()
                
                counterparty_pub_key_sexp, symmetric_key = self._session_keeper.parse_header(header)
                decrypted = tripledescbc.new(symmetric_key).decrypt(iv, encrypted)
                u = Unpacker(decrypted)
                message = u.unpack_string()
                mac = u.unpack_fstring(SIZE_OF_UNIQS)
                u.done()
                
                # debugprint("------ ------ ------ ------ hmachish(key=%s, message=%s)\n" % (`symmetric_key`, `message`))
                maccomp = cryptutil.hmacish(key=symmetric_key, message=message)

                if mac != maccomp:
                    raise Error, 'incorrect MAC'
                return (counterparty_pub_key_sexp, message)
            elif mtype == '\000\000\000\001':   # a message using an already established session id
                session = u.unpack_fstring(SIZE_OF_UNIQS)
                iv = u.unpack_fstring(8)
                prefix = wired_string[:u.get_position()]
                encrypted = u.unpack_string()
                u.done()
                
                counterparty_pub_key_sexp, symmetric_key, want_ack = self._session_keeper.get_session_info(session)
                decrypted = tripledescbc.new(symmetric_key).decrypt(iv, encrypted)

                u = Unpacker(decrypted)
                message = u.unpack_string()
                mac = u.unpack_fstring(SIZE_OF_UNIQS)
                u.done()

                counterparty_id = idlib.make_id(counterparty_pub_key_sexp, 'broker')

                # debugprint("------ ------ ------ ------ hmachish(key=%s, message=%s)\n" % (`symmetric_key`, `message`))
                maccomp = cryptutil.hmacish(key=symmetric_key, message=message)
                if mac != maccomp:
                    raise Error, 'incorrect MAC'
                if want_ack:
                    self._session_keeper.got_ack(counterparty_id)
                return (counterparty_pub_key_sexp, message)
            elif mtype == '\000\000\002\002':   # a short "message" invalidating an outgoing session id
                bad_session_id_out = u.unpack_fstring(SIZE_OF_UNIQS)
                unverified_counterparty_id = u.unpack_fstring(SIZE_OF_UNIQS)
                self._session_keeper.invalidate_session(bad_session_id_out, unverified_counterparty_id)
                raise SessionInvalidated, 'session_id %s with %s invalidated' % (`bad_session_id_out`, idlib.to_ascii(unverified_counterparty_id))
            else:
                raise Error, 'unsupported message type'
        except (modval.Error, tripledescbc.Error, xdrlib.Error, EOFError), le:
            debugprint("got error in mesgen.parse(): %s", args=(le,), v=4, vs="debug")
            if session is not None:
                raise UnknownSession(session, self.get_id())
            else:
                raise Error, le
Ejemplo n.º 9
0
Archivo: mesgen.py Proyecto: zooko/egtp
    def __parse_header(self, header):
        """
        Parses a header and stores information contained in it as necessary
        
        Returns (counterparty pub key sexp, symmetric key) throws Error
        """
        assert type(header) == type('')
        try:
            hash = sha(header).digest()
            cached = self.__cached_headers.get(hash)
            if cached is not None:
                return cached
            u = Unpacker(header)
            # messages start with the hash of the recipient's public id
            recipient_id = u.unpack_fstring(SIZE_OF_UNIQS)
            if recipient_id != self.__my_public_key_id:
                raise Error, 'message not intended for me'
            # unpack PK encrypted public key
            encrypted_key = u.unpack_string()
            self.__key.set_value_string(encrypted_key)
            self.__key.decrypt()   # PKop
            decrypted = self.__key.get_value()

            try:
                symmetric_key = cryptutil.oaep_decode(decrypted[1:]) # Leave off the initial 0 byte. ### XX check whether it really is 0 and raise bad-encoding error if not.  --Zooko 2000-07-29
            except cryptutil.OAEPError, le:
                raise Error, 'bad encryption -- pad badding: padded: %s, Error: %s' % (`decrypted`, `le.args`)

            iv = u.unpack_fstring(8)
            # first half of the MAC # XXX A.K.A. the key?  --Zooko 2000-07-29
            prefix = header[:u.get_position()]
            # all data except the symmetric key and recipient, encrypted
            encrypted = u.unpack_string()
            u.done()

            decrypted = tripledescbc.new(symmetric_key).decrypt(iv, encrypted)                
            u = Unpacker(decrypted)
            # the full public key of the sender
            sender_key = u.unpack_string()
            full_key = MojoKey.makePublicRSAKeyForCommunicating(modval.new(sender_key, HARDCODED_RSA_PUBLIC_EXPONENT))
            full_key_id = idlib.make_id(full_key, 'broker')
            # the session id for messages sent 'here'
            id_in = _mix_counterparties(full_key_id, self.__my_public_key_id, u.unpack_fstring(SIZE_OF_UNIQS))
            # the session id for messages sent 'there'
            id_out = _mix_counterparties(full_key_id, self.__my_public_key_id, u.unpack_fstring(SIZE_OF_UNIQS))
            # check that the pk encrypted symmetric key used to send this message is the same was generated properly
            strl = u.unpack_fstring(SIZE_OF_UNIQS)
            sr = HashRandom.SHARandom(_mix_counterparties(full_key_id, self.__my_public_key_id, strl))
            spaml = sr.get(SIZE_OF_SYMMETRIC_KEYS)
            if symmetric_key != spaml:
                raise Error, 'improperly generated key'
            # the second half of what's in the MAC # XXX A.K.A. the message?  --Zooko 2000-07-29
            end = decrypted[:u.get_position()]
            # the signature of everything
            signature = u.unpack_fstring(len(sender_key))
            u.done()
            
            # debugprint("------ ------ ------ ------ hmachish(key=%s, message=%s)\n" % (`symmetric_key`, `end`))
            summary = cryptutil.hmacish(key=symmetric_key, message=end)
            
            x = modval.new(sender_key, HARDCODED_RSA_PUBLIC_EXPONENT, signature)
            x.undo_signature()   # PKop
            signed_value = x.get_value()

            try:
                thingie = cryptutil.oaep_decode(signed_value[1:]) # Leave off the initial 0 byte. ### XX check whether it really is 0 and raise bad-encoding error if not.  --Zooko 2000-07-29
            except cryptutil.OAEPError, le:
                raise Error, 'bad encryption -- pad badding: padded: %s, Error: %s' % (`signed_value`, `le.args`)
Ejemplo n.º 10
0
            else:
                logging.info(str(flow_sample_cache))

            ### Flow Sample ###
            if enterprise_format_num in [[0, 1], [0, 3]]:  # Flow Sample

                # Iterate through the flow records
                for record_counter_num in range(
                        0, flow_sample_cache["Record Count"]
                ):  # For each staged sample
                    record_ent_form_number = enterprise_format_numbers(
                        unpacked_sample_data.unpack_uint()
                    )  # [Enterprise, Format] numbers
                    counter_data_length = int(
                        unpacked_sample_data.unpack_uint())  # Length of record
                    current_position = int(unpacked_sample_data.get_position()
                                           )  # Current unpack buffer position
                    skip_position = current_position + counter_data_length  # Bail out position if unpack fails for skipping

                    logging.info("Flow record " + str(record_counter_num + 1) +
                                 " of " +
                                 str(flow_sample_cache["Record Count"]) +
                                 ", type " + str(record_ent_form_number) +
                                 ", length " + str(counter_data_length) +
                                 ", XDR position " + str(current_position) +
                                 ", skip position " + str(skip_position))

                    # Unpack the opaque flow record
                    unpacked_record_data = Unpacker(
                        unpacked_sample_data.unpack_fopaque(
                            counter_data_length))
Ejemplo n.º 11
0
class trrParser:
    """ Parses .trr Gromacs trajectory file """
    
    def __init__(self, file):

        self.nframes = 0
        self.headers=[]
##         header = {
##             "ir_size":None,
##             "e_size": None,
##             "box_size" :None,
##             "vir_size": None,
##             "pres_size": None,
##             "top_size ": None,
##             "sym_size ": None,
##             "x_size ": None,
##             "v_size ": None,
##             "f_size ": None,
##             "natoms ": None,
##             "step ": None,
##             "nre ": None,
##             "version":'GMX_trn_file',
##             "magicnum" :1993,
##             "bDouble ": None,
##             }
        self.file = file
        self.coords = []
        self.velocities = {}
        self.forces = {}


    def nFloatSize(self, h):

        nflsize=0;
        if h["box_size"]:
            nflsize = h["box_size"]/(DIM*DIM);
        elif h["x_size"]:
            nflsize = h["x_size"]/(h["natoms"]*DIM);
        elif h["v_size"]:
            nflsize = h["v_size"]/(h["natoms"]*DIM);
        elif h["f_size"]:
            nflsize = h["f_size"]/(h["natoms"]*DIM);
        else: 
            print "Can not determine precision of trr file"
  
        if (nflsize != calcsize("f")) and (nflsize != calcsize("d")):
            print "Float size %d. Maybe different CPU?"%nflsize
      
        return nflsize

    def read(self):
        fext = os.path.splitext(self.file)[-1]
        assert fext == ".trr"
        fp = open(self.file, "rb")
        self.data = data = fp.read()
        self.coords = []
        self.v = {}
        self.f = {}
        self.up = Unpacker(data)
        curpos = self.up.get_position()
        datasize = len(data)
        nframe = 0
        #each frame begins with a header
        while curpos < datasize:
            #print "current position:", curpos
            h = self.readHeader(nframe)
            self.headers.append(h)
            self.readData(nframe)
            nframe = nframe + 1
            curpos = self.up.get_position()
        #print "end of readTraj, cur position : %d, datazize: %d" %(self.up.get_position(), datasize)
        self.nframes = nframe
        if self.nframes:
            return 1
        else:
            return 0

    def readHeader(self, nframe):
        #print "reading header, frame %d" %nframe
        up = self.up
        header = {}
        header["magicnum"] = up.unpack_int()
        #print "magicnum: ", header["magicnum"]
        #1993
        i1 = up.unpack_int()
        #13
        version = up.unpack_string()
        #'GMX_trn_file'
        header["version"] = version
        #print "version:", version
        header["ir_size"] = up.unpack_int()
        #print "ir_size=", header["ir_size"]
        header["e_size"]=up.unpack_int()
        #print "e_size=", header["e_size"]
        header["box_size"] =up.unpack_int()
        #print "box_size=", header["box_size"]
        header["vir_size"] = up.unpack_int()
        #print "vir_size=", header["vir_size"]
        header["pres_size"] = up.unpack_int()
        #print "pres_size=", header["pres_size"]
        header["top_size"]=up.unpack_int()
        #print "top_size=", header["top_size"]

        header["sym_size"]=up.unpack_int()
        #print "sym_size=", header["sym_size"]

        header["x_size"]=up.unpack_int()
        #print "x_size=", header["x_size"]

        header["v_size"]=up.unpack_int()
        #print "v_size=", header["v_size"]

        header["f_size"]=up.unpack_int()
        #print "f_size=", header["f_size"]

        header["natoms"]=up.unpack_int()
        #print "natoms=", header["natoms"]
        header["step"]=up.unpack_int()
        #print "step=", header["step"]
        header["nre"]=up.unpack_int()
        #print "nre=", header["nre"]

        
        if self.nFloatSize(header) == calcsize("d"):
            header["bDouble"] = True
        else:
            header["bDouble"] = False

        if header["bDouble"]:
            header["time"] = up.unpack_double()
            header["lam"] = up.umpack_double()
        else:
            header["time"] = up.unpack_float()
            header["lam"] = up.unpack_float()

        #print "time = ", header["time"]
        #print "lambda = ", header["lam"]
        #print "natoms=%10d  step=%10d  time=%10g  lambda=%10g"% (header["natoms"],header["step"],header["time"],header["lam"])
        #print "current position:",  up.get_position()
        return header


    def readData(self, nframe):
        up = self.up
        h = self.headers[nframe]
        box = []
        if h["box_size"] != 0 :
            for i in range(3):
                box.append(up.unpack_farray(3, up.unpack_float))
            #print " box (3x3):"
            #print box
            self.headers[nframe]["box"] = box
        pv = []
        if h["vir_size"] != 0:
            for i in range(3):
                pv.append(up.unpack_farray(3, up.unpack_float))
            #print "pv:"
            #print pv
            self.headers[nframe]["pv"] = pv
        if h["pres_size"]!= 0:
            pv.append(up.unpack_farray(3, up.unpack_float))
            #print "pv:"
            #print pv
            self.headers[nframe]["pv"] = pv
        natoms = h["natoms"]
        if h["x_size"] != 0:
            x= []
            for i in range (natoms): 
                x.append(up.unpack_farray(3, up.unpack_float))
            #self.coords["frame%d"%nframe] = x
            self.coords.append(x)

        if h["v_size"] != 0:
            v = []
            for i in range (natoms):
                v.append(up.unpack_farray(3, up.unpack_float))
            self.velocities["frame%d"%nframe] = v
        if h["f_size"] != 0:
            f = []
            for i in range (natoms):
                f.append(up.unpack_farray(3, up.unpack_float))
            self.forces["frame%d"%nframe] = f
Ejemplo n.º 12
0
    def handle_message(self, opaque_bytes, client_id):
        """
        Handles a message, start to finish.
        Takes the opaque bytes representing the XDR encoded RPC message.
        Produces an RPC reply, also encoded as opaque bytes.
        """
        from xdrlib import Unpacker, Packer
        unpacker = Unpacker(opaque_bytes)
        msg = rpc_msg.unpack(unpacker)
        print(msg.body.mtype.value)
        if msg.body.mtype != msg_type.CALL:
            print("No reply!")
            return None # do not reply to such a bad message.
        #response = self.handle_message(msg,
        #                               opaque_bytes[unpacker.get_position():])
        print("Well-formed message!")
        print("rpc version: %d" % msg.body.cbody.rpcvers)
        print("program id: %d" % msg.body.cbody.prog)
        print("version id: %d" % msg.body.cbody.vers)
        print("procedure id: %d" % msg.body.cbody.proc)
        print("cred flavor: %d" % msg.body.cbody.cred.flavor)
        print("verf flavor: %d" % msg.body.cbody.verf.flavor)
        print("remaining bytes: %s" % opaque_bytes[unpacker.get_position():])

        if msg.body.cbody.cred.flavor == auth_flavor.AUTH_SYS:
            print("using system auth")
            unpacker2 = Unpacker(msg.body.cbody.cred.body.bytes)
            params = authsys_parms.unpack(unpacker2)
            print(params)
            id = self.next_short_id
            self.next_short_id += 1
            self.system_auth[id] = params
            packer = Packer()
            packer.pack_uint(id)
            verf = opaque_auth(flavor=auth_flavor.AUTH_SHORT,
                               body=packer.get_buffer())
        else:
            verf = opaque_auth.NONE()

        def _pack(reply):
            packer = Packer()
            reply.pack(packer)
            return packer.get_buffer()
        _body = rpc_msg.body
        _rbody = reply_body
        _rreply = rejected_reply
        _areply = accepted_reply
        _rdata = accepted_reply.reply_data
        
        if msg.body.cbody.rpcvers != 2:
            reply = rpc_msg(xid=msg.xid,
                            body=_body(mtype=msg_type.REPLY,
                                       rbody=_rbody(stat=reply_stat.MSG_DENIED,
                                                    rreply=_rreply(stat=reject_stat.RPC_MISMATCH,
                                                                   mismatch_info=mismatch_info(low=2, high=2)))))
            return _pack(reply)

        if msg.body.cbody.prog not in self.programs:
            print("no such program!")
            reply = rpc_msg(xid=msg.xid,
                            body=_body(mtype=msg_type.REPLY,
                                       rbody=_rbody(stat=reply_stat.MSG_ACCEPTED,
                                                    areply=_areply(verf=verf,
                                                                   reply_data=_rdata(stat=accept_stat.PROG_UNAVAIL)))))
            return _pack(reply)

        program = self.programs[msg.body.cbody.prog]
        print("program: %s" % str(program))
        version = program.get_version_impl(msg.body.cbody.vers)
        print("version: %s" % str(version))
        procedure = version.get_procedure_by_id(msg.body.cbody.proc)
        print("procedure: %s" % str(procedure))
        print("procedure.arg_type: %s" % str(procedure.argument_type))
        args = procedure.argument_type.unpack(unpacker)
        print("args: %s" % str(args))
        response = procedure(version, msg, args)
        print("response: %s" % str(response))
        reply = rpc_msg(xid=msg.xid,
                        body=_body(mtype=msg_type.REPLY,
                                   rbody=_rbody(stat=reply_stat.MSG_ACCEPTED,
                                                areply=_areply(verf=verf,
                                                               reply_data=_rdata(stat=accept_stat.SUCCESS)))))
        print("reply: %s" % str(reply))
        packer = Packer()
        reply.pack(packer)
        response.pack(packer)
        print("bytes: %s" % str(packer.get_buffer()))
        return packer.get_buffer()