def __directSendParams (self, destination, clusterName, nodeName, timeStamp, params): if self.__shouldSend() == False: # self.logger.log(Logger.ERROR, "Dropping packet since rate is too fast!"); self.logger.log(Logger.INFO, "Pausing 1sec since rate is too fast!"); time.sleep(1.0) # return; if destination == None: self.logger.log(Logger.WARNING, "Destination is None"); return; host, port, passwd = destination crtSenderRef = self.senderRef[destination] crtSenderRef['SEQ_NR'] = (crtSenderRef['SEQ_NR'] + 1) % 2000000000; # wrap around 2 mld xdrPacker = xdrlib.Packer () xdrPacker.pack_string ("v:"+self.__version+"p:"+passwd) xdrPacker.pack_int (crtSenderRef['INSTANCE_ID']) xdrPacker.pack_int (crtSenderRef['SEQ_NR']) xdrPacker.pack_string (clusterName) xdrPacker.pack_string (nodeName) sent_params_nr = 0 paramsPacker = xdrlib.Packer () if isinstance(params, type( {} )): for name, value in params.iteritems(): if self.__packParameter(paramsPacker, name, value): sent_params_nr += 1 elif isinstance(params, type( [] )): for name, value in params: self.logger.log(Logger.DEBUG, "Adding parameter "+name+" = "+str(value)); if self.__packParameter(paramsPacker, name, value): sent_params_nr += 1 else: self.logger.log(Logger.WARNING, "Unsupported params type in sendParameters: " + str(type(params))); xdrPacker.pack_int (sent_params_nr) if (timeStamp != None) and (timeStamp > 0): paramsPacker.pack_int(timeStamp); buffer = xdrPacker.get_buffer() + paramsPacker.get_buffer() self.logger.log(Logger.NOTICE, "Building XDR packet ["+str(clusterName)+"/"+str(nodeName)+"] <"+str(crtSenderRef['SEQ_NR'])+"/"+str(crtSenderRef['INSTANCE_ID'])+"> "+str(sent_params_nr)+" params, "+str(len(buffer))+" bytes."); # send this buffer to the destination, using udp datagrams try: self.__udpSocket.sendto(buffer, (host, port)) self.logger.log(Logger.NOTICE, "Packet sent to "+host+":"+str(port)+" "+passwd) except socket.error as msg: self.logger.log(Logger.ERROR, "Cannot send packet to "+host+":"+str(port)+" "+passwd+": "+str(msg[1])) xdrPacker.reset() paramsPacker.reset()
def run_unctrl(sc): print('--- Simulating uncontrolled behavior (full)') p_sim = PBar(len(sc.devices) * (sc.i_end - sc.i_pre)).start() sim_data = {} sc.state_files_unctrl = {} for d in sc.devices: aid = str(d.typename) + str(d.id) # Create a shadow copy of the device to operate on d = d.copy() # Pre-Simulation simulate(d, sc.i_pre, sc.i_start, p_sim) # Simulate [i_start, block_start] sim_data_b_start = simulate(d, sc.i_start, sc.i_block_start, p_sim) # Simulate [block_start, block_end] sim_data_b_end = simulate(d, sc.i_block_start, sc.i_block_end, p_sim) # Save state (needed in run_states() below) packer = xdrlib.Packer() d.save_state(packer) tmpf = NamedTemporaryFile(mode='wb', dir='/tmp', delete=False) tmpf.write(packer.get_buffer()) tmpf.close() sc.state_files_unctrl[aid] = tmpf.name # Simulate [block_end, i_end] sim_data_i_end = simulate(d, sc.i_block_end, sc.i_end, p_sim) # Combine sim_data sim_data[aid] = np.concatenate( (sim_data_b_start, sim_data_b_end, sim_data_i_end), axis=1) print() return sim_data
def _op_connect_request(self): p = xdrlib.Packer() p.pack_int(self.op_connect_request) p.pack_int(1) # async p.pack_int(self.db_handle) p.pack_int(0) send_channel(self.sock, p.get_buffer()) b = self.recv_channel(4) while bytes_to_bint(b) == self.op_dummy: b = self.recv_channel(4) if bytes_to_bint(b) != self.op_response: raise InternalError h = bytes_to_bint(self.recv_channel(4)) self.recv_channel(8) # garbase ln = bytes_to_bint(self.recv_channel(4)) ln += ln % 4 # padding family = bytes_to_bint(self.recv_channel(2)) port = bytes_to_bint(self.recv_channel(2), u=True) b = self.recv_channel(4) ip_address = '.'.join([str(byte_to_int(c)) for c in b]) ln -= 8 self.recv_channel(ln) (gds_codes, sql_code, message) = self._parse_status_vector() if sql_code or message: raise OperationalError(message, gds_codes, sql_code) return (h, port, family, ip_address)
def _op_service_start(self, param): p = xdrlib.Packer() p.pack_int(self.op_service_start) p.pack_int(self.db_handle) p.pack_int(0) p.pack_bytes(param) send_channel(self.sock, p.get_buffer())
def encode(self, message): packer = xdrlib.Packer() user = message.get('user', 0) cause = message.get('cause', 0) uc = ((cause & 0xffff) << 16) | (user & 0xffff) packer.pack_uint(uc) return packer.get_buffer()
def fs_cut(fname, subject, hemi, freesurfer_subject_dir=None): """Cut freesurfer surface using blender interface Parameters ---------- fname : str file path for new .blend file (must end in ".blend") if `freesurfer_subject_dir` is None, it defaults to SUBJECTS_DIR environment variable """ wpts, polys, curv = freesurfer.get_surf(subject, hemi, 'smoothwm', freesurfer_subject_dir=freesurfer_subject_dir) ipts, _, _ = freesurfer.get_surf(subject, hemi, 'inflated', freesurfer_subject_dir=freesurfer_subject_dir) rcurv = np.clip(((-curv + .6) / 1.2), 0, 1) p = xdrlib.Packer() p.pack_array(wpts.ravel(), p.pack_double) p.pack_array(ipts.ravel(), p.pack_double) p.pack_array(polys.ravel(), p.pack_uint) p.pack_array(rcurv.ravel(), p.pack_double) with tempfile.NamedTemporaryFile() as tf: tf.write(p.get_buffer()) tf.flush() code = """with open('{tfname}', 'rb') as fp: u = xdrlib.Unpacker(fp.read()) wpts = u.unpack_array(u.unpack_double) ipts = u.unpack_array(u.unpack_double) polys = u.unpack_array(u.unpack_uint) curv = u.unpack_array(u.unpack_double) blendlib.init_subject(wpts, ipts, polys, curv) """.format(tfname=tf.name) _call_blender(fname, code)
def make_call(to_call, **kwargs): packer = xdrlib.Packer() xid = random.randint(0, 1024 * 1024) packer.pack_uint(xid) packer.pack_enum(CALL) packer.pack_uint(RPCVERSION) packer.pack_uint(to_call['prog']) packer.pack_uint(to_call['vers']) packer.pack_uint(to_call['proc']) cred = kwargs.get('cred', (0, '')) packer.pack_enum(cred[0]) packer.pack_opaque(cred[1]) verf = kwargs.get('verf', (0, '')) packer.pack_enum(verf[0]) packer.pack_opaque(verf[1]) if kwargs.get('args_pack_func') is not None: kwargs['args_pack_func'](packer, to_call['args']) data = packer.get_buffer() return xid, data
def _histogram_append_chunk(self, sample_rate, data): logger.debug("calling _histogram_append_chunk. points:%s", len(data)) #if we get an empty container then there's nothing to do if len(data) == 0: return first_histogram = data[0] bin_start = first_histogram.bin_start bin_size = first_histogram.bin_size num_bins = len(first_histogram.bins) packer = xdrlib.Packer() for histogram in data: #check that all of the histograms have the same meta-info if histogram.bin_start != bin_start or\ histogram.bin_size != bin_size or\ len(histogram.bins) != num_bins: raise Error( "All histograms must have same bin start, bin size, and number of bins" ) packer.pack_uhyper(histogram.timestamp_nanoseconds) for bin_value in histogram.bins: packer.pack_uint(bin_value) self._histogram_submit_blob(sample_rate, bin_start, bin_size, num_bins, packer.get_buffer()) self._new_histogram(sample_rate, data[-1])
def make_wave_file(outfile, start=None, end=None, step=None, new_wave=None, ewave=None, air=True): """ Writes RH wave file (in xdr format). All wavelengths should be in nm. Parameters ---------- start: number Starting wavelength. end: number Ending wavelength (non-inclusive) step: number Wavelength separation new_wave: 1D array Alternatively to start/end, one can specify an array of wavelengths here. outfile: string Name of file to write. ewave: 1-D array, optional Array of existing wavelengths. Program will make discard points to make sure no step is enforced using these points too. air: boolean, optional If true, will at the end convert the wavelengths into vacuum wavelengths. """ import xdrlib from specutils.utils.wcs_utils import air_to_vac if new_wave is None: new_wave = np.arange(start, end, step) if None in [start, end, step]: raise ValueError('Must specify either new_wave, or start, end, ' 'step. Stopping.') if step is None: step = np.median(np.diff(new_wave)) if ewave is not None: # ensure step is kept at most times keepers = [] for w in new_wave: if np.min(np.abs(w - ewave)) > step * 0.375: keepers.append(w) new_wave = np.array(keepers) if air: # RH uses Edlen (1966) to convert from vacuum to air new_wave = air_to_vac(new_wave * units.nm, method='edlen1966', scheme='iteration').value # write file p = xdrlib.Packer() nw = len(new_wave) p.pack_int(nw) p.pack_farray(nw, new_wave.astype('d'), p.pack_double) f = open(outfile, 'wb') f.write(p.get_buffer()) f.close() print(("Wrote %i wavelengths to file." % nw))
def GeneratingData(): # we need to pack these strings into an xdr structure packer = xdrlib.Packer() packer.pack_int(1) # version 1 # set samplerate to 10 Hz packer.pack_enum(HERTZ) packer.pack_int(10) # Total number of datapoints. 6000 points is 10 minutes of data sampled at 10 Hz POINTS = 1000 packer.pack_int(POINTS) print("generating data...") # now pack each datapoint, we'll use a sin wave function to generate fake data. we'll use the current time as the starting point # start time in nanoseconds timestamp_nanoseconds = int(time.time() * 1000000000) # number of nanoseconds between 2 datapoints when sampling at 10 Hz sampleInterval_nanoseconds = 100000000 for i in range(0, POINTS): packer.pack_hyper(timestamp_nanoseconds) # generate value as a function of time packer.pack_float(math.sin(timestamp_nanoseconds / 20000000000.0)) # increment the timestamp for the next datapoint timestamp_nanoseconds += sampleInterval_nanoseconds # print(timestamp_nanoseconds, math.sin(timestamp_nanoseconds/20000000000.0)) return packer.get_buffer()
def pack(self): packdata = xdrlib.Packer() # create the packed object packdata.pack_uint(self.src_vlan) packdata.pack_uint(self.src_priority) packdata.pack_uint(self.dst_vlan) packdata.pack_uint(self.dst_priority) return packdata.get_buffer()
def pack(self): packdata = xdrlib.Packer() # create the packed object packdata.pack_int(self.header_protocol) packdata.pack_uint(self.frame_length) packdata.pack_uint(self.stripped) packdata.pack_opaque(self.header) return packdata.get_buffer()
def write_preamble(self): preamble_encoder = xdrlib.Packer() # Magic numbers and versioning preamble_encoder.pack_uint(self.hemelb_magic_number) preamble_encoder.pack_uint(self.geometry_magic_number) preamble_encoder.pack_uint( self.hemelb_geometry_file_format_version_number) # Domain size in blocks for blocks_across_dimension in self.size_in_blocks: preamble_encoder.pack_uint(blocks_across_dimension) # Number of lattice sites along the side of a block preamble_encoder.pack_uint(self.sites_along_block) # Grid space step preamble_encoder.pack_double(self.space_step) # Origin of coordinates for origin_coordinate in self.origin: preamble_encoder.pack_double(origin_coordinate) # Pad the length of the preamble to 64 bytes preamble_encoder.pack_uint(0) self.outfile.write(preamble_encoder.get_buffer())
def run_schedule(sc): print('--- Simulating controlled behaviour in [block_start, block_end]') p_sim = PBar(len(sc.devices) * (sc.i_block_end - sc.i_block_start)).start() basedir = os.path.dirname(sc.loaded_from) schedules = np.load(os.path.join(basedir, sc.sched_file)) sim_data = {} sc.state_files_ctrl = {} for d in sc.devices: aid = str(d.typename) + str(d.id) # Load state statefile = sc.state_files[aid] with open(statefile, 'rb') as data: unpacker = xdrlib.Unpacker(data.read()) d.load_state(unpacker) os.remove(statefile) sched = schedules[aid] if d.typename == 'heatpump': # This is a consumer, so negate P_el sched = sched * (-1.0) # Set schedule d.components.scheduler.schedule = sched.tolist() # Simulate sim_data[aid] = simulate(d, sc.i_block_start, sc.i_block_end, p_sim) # Save state packer = xdrlib.Packer() d.save_state(packer) tmpf = NamedTemporaryFile(mode='wb', dir='/tmp', delete=False) tmpf.write(packer.get_buffer()) tmpf.close() sc.state_files_ctrl[aid] = tmpf.name print() return sim_data
def setUp(self): with mock.patch('hemelb_steering.remote_hemelb.PagedSocket' ) as mockPagedSocket: self.mockSocket = mockPagedSocket.return_value self.rhlb = RemoteHemeLB(address='fibble', port=8080, steering_id=1111) mockPagedSocket.assert_called_once_with( address='fibble', port=8080, receive_length=12, additional_receive_length_function=RemoteHemeLB. _calculate_receive_length) fixture = xdrlib.Packer() fixture.pack_int(4) #x fixture.pack_int(4) #y pixels = 16 bytes_per_pixel = 4 + 12 #each three colors with four sub-images per color and two two-byte coordinates image_size = pixels * bytes_per_pixel fixture.pack_int(image_size) for _ in xrange(pixels): fixture.pack_fopaque(bytes_per_pixel, 'abcdefghijklmnop') fixture.pack_int(7) # step fixture.pack_double(0.7) #time fixture.pack_int(0) #cycle fixture.pack_int(2) #inlets fixture.pack_double(0) #mouse stress fixture.pack_double(0) #mouse pressure self.mockSocket.receive.return_value = str( bytearray(fixture.get_buffer()))
def delChannel(server, auth_token, device_id, sensor_name, channel_name, channel_label="", channel_desc=""): """ Delete a channel of the sensor. label and description are optional. """ conn = httplib.HTTPSConnection(server) url = "/SensorCloud/devices/%s/sensors/%s/channels/%s/?version=1&auth_token=%s" % ( device_id, sensor_name, channel_name, auth_token) headers = {"Content-type": "application/xdr"} #delChannel allows you to delete the channel and all its associated data streams. All fileds are strings. #we need to pack these strings into an xdr structure packer = xdrlib.Packer() packer.pack_int(1) #version 1 packer.pack_string(channel_label) packer.pack_string(channel_desc) data = packer.get_buffer() print "deleting channel..." conn.request('DELETE', url=url, body=data, headers=headers) response = conn.getresponse() print response.status, response.reason
def mk_specialisation_float(nbits: int) -> str: p = xdrlib.Packer() if nbits == 32: typename = "float" pack = p.pack_float suffix = "U" flt_type_str = ">f" int_type_str = ">I" func_name = "binflt" elif nbits == 64: typename = "double" pack = p.pack_double suffix = "UL" flt_type_str = ">d" int_type_str = ">Q" func_name = "bindbl" else: raise ValueError("only deal with 32/64 bit floats") intvals = mk_ints(nbits) fltvals = [ struct.unpack(flt_type_str, struct.pack(int_type_str, v))[0] for v in intvals ] for v in fltvals: pack(v) values_code = ",\n ".join(f"{func_name}(0x{v:x})" for v in intvals) buffer_data = ", ".join(f"'\\x{x:02x}'" for x in p.get_buffer()) return spec_template.substitute(locals())
def addSensor(server, auth_token, device_id, sensor_name, sensor_type="", sensor_label="", sensor_desc=""): """ Add a sensor to the device. type, label, and description are optional. """ conn = http.client.HTTPSConnection(server) url="/SensorCloud/devices/%s/sensors/%s/?version=1&auth_token=%s"%(device_id, sensor_name, auth_token) headers = {"Content-type" : "application/xdr"} #addSensor allows you to set the sensor type label and description. All fileds are strings. #we need to pack these strings into an xdr structure packer = xdrlib.Packer() packer.pack_int(1) #version 1 packer.pack_string(sensor_type.encode('utf-8')) packer.pack_string(sensor_label.encode('utf-8')) packer.pack_string(sensor_desc.encode('utf-8')) data = packer.get_buffer() print("adding sensor...") conn.request('PUT', url=url, body=data, headers=headers) response =conn.getresponse() print(response.status , response.reason) #if response is 201 created then we know the sensor was added if response.status == http.client.CREATED: print("Sensor added") else: print("Error adding sensor. Error:", response.read())
def _histogram_submit_blob(self, sampleRate, bin_start, bin_size, num_bins, blob): hist_size = 8 + (4 * num_bins) hist_count = len(blob) / hist_size packer = xdrlib.Packer() VERSION = 1 packer.pack_int(VERSION) packer.pack_fopaque(8, sampleRate.to_xdr()) #pack histogram info packer.pack_float(bin_start) packer.pack_float(bin_size) packer.pack_uint(num_bins) #Writing an array in XDR. an array is always prefixed by the array length packer.pack_int(hist_count) data = packer.get_buffer() + blob response = self.url("/streams/histogram/data/")\ .param("version", "1")\ .content_type("application/xdr")\ .data(data)\ .post() # if response is 201 created then we know the data was successfully added if response.status_code != httplib.CREATED: raise error(response, "histogram upload")
def _op_create(self, page_size=4096): dpb = bs([1]) s = self.str_to_bytes(self.charset) dpb += bs([isc_dpb_set_db_charset, len(s)]) + s dpb += bs([isc_dpb_lc_ctype, len(s)]) + s s = self.str_to_bytes(self.user) dpb += bs([isc_dpb_user_name, len(s)]) + s if self.accept_version < PROTOCOL_VERSION13: enc_pass = get_crypt(self.password) if self.accept_version == PROTOCOL_VERSION10 or not enc_pass: s = self.str_to_bytes(self.password) dpb += bs([isc_dpb_password, len(s)]) + s else: enc_pass = self.str_to_bytes(enc_pass) dpb += bs([isc_dpb_password_enc, len(enc_pass)]) + enc_pass if self.role: s = self.str_to_bytes(self.role) dpb += bs([isc_dpb_sql_role_name, len(s)]) + s if self.auth_data: s = bytes_to_hex(self.auth_data) dpb += bs([isc_dpb_specific_auth_data, len(s)]) + s if self.timezone: s = self.str_to_bytes(self.timezone) dpb += bs([isc_dpb_session_time_zone, len(s)]) + s dpb += bs([isc_dpb_sql_dialect, 4]) + int_to_bytes(3, 4) dpb += bs([isc_dpb_force_write, 4]) + int_to_bytes(1, 4) dpb += bs([isc_dpb_overwrite, 4]) + int_to_bytes(1, 4) dpb += bs([isc_dpb_page_size, 4]) + int_to_bytes(page_size, 4) p = xdrlib.Packer() p.pack_int(self.op_create) p.pack_int(0) # Database Object ID p.pack_string(self.str_to_bytes(self.filename)) p.pack_bytes(dpb) self.sock.send(p.get_buffer())
def gii_cut(fname, subject, hemi): ''' Add gifti surface to blender ''' from ..database import db hemis = dict(lh='left', rh='right') wpts, polys = db.get_surf(subject, 'wm', hemi) ipts, _ = db.get_surf(subject, 'very_inflated', hemi) curvature = db.getSurfInfo(subject, 'curvature') rcurv = curvature.__getattribute__(hemis[hemi]) p = xdrlib.Packer() p.pack_array(wpts.ravel(), p.pack_double) p.pack_array(ipts.ravel(), p.pack_double) p.pack_array(polys.ravel(), p.pack_uint) p.pack_array(rcurv.ravel(), p.pack_double) with tempfile.NamedTemporaryFile() as tf: tf.write(p.get_buffer()) tf.flush() code = """with open('{tfname}', 'rb') as fp: u = xdrlib.Unpacker(fp.read()) wpts = u.unpack_array(u.unpack_double) ipts = u.unpack_array(u.unpack_double) polys = u.unpack_array(u.unpack_uint) curv = u.unpack_array(u.unpack_double) blendlib.init_subject(wpts, ipts, polys, curv) """.format(tfname=tf.name) _call_blender(fname, code)
def _op_attach(self): dpb = bs([isc_dpb_version1]) s = self.str_to_bytes(self.charset) dpb += bs([isc_dpb_lc_ctype, len(s)]) + s s = self.str_to_bytes(self.user) dpb += bs([isc_dpb_user_name, len(s)]) + s if self.accept_version < PROTOCOL_VERSION13: enc_pass = get_crypt(self.password) if self.accept_version == PROTOCOL_VERSION10 or not enc_pass: s = self.str_to_bytes(self.password) dpb += bs([isc_dpb_password, len(s)]) + s else: enc_pass = self.str_to_bytes(enc_pass) dpb += bs([isc_dpb_password_enc, len(enc_pass)]) + enc_pass if self.role: s = self.str_to_bytes(self.role) dpb += bs([isc_dpb_sql_role_name, len(s)]) + s dpb += bs([isc_dpb_process_id, 4]) + int_to_bytes(os.getpid(), 4) s = self.str_to_bytes(sys.argv[0]) dpb += bs([isc_dpb_process_name, len(s)]) + s if self.auth_data: s = bytes_to_hex(self.auth_data) dpb += bs([isc_dpb_specific_auth_data, len(s)]) + s if self.timezone: s = self.str_to_bytes(self.timezone) dpb += bs([isc_dpb_session_time_zone, len(s)]) + s p = xdrlib.Packer() p.pack_int(self.op_attach) p.pack_int(0) # Database Object ID p.pack_string(self.str_to_bytes(self.filename)) p.pack_bytes(dpb) self.sock.send(p.get_buffer())
def write_patch(bname, pname, mesh="hemi"): """Write out the mesh 'mesh' in the blender file 'bname' into patch file 'pname' This is a necessary step for flattening the surface in freesurfer Parameters ---------- bname : str blender file name that contains the mesh pname : str name of patch file to be saved mesh : str name of mesh in blender file """ p = xdrlib.Packer() p.pack_string(pname.encode()) p.pack_string(mesh.encode()) with tempfile.NamedTemporaryFile() as tf: tf.write(p.get_buffer()) tf.flush() code = """with open('{tfname}', 'rb') as fp: u = xdrlib.Unpacker(fp.read()) pname = u.unpack_string().decode('utf-8') mesh = u.unpack_string().decode('utf-8') blendlib.save_patch(pname, mesh) """.format(tfname=tf.name) _call_blender(bname, code)
def _op_detach(self): if self.db_handle is None: raise OperationalError('_op_detach() Invalid db handle') p = xdrlib.Packer() p.pack_int(self.op_detach) p.pack_int(self.db_handle) self.sock.send(p.get_buffer())
def encode(self, message): packer = xdrlib.Packer() statusType = message.get('statusType', 2) # other statusId = message.get('statusId', 1) # reserved s = ((statusType & 0xffff) << 16) | (statusId & 0xffff) packer.pack_uint(s) return packer.get_buffer()
def add_sensor(self, sensor_name, sensor_type="", sensor_label="", sensor_desc=""): """ Add a sensor to the device. type, label, and description are optional. """ logger.debug("add_sensor(sensor_name='%s', sensor_type='%s', sensor_label='%s', sensor_desc='%s')", sensor_name, sensor_type, sensor_label, sensor_desc) #addSensor allows you to set the sensor type label and description. All fileds are strings. #we need to pack these strings into an xdr structure packer = xdrlib.Packer() packer.pack_int(1) #version 1 packer.pack_string(sensor_type) packer.pack_string(sensor_label) packer.pack_string(sensor_desc) data = packer.get_buffer() response = self.url("/sensors/%s/"%sensor_name)\ .param("version", "1")\ .data(data)\ .content_type("application/xdr").put() #if response is 201 created then we know the sensor was added if response.status_code != httplib.CREATED: raise Exception("add sensor failed. status: %s %s message:%s"%(response.status_code , response.reason, response.text)) return self.sensor(sensor_name)
def _op_get_segment(self, blob_handle): p = xdrlib.Packer() p.pack_int(self.op_get_segment) p.pack_int(blob_handle) p.pack_int(self.buffer_length) p.pack_int(0) send_channel(self.sock, p.get_buffer())
def rpc(self, code, *args, **kwargs): client = kwargs.get("client", 0) packer = xdrlib.Packer() packer.pack_uint(code) packer.pack_uint(client) self._pack_args(packer, args) packer = libhal.slip_encode(packer.get_buffer()) if self.debug_io: logger.debug("send: %s", ":".join("{:02x}".format(ord(c)) for c in packer)) yield self.iostream.write(packer) while True: try: unpacker = yield self.iostream.read_until(SLIP_END) except StreamClosedError: raise HAL_ERROR_RPC_TRANSPORT() if self.debug_io: logger.debug( "recv: %s", ":".join("{:02x}".format(ord(c)) for c in unpacker)) unpacker = libhal.slip_decode(unpacker) if not unpacker: continue unpacker = ContextManagedUnpacker("".join(unpacker)) if unpacker.unpack_uint() == code: break client = unpacker.unpack_uint() self._raise_if_error(unpacker.unpack_uint()) raise Return(unpacker)
def __init__(self, parentAddr=None, parentDirectory=None, load=1, autoShutdown=1, readonly=False): import atexit import time import xdrlib self.logFile = None self.setupLogFile() self.target = ['default'] self.parent = None self.saveTimer = None self.shutdownTimer = None self.lastAccess = time.time() self.saveFilename = 'RDict.db' self.addrFilename = 'RDict.loc' self.parentAddr = parentAddr self.isServer = 0 self.readonly = readonly self.parentDirectory = parentDirectory self.packer = xdrlib.Packer() self.unpacker = xdrlib.Unpacker('') self.stopCmd = pickle.dumps(('stop', )) self.writeLogLine('Greetings') self.connectParent(self.parentAddr, self.parentDirectory) if load: self.load() if autoShutdown and useThreads: atexit.register(self.shutdown) self.writeLogLine('SERVER: Last access ' + str(self.lastAccess)) return
async def handshake( self, last_seen_order: int) -> Tuple[int, crypto.Cipher, int]: packer = xdrlib.Packer() packer.pack_bytes(self.client_id.encode('ascii')) packer.pack_hyper(last_seen_order) packer.pack_bytes(self.symmetric_key) packer.pack_uint(self.VERSION) await self.send_bytes(self.server_keys.encrypt(packer.get_buffer())) logger.debug('sent handshake') response = await receive_msg(self, timeout=3) logger.debug('received handshake') unpacker = xdrlib.Unpacker(self.client_keys.decrypt(response)) data_to_sign = unpacker.unpack_bytes() last_seen_sequence = unpacker.unpack_hyper() server_aes_key = unpacker.unpack_bytes() try: server_version = unpacker.unpack_uint() except EOFError: server_version = 1 await self.send_bytes(self.client_keys.sign(data_to_sign)) logger.debug('sent client key') return last_seen_sequence, crypto.Cipher( server_aes_key), server_version