def send(self, *args): """ Injects a packet into the network stack. Args could be a tuple or two different values, or an high level packet. In each case the raw data and the meta about the direction and interface to use are required. If the packet is an highlevel packet, recalculates the checksum before sending. The return value is the number of bytes actually sent. The injected packet may be one received from receive(), or a modified version, or a completely new packet. Injected packets can be captured and diverted again by other WinDivert handles with lower priorities. The remapped function is DivertSend: BOOL WinDivertSend( __in HANDLE handle, __in PVOID pPacket, __in UINT packetLen, __in PWINDIVERT_ADDRESS pAddr, __out_opt UINT *sendLen ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send """ data, address = self.__parse_send_args(*args) send_len = c_int(0) self._lib.WinDivertSend(self._handle, data, len(data), byref(address), byref(send_len)) return send_len
def setup_console(self): """Initializes the screen frame buffer. Swaps the current screen buffer with a brand new created back buffer where the characters can be written to the flicker-free rectangular region. """ self._console = get_std_handle(STD_OUTPUT_HANDLE) # could not get the standard # console handle, raise an exception if self._console == INVALID_HANDLE_VALUE: raise TermInitializationError() buffer_info = CONSOLE_SCREEN_BUFFER_INFO() get_console_screen_buffer_info(self._console, byref(buffer_info)) get_console_cursor_info(self._console, byref(self._cursor_info)) self._cursor_info.visible = False self._cols = buffer_info.size.x self._rows = buffer_info.size.y self._size = COORD(self._cols, self._rows) self._rect = SMALL_RECT(0, 0, self._cols - 1, self._rows - 1) self._char_buffer = (CHAR_INFO * (self._size.x * self._size.y))() self._framebuffer = create_console_screen_buffer( GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, None, CONSOLE_TEXTMODE_BUFFER, None) if self._framebuffer == INVALID_HANDLE_VALUE: raise TermInitializationError() # hide the cursor and swap # the console active screen buffer set_console_cursor_info(self._framebuffer, byref(self._cursor_info)) set_console_active_screen_buffer(self._framebuffer)
def recv(self, bufsize=Defaults.PACKET_BUFFER_SIZE): """ Receives a diverted packet that matched the filter passed to the handle constructor. The return value is a pair (raw_packet, meta) where raw_packet is the data read by the handle, and meta contains the direction and interface indexes. The received packet is guaranteed to match the filter. The remapped function is WinDivertRecv: BOOL WinDivertRecv( __in HANDLE handle, __out PVOID pPacket, __in UINT packetLen, __out_opt PWINDIVERT_ADDRESS pAddr, __out_opt UINT *recvLen ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv """ packet = create_string_buffer(bufsize) address = WinDivertAddress() recv_len = c_int(0) self._lib.WinDivertRecv(self._handle, packet, bufsize, byref(address), byref(recv_len)) return packet[:recv_len.value], CapturedMetadata( (address.IfIdx, address.SubIfIdx), address.Direction)
def hook(self): def on_event(*args, **kwargs): call_next = True # noinspection PyBroadException try: self.handler(*args, **kwargs) except BlockNextHookException: call_next = False except: print_exception(*sys.exc_info()) finally: if not call_next: return 1 return _win32_CallNextHookEx(None, *args, **kwargs) func = ctypes.CFUNCTYPE(ctypes.c_int, *self.signature) pntr = func(on_event) hmod = _win32_GetModuleHandleA(None) self.hook_id = _win32_SetWindowsHookExA(self.event, pntr, hmod, 0) atexit.register(self.unhook) msg = wintypes.MSG() while self.hook_id: if self.polling: _win32_PeekMessageW(None, 0, 0, 0, 0) else: _win32_GetMessageW(byref(msg), 0, 0, 0) _win32_TranslateMessage(byref(msg)) _win32_DispatchMessageW(byref(msg))
def inet_ntop(address_family, packed_ip, encoding="UTF-8"): addr = sockaddr() addr.sa_family = address_family addr_size = c_int(sizeof(addr)) ip_string = create_string_buffer(128) ip_string_size = c_int(sizeof(addr)) if address_family == socket.AF_INET: if len(packed_ip) != sizeof(addr.ipv4_addr): raise socket.error('packed IP wrong length for inet_ntop') memmove(addr.ipv4_addr, packed_ip, 4) elif address_family == socket.AF_INET6: if len(packed_ip) != sizeof(addr.ipv6_addr): raise socket.error('packed IP wrong length for inet_ntop') memmove(addr.ipv6_addr, packed_ip, 16) else: raise socket.error('unknown address family') if WSAAddressToStringA(byref(addr), addr_size, None, ip_string, byref(ip_string_size)) != 0: raise socket.error(FormatError()) return (ip_string[:ip_string_size.value - 1]).decode(encoding)
def c_multiplication(a, b): class Collection(Structure): _fields_ = [("size", c_int), ("data", (c_float * a.shape[1]) * a.shape[0])] libmatmult = ctypes.CDLL("./multiply.so") libmatmult.multiply.argtypes = [POINTER(Collection)] libmatmult.multiply.restype = None t_a = Collection() t_b = Collection() t_c = Collection() for i in range(a.shape[0]): for j in range(a.shape[1]): t_a.data[i][j] = a[i][j] t_c.data[i][j] = a[i][j] for i in range(b.shape[0]): for j in range(b.shape[1]): t_b.data[i][j] = b[i][j] start = time.time() libmatmult.multiply(byref(t_a), byref(t_b), byref(t_c), a.shape[0], a.shape[1]) end = time.time() print(end - start) c_result = np.ones(a.shape) for i in range(a.shape[0]): for j in range(a.shape[1]): c_result = (t_c.data[i][j]) return c_result
def _receive_async(self, callback=None, bufsize=Defaults.PACKET_BUFFER_SIZE): """ Receives a diverted packet that matched the filter passed to the handle constructor asynchronously. The remapped function is WinDivertRecvEx: BOOL WinDivertRecvEx( __in HANDLE handle, __out PVOID pPacket, __in UINT packetLen, __in UINT64 flags, __out_opt PWINDIVERT_ADDRESS pAddr, __out_opt UINT *recvLen, __inout_opt LPOVERLAPPED lpOverlapped ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv_ex """ if not hasattr(self._lib, "WinDivertRecvEx"): raise MethodUnsupportedException("Async receive is not supported with this version of WinDivert") future = FuturePacket(self._handle, callback=callback, bufsize=bufsize) retcode = self._lib.WinDivertRecvEx(self._handle, byref(future.packet), sizeof(future.packet), 0, byref(future.address), byref(future.recv_len), byref(future.overlapped)) last_error = GetLastError() if not retcode and last_error == ErrorCodes.ERROR_IO_PENDING: return future.get_result() else: raise AsyncCallFailedException( "Async receive failed with retcode %d and LastError %d" % (retcode, last_error))
def parse(self, text, scope=None): """Extract builtin entities from *text* Args: text (str): Input scope (list of str, optional): List of builtin entity labels. If defined, the parser will extract entities using the provided scope instead of the entire scope of all available entities. This allows to look for specifics builtin entity kinds. Returns: list of dict: The list of extracted entities """ if not isinstance(text, str): raise TypeError("Expected language to be of type 'str' but found: " "%s" % type(text)) if scope is not None: if not all(isinstance(e, str) for e in scope): raise TypeError( "Expected scope to contain objects of type 'str'") scope = [e.encode("utf8") for e in scope] arr = CStringArray() arr.size = c_int(len(scope)) arr.data = (c_char_p * len(scope))(*scope) scope = byref(arr) with string_pointer(c_char_p()) as ptr: exit_code = lib.snips_nlu_ontology_extract_builtin_entities_json( self._parser, text.encode("utf8"), scope, byref(ptr)) check_ffi_error( exit_code, "Something went wrong when extracting " "builtin entities") result = string_at(ptr) return json.loads(result.decode("utf8"))
def Init_Can(self, ZLG_Baud, Device_handle): self.Baud = ZLG_Baud self.ZLGDeviceHandle = Device_handle print("ZLG baud:{0}".format(hex(self.Baud))) print("ZLG device handle:{0}".format(self.ZLGDeviceHandle)) ZLG_USB_CAN_Info = VCI_BOARD_INFO() ZLG_USB_CAN_Info_P = byref(ZLG_USB_CAN_Info) self.ZLG_USB_CAN_Dll.ReadBoardInfo(self.ZLGDeviceHandle, 0, ZLG_USB_CAN_Info_P) #read info print("HW:%#x\n" % ZLG_USB_CAN_Info.hw_Version) print("FW:%#x\n" % ZLG_USB_CAN_Info.fw_Version) print("DR:%#x\n" % ZLG_USB_CAN_Info.dr_Version) print("IN:%#x\n" % ZLG_USB_CAN_Info.in_Version) print("IRQ:%#d\n" % ZLG_USB_CAN_Info.irq_Num) print("CAN_NUM:%#d\n" % ZLG_USB_CAN_Info.can_Num) print("STR_serial:%s\n" % ZLG_USB_CAN_Info.str_Serial_Num) print("Str_Hw_NUM:%s\n" % ZLG_USB_CAN_Info.str_hw_Type) ZLG_USB_CAN_INIT = VCI_INIT_CONFIG() ZLG_USB_CAN_INIT.AccCode = 0x00000000 ZLG_USB_CAN_INIT.AccMaxk = 0x00FFFFFF ZLG_USB_CAN_INIT.Mode = 0 ZLG_USB_CAN_INIT.Fiter = 1 ZLG_USB_CAN_INIT.Timing0 = 0 ZLG_USB_CAN_INIT.Timing1 = 0x1c ZLG_USB_CAN_INIT_P = byref(ZLG_USB_CAN_INIT) print(ZLG_USB_CAN_INIT.Mode) print(type(self.Baud)) baud_value = ctypes.c_int32(self.Baud) print("ZLG baud value:{0}".format((baud_value))) set_can_reference = self.ZLG_USB_CAN_Dll.SetReference( self.ZLGDeviceHandle, 0, 0, 0, ctypes.byref(baud_value)) if (set_can_reference == 1): print("can set reference ok\r\n") init_can = self.ZLG_USB_CAN_Dll.InitCAN( self.ZLGDeviceHandle, 0, 0, ZLG_USB_CAN_INIT_P) #init can if (init_can == 1): self.set_can_state = 0 print("CAN init success\r\n") ZLG_USB_CAN_FILTER = VCI_FILTER_RECORD() if File_data.RES_ID & 0xFFFFF000 != 0: #扩展帧 ZLG_USB_CAN_FILTER.ExtFrame = 1 else: ZLG_USB_CAN_FILTER.ExtFrame = 0 ZLG_USB_CAN_FILTER.Start = File_data.RES_ID ZLG_USB_CAN_FILTER.End = File_data.RES_ID ZLG_USB_CAN_FILTER_P = byref(ZLG_USB_CAN_FILTER) set_fielter = self.ZLG_USB_CAN_Dll.SetReference( self.ZLGDeviceHandle, 0, 0, 1, ZLG_USB_CAN_FILTER_P) if set_fielter == 1: print("set fielter success:{0}".format(File_data.RES_ID)) else: pass else: print("CAN init error\r\n") self.set_can_state = 1 else: print("can set reference error\r\n") self.set_can_state = 1 return self.set_can_state
def __or__(self, other: 'PyEnvironment') -> 'PyEnvironment': assert isinstance(other, PyEnvironment) d1 = DimChange() d2 = DimChange() environment = libapron.ap_environment_lce(self, other, byref(d1), byref(d2)) if not environment: raise ValueError('incompatible environments') return PyEnvironment(environment)
def login(self): loginfo = NET_DEVICEINFO_Ex() err = NET_DEVICEINFO_Ex() self.userSession = self.nvrDll.CLIENT_LoginEx2( c_char_p(self.nvrIp.encode('ascii')), self.nvrPort, c_char_p(self.nvrLogin.encode('ascii')), c_char_p(self.nvrPass.encode('ascii')), 0, None, byref(loginfo), byref(err)) return self.userSession
def compute_all_ngrams(tokens, max_ngram_size): with ngram_array_pointer(pointer(CNgramArray())) as ptr: nb_tokens = len(tokens) c_tokens = CStringArray() c_tokens.data = (c_char_p * nb_tokens)( *[token.encode("utf8") for token in tokens]) c_tokens.size = nb_tokens exit_code = lib.snips_nlu_utils_compute_all_ngrams( byref(c_tokens), max_ngram_size, byref(ptr)) check_ffi_error( exit_code, "Something went wrong when computing all ngrams for '%s'" % tokens) array = ptr.contents return array.to_pylist()
def inet_pton(address_family, ip_string, encoding="UTF-8"): addr = sockaddr() addr.sa_family = address_family addr_size = c_int(sizeof(addr)) if WSAStringToAddressA(ip_string.encode(encoding), address_family, None, byref(addr), byref(addr_size)) != 0: raise socket.error(FormatError()) if address_family == socket.AF_INET: return string_at(addr.ipv4_addr, 4) if address_family == socket.AF_INET6: return string_at(addr.ipv6_addr, 16) raise socket.error('unknown address family')
def createNextCover(self, name : str, data : CoverData, sourceinfo : SourceInfo) -> int: sourceinfo_p = None if sourceinfo is None else byref(_LibSourceInfo.ctor(sourceinfo)) data_p = byref(LibCoverData.ctor(data)) index = get_lib().ucis_CreateNextCover( self.db, self.obj, str.encode(name), data_p, sourceinfo_p) return LibCoverIndex(self.db, self.obj, index)
def write(self, char_seq): col = 0 index = 0 line_feed = False for char in char_seq: if char == '\n': line_feed = True col += 1 if col == self.cols: col = 0 if line_feed: line_feed = False continue if line_feed: line_feed = False blank_index = col while blank_index <= self.cols: self.char_buffer[blank_index - 1].char.unicode_char = ' ' blank_index += 1 index += 1 col = 0 continue self.char_buffer[index].char.unicode_char = char self.char_buffer[index].attributes = LIGHT_WHITE index += 1 write_console_output(self.backbuffer_handle, self.char_buffer, self.size, self.coord, byref(self.rect))
def Receive_data(self): return_data = [] return_len = 0 VCI_CAN_OBJ_Info = VCI_CAN_OBJ() VCI_CAN_OBJ_Info.TimeStamp = 0 VCI_CAN_OBJ_Info.TimeFlag = 0 VCI_CAN_OBJ_Info.SendType = 0 VCI_CAN_OBJ_Info.RemoteFlag = 0 VCI_CAN_OBJ_Info.ExternFlag = 0 VCI_CAN_OBJ_Info.DataLen = 0 VCI_CAN_OBJ_Info_P = byref(VCI_CAN_OBJ_Info) self.receive_frame_num = self.ZLG_USB_CAN_Dll.GetReceiveNum( self.ZLGDeviceHandle, 0, 0) if (self.receive_frame_num != 0): ret_data = self.ZLG_USB_CAN_Dll.Receive(self.ZLGDeviceHandle, 0, 0, VCI_CAN_OBJ_Info_P, 1, 0) if ret_data != 0xFFFFFFFF: self.Tx_conf = 0 return_len = VCI_CAN_OBJ_Info.DataLen return_ID = VCI_CAN_OBJ_Info.Id #if return_ID == 0x72e: for i in (range(0, return_len)): return_data.append(VCI_CAN_OBJ_Info.Data[i]) #print("receive ID:{0}".format(list(map(hex,return_data)))) else: return_ID = None else: return_ID = None return (return_ID, return_len, return_data)
def hide(self): SetWindowPos(self.hwnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW) data = APPBARDATA() data.cbSize = ctypes.sizeof(APPBARDATA) data.lParam = 1 SHAppBarMessage(ABM_SETSTATE, byref(data)) logging.info('Hide task bar.')
def vJoyFfbCap(self): yes = c_bool() ok = self._vjoy.vJoyFfbCap(byref(yes)) if ok: return yes.value else: raise RuntimeError('Calling: vJoyFfbCap failed.')
def GetNumberExistingVJD(self): n = c_int() ok = self._vjoy.GetNumberExistingVJD(byref(n)) if ok: return n.value else: return -1
def _send_async(self, *args): """ Injects a packet into the network stack. The remapped function is WinDivertSendEx: BOOL WinDivertSendEx( __in HANDLE handle, __in PVOID pPacket, __in UINT packetLen, __in UINT64 flags, __in PWINDIVERT_ADDRESS pAddr, __out_opt UINT *sendLen, __inout_opt LPOVERLAPPED lpOverlapped ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send_ex """ if not hasattr(self._lib, "WinDivertSendEx"): raise MethodUnsupportedException("Async send is not supported with this version of WinDivert") data, address = self.__parse_send_args(*args) send_len = len(data) retcode = self._lib.WinDivertSendEx(self._handle, data, send_len, 0, byref(address), None, None) last_error = GetLastError() if retcode and last_error == ErrorCodes.ERROR_IO_PENDING: return True else: raise AsyncCallFailedException("Async send failed with retcode %d and LastError %d" % (retcode, last_error))
def GetvJoyMaxDevices(self): n = c_int() ok = self._vjoy.GetvJoyMaxDevices(byref(n)) if ok: return n.value else: return -1
def _query_handle(self, handle, klass, object_info_type): """Gets the object handle info. Parameters ---------- handle: HANDLE handle object klass: int the class of information to query object_info_type: Structure structure type which holds the handle info """ buff = malloc(self._object_buff_size) rlen = ULONG() status = nt_query_object(handle, klass, buff, self._object_buff_size, byref(rlen)) if status >= 0: info = cast(buff, POINTER(object_info_type)) self._buffers.append(buff) return info else: # reallocate the buffer size # and try again buff = realloc(buff, rlen.value) status = nt_query_object(handle, klass, buff, self._object_buff_size, None) if status >= 0: info = cast(buff, POINTER(object_info_type)) self._buffers.append(buff) return info else: free(buff) return None
def CheckCFAdc(xpin, minlim, maxlim): try: mypin = PinTuples.index(xpin) retval = loadedll.GetColdFireAdc(mypin, byref(floatBufr)) myTxt = "dllCallexe = GetColdFireAdc(" + xpin + ",floatBufr)\n" myTxt += "RValue = " + str(floatBufr.value) + "\n" myTxt += "LowLimit = " + str(minlim) + "\n" myTxt += "HighLimit = " + str(maxlim) + "\n" myTxt += "StepType = NumericLimitTest\n" myTxt += "Units = Volts\n" if floatBufr.value < float(minlim) or floatBufr.value > float(maxlim): myTxt += "RStatus = Fail\n" else: myTxt += "RStatus = PASS\n" OUT_LIST.append([myTxt]) return retval except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n") OUT_LIST.append([ "error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n\n" ])
def _send_async(self, *args): """ Injects a packet into the network stack. The remapped function is WinDivertSendEx: BOOL WinDivertSendEx( __in HANDLE handle, __in PVOID pPacket, __in UINT packetLen, __in UINT64 flags, __in PWINDIVERT_ADDRESS pAddr, __out_opt UINT *sendLen, __inout_opt LPOVERLAPPED lpOverlapped ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send_ex """ if not hasattr(self._lib, "WinDivertSendEx"): raise MethodUnsupportedException( "Async send is not supported with this version of WinDivert") data, address = self.__parse_send_args(*args) send_len = len(data) retcode = self._lib.WinDivertSendEx(self._handle, data, send_len, 0, byref(address), None, None) last_error = GetLastError() if retcode and last_error == ErrorCodes.ERROR_IO_PENDING: return True else: raise AsyncCallFailedException( "Async send failed with retcode %d and LastError %d" % (retcode, last_error))
def createScope(self, name:str, srcinfo:SourceInfo, weight:int, source, type, flags): srcinfo_p = None if srcinfo is None else byref(_LibSourceInfo.ctor(srcinfo)) print("createScope: db=" + str(self.db) + " obj=" + str(self.obj) + " name=" + str(name) + " srcinfo_p=" + str(srcinfo_p) + " weight=" + str(weight) + "source=" + hex(source) + " type=" + hex(type) + " flags=" + hex(flags)); sh = get_lib().ucis_CreateScope( self.db, self.obj, None if name is None else str.encode(name), srcinfo_p, weight, source, type, flags) if sh is None: print("Error: createScope failed: parent=" + str(self.obj)) raise Exception("Failed to create scope") return LibScope(self.db, sh)
def GetScannerDeviceType(x): try: retval = loadedll.GetScannerDeviceType(byref(intBufr1)) myTxt = "RValue = " + str(intBufr1.value) + "\n" myTxt += "LowLimit = 7 \n" myTxt += "HighLimit = 7 \n" myTxt += "StepType = NumericLimitTest\n" myTxt += "Units = retval\n" if intBufr1.value == int( x): #GEP2016 scanners return a Device Type of 7 myTxt += "RStatus = PASS\n" else: myTxt += "RStatus = Fail\n" OUT_LIST.append([myTxt]) return retval except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n") OUT_LIST.append([ "error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n\n" ])
def get_result(self): ready = False while not ready: iolen = DWORD() if GetOverlappedResult(self.handle, byref(self.overlapped), byref(iolen), False): # print("%d Executing callback" % GetLastError()) if self.callback: self.callback(self.packet[:iolen.value], CapturedMetadata((self.address.IfIdx, self.address.SubIfIdx), self.address.Direction)) self.complete = True ready = (GetLastError() != 996) yield self sleep(self.iodelay)
def CheckRealtimeClock(x): try: retval = loadedll.Get_RTC_Time_GEP(byref(uLongBufr)) time_now = time.time() myTxt = "dllCallexe = Get_RTC_Time_GEP()\n" time_diff = abs(time_now - int(uLongBufr.value)) myTxt += "RValue = " + str(time_diff) + "\n" myTxt += "LowLimit = 0\n" myTxt += "HighLimit = " + x + "\n" myTxt += "StepType = NumericLimitTest\n" myTxt += "Units = retval\n" if time_diff <= int(x): myTxt += "RStatus = PASS\n" else: myTxt += "RStatus = Fail\n" OUT_LIST.append([myTxt]) return retval except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n") OUT_LIST.append([ "error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n\n" ])
def build(cls, language, gazetteer_entity_parser_path=None): """Build a `BuiltinEntityParser` Args: language (str): Language identifier gazetteer_entity_parser_path (str, optional): Path to a gazetteer entity parser. If None, the builtin entity parser will only use grammar entities. """ if isinstance(gazetteer_entity_parser_path, Path): gazetteer_entity_parser_path = str(gazetteer_entity_parser_path) if not isinstance(language, str): raise TypeError("Expected language to be of type 'str' but found:" " %s" % type(language)) parser_config = dict( language=language.upper(), gazetteer_parser_path=gazetteer_entity_parser_path) parser = pointer(c_void_p()) json_parser_config = bytes(json.dumps(parser_config), encoding="utf8") exit_code = lib.snips_nlu_ontology_create_builtin_entity_parser( byref(parser), json_parser_config) check_ffi_error( exit_code, "Something went wrong while creating the " "builtin entity parser") return cls(parser)
def CheckCanRxStatus(nTestValue): try: retval = loadedll.VcomReadCANRx(byref(sByteBufr)) OUT_LIST.append(["dllCallexe = VcomReadCANRx(sByteBufr)\n"]) myTxt = "RValue = " + str(sByteBufr.value) + "\n" myTxt += "LowLimit = " + nTestValue + "\n" myTxt += "HighLimit = " + nTestValue + "\n" myTxt += "StepType = NumericLimitTest\n" myTxt += "Units = retval\n" if sByteBufr.value == c2int(nTestValue): myTxt += "RStatus = PASS\n" # : CAN Rx value checks okay" else: myTxt += "RStatus = FAIL\n" # : CAN Rx value Failed" OUT_LIST.append([myTxt]) return retval except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n") OUT_LIST.append([ "error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n\n" ])
def get_builtin_entity_examples(builtin_entity_kind, language): """Provides some examples of the builtin entity in the specified language """ global _ENTITIES_EXAMPLES if not isinstance(builtin_entity_kind, str): raise TypeError("Expected `builtin_entity_kind` to be of type 'str' " "but found: %s" % type(builtin_entity_kind)) if not isinstance(language, str): raise TypeError( "Expected `language` to be of type 'str' but found: %s" % type(language)) if builtin_entity_kind not in _ENTITIES_EXAMPLES: _ENTITIES_EXAMPLES[builtin_entity_kind] = dict() if language not in _ENTITIES_EXAMPLES[builtin_entity_kind]: with string_array_pointer(pointer(CStringArray())) as ptr: exit_code = lib.snips_nlu_ontology_builtin_entity_examples( builtin_entity_kind.encode("utf8"), language.encode("utf8"), byref(ptr)) check_ffi_error( exit_code, "Something went wrong when retrieving " "builtin entity examples") array = ptr.contents _ENTITIES_EXAMPLES[builtin_entity_kind][language] = list( array.data[i].decode("utf8") for i in range(array.size)) return _ENTITIES_EXAMPLES[builtin_entity_kind][language]
def print_log(shader): length = c_int() glGetShaderiv(shader, GL_INFO_LOG_LENGTH, byref(length)) if length.value > 0: log = create_string_buffer(length.value) print(glGetShaderInfoLog(shader))
def getSourceInfo(self)->SourceInfo: libsrcinfo = _LibSourceInfo() sourceinfo_p = byref(libsrcinfo) get_lib().ucis_GetScopeSourceInfo(self.db, self.obj, sourceinfo_p) return LibSourceInfo.ctor(self.db, libsrcinfo)
def createInstance(self, name : str, fileinfo : SourceInfo, weight : int, source : SourceT, type : ScopeTypeT, du_scope : Scope, flags : FlagsT): fileinfo_p = None if fileinfo is None else byref(_LibSourceInfo.ctor(fileinfo)) sh = get_lib().ucis_CreateInstance( self.db, self.obj, str.encode(name), fileinfo_p, weight, source, type, du_scope.obj, flags) if sh is None: print("Error: ucis_CreateInstance failed: du=" + str(du_scope) + " du.obj=" + str(du_scope.obj)) raise Exception("ucis_CreateInstance failed") return LibScope(self.db, sh)
def show(self): SetWindowPos(self.hwnd, 0, 0, 0, 0, 0, SWP_SHOWWINDOW) data = APPBARDATA() data.cbSize = ctypes.sizeof(APPBARDATA) data.lParam = 0 SHAppBarMessage(ABM_SETSTATE, byref(data)) logging.info('Show task bar.')
def ReadFpgaRegister(wRegister): try: wRegister = c2int(wRegister, 16) retval = loadedll.VcomGet1Reg(wRegister, byref(sByteBufr)) OUT_LIST.append(["dllCallexe = loadedll.VcomGet1Reg \n"]) OUT_LIST.append(["RValue = ", sByteBufr.value, "\n"]) OUT_LIST.append(["hex(wRegister) = ", hex(wRegister), "\n"]) OUT_LIST.append([ "binary(sByteBufr.value,pre='') = ", binary(sByteBufr.value, pre=''), "\n" ]) return retval except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n") OUT_LIST.append([ "error = ", str(exc_type), ", ", fname, ", ", str(exc_tb.tb_lineno), ", ", str(e), " in function ", sys._getframe().f_code.co_name, "\n\n" ])
def createCross(self, name: str, srcinfo: SourceInfo, weight: int, source: SourceT, points_l: List['Coverpoint']) -> CoverType: srcinfo_p = None if srcinfo is None else byref( _UcdbSourceInfo.ctor(srcinfo)) points = (c_void_p * len(points_l))() for i, cp in enumerate(points_l): points[i] = cp.obj cr_o = get_lib().ucdb_CreateCross(self.db, self.obj, str.encode(name), srcinfo_p, weight, source, len(points_l), byref(points)) return UcdbCross(self.db, cr_o) raise NotImplementedError()
def write_console(self, charseq): """Writes a string to a console frame buffer beginning at the current cursor location. charseq: str the string to be written on the frame buffer """ write_console_unicode(self._framebuffer, charseq, len(charseq), byref(c_ulong()), None)
def find_devices(self): self.devices = POINTER(pcap_if_t)() self.errbuf= create_string_buffer(PCAP_ERRBUF_SIZE) if (pcap_findalldevs(byref(self.devices ), self.errbuf) == -1): msg = "Error in pcap_findalldevs: %s\n" % self.errbuf.value print (msg) logging.error(msg) sys.exit(1)
def cls(self): for y in range(self.rows): for x in range(self.cols): i = (y * self.cols) + x self.char_buffer[i].char.unicode_char = ' ' write_console_output(self.backbuffer_handle, self.char_buffer, self.coord, self.size, byref(self.rect))
def create_shader(self, strings, shader_type): count = len(strings) # if we have no source code, ignore this shader if count < 1: return # create the shader handle shader = glCreateShader(shader_type) shaderstrings = [] for string in strings: shaderstrings.append(bytes(string, 'ascii')) # convert the source strings into a ctypes pointer-to-char array, and # upload them this is deep, dark, dangerous black magic - don't try # stuff like this at home! src = (c_char_p * count)(*shaderstrings) glShaderSource(shader, count, cast( pointer(src), POINTER(POINTER(c_char))), None) # compile the shader glCompileShader(shader) temp = c_int(0) # retrieve the compile status glGetShaderiv(shader, GL_COMPILE_STATUS, byref(temp)) # if compilation failed, print the log if not temp: # retrieve the log length glGetShaderiv(shader, GL_INFO_LOG_LENGTH, byref(temp)) # create a buffer for the log buffer = create_string_buffer(temp.value) # retrieve the log text glGetShaderInfoLog(shader, temp, None, buffer) # print the log to the console print(buffer.value) else: # all is well, so attach the shader to the program glAttachShader(self.handle, shader)
def link(self): # link the program glLinkProgram(self.handle) temp = c_int(0) # retrieve the link status glGetProgramiv(self.handle, GL_LINK_STATUS, byref(temp)) # if linking failed, print the log if not temp: # retrieve the log length glGetProgramiv(self.handle, GL_INFO_LOG_LENGTH, byref(temp)) # create a buffer for the log buffer = create_string_buffer(temp.value) # retrieve the log text glGetProgramInfoLog(self.handle, temp, None, buffer) # print the log to the console print(buffer.value) else: # all is well, so we are linked self.linked = True
def cls(self): """Clears the current screen buffer. """ for y in range(self._rows): for x in range(self._cols): i = (y * self._cols) + x self._char_buffer[i].char.unicode_char = ' ' write_console_output(self._framebuffer, self._char_buffer, self._coord, self._size, byref(self._rect))
def emit(self, kevent, **kwargs): """Renders the kevent to the standard output stream. Uses the default output format or JSON to render the kernel event to standard output stream. The default output format is as follows: id timestamp cpu process (process id) - kevent (parameters) -- --------- --- ------- ----------- ------- ------------ Example: 160 13:27:27.554 0 wmiprvse.exe (1012) - CloseFile (file=C:\\WINDOWS\\SYSTEM32\\RSAENH.DLL, tid=2668) Parameters ---------- kevent: KEvent the information regarding the kernel event kwargs: dict console adapter configuration """ if isinstance(kevent, dict): kevt = json.dumps(kevent) else: pid, proc = kevent.get_thread() if 'pretty' in self._fmt: kevt = RENDER_FORMAT % (kevent.kid, kevent.ts.time(), kevent.cpuid, proc, pid, kevent.name, self._format_params(kevent.params)) else: kevt = json.dumps(dict(id=kevent.kid, timestamp=kevent.ts.strftime(self._timestamp_pattern), cpuid=kevent.cpuid, proc=proc, pid=pid, name=kevent.name, params=kevent.params)) kevt += '\n' # write the output on the standard output stream write_console_unicode(self._stdout_handle, kevt, len(kevt), byref(c_ulong()), None)
def query_handles(self, pid=None): raw_handles = self._enum_handles(pid) current_ps = HANDLE(get_current_process()) handles = [] # find the object handles for the process for _, handle in raw_handles.items(): ps_handle = open_process(PROCESS_DUP_HANDLE, False, handle.pid) if ps_handle: handle_copy = HANDLE() # to query the object handle # we need to duplicate it in # the address space of the current process status = duplicate_handle(ps_handle, handle.handle, current_ps, byref(handle_copy), 0, 0, 0) if status != ERROR_SUCCESS: # get the object type handle_type = self._query_handle(handle_copy, PUBLIC_OBJECT_TYPE_INFORMATION, OBJECT_TYPE_INFORMATION) if handle_type: handle_type = cast(handle_type.contents.type_name.buffer, c_wchar_p) \ .value \ .upper().replace(' ', '_') # query for object name # (file names, registry keys, # sections, ALPC ports, etc) # check the access mask to make # sure `NtQueryObject` won't hang if handle_type in self._handle_types and \ handle.access_mask not in self._nasty_access_masks: handle_name = self._query_handle(handle_copy, PUBLIC_OBJECT_NAME_INFORMATION, UNICODE_STRING) if handle_name: handle_name = cast(handle_name.contents.buffer, c_wchar_p).value handle_info = HandleInfo(handle.handle, handle.obj, HandleType(HandleType.__getattr__(handle_type)), handle_name, handle.pid) handles.append(handle_info) close_handle(handle_copy) close_handle(ps_handle) return handles
def recv(self, bufsize=Defaults.PACKET_BUFFER_SIZE): """ Receives a diverted packet that matched the filter passed to the handle constructor. The return value is a pair (raw_packet, meta) where raw_packet is the data read by the handle, and meta contains the direction and interface indexes. The received packet is guaranteed to match the filter. The remapped function is WinDivertRecv: BOOL WinDivertRecv( __in HANDLE handle, __out PVOID pPacket, __in UINT packetLen, __out_opt PWINDIVERT_ADDRESS pAddr, __out_opt UINT *recvLen ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv """ packet = create_string_buffer(bufsize) address = WinDivertAddress() recv_len = c_int(0) self._lib.WinDivertRecv(self._handle, packet, bufsize, byref(address), byref(recv_len)) return packet[: recv_len.value], CapturedMetadata((address.IfIdx, address.SubIfIdx), address.Direction)
def setup_console(self): """Initializes the screen frame buffer. Swaps the current screen buffer with a brand new created back buffer where the characters can be written to the flicker-free rectangular region. """ self._console = get_std_handle(STD_OUTPUT_HANDLE) # could not get the standard # console handle, raise an exception if self._console == INVALID_HANDLE_VALUE: raise TermInitializationError() buffer_info = CONSOLE_SCREEN_BUFFER_INFO() get_console_screen_buffer_info(self._console, byref(buffer_info)) get_console_cursor_info(self._console, byref(self._cursor_info)) self._cursor_info.visible = False self._cols = buffer_info.size.x self._rows = buffer_info.size.y self._size = COORD(self._cols, self._rows) self._rect = SMALL_RECT(0, 0, self._cols - 1, self._rows - 1) self._char_buffer = (CHAR_INFO * (self._size.x * self._size.y))() self._framebuffer = create_console_screen_buffer(GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, None, CONSOLE_TEXTMODE_BUFFER, None) if self._framebuffer == INVALID_HANDLE_VALUE: raise TermInitializationError() # hide the cursor and swap # the console active screen buffer set_console_cursor_info(self._framebuffer, byref(self._cursor_info)) set_console_active_screen_buffer(self._framebuffer)
def init_console(self): self.console_handle = get_std_handle(STD_OUTPUT_HANDLE) if self.console_handle == INVALID_HANDLE_VALUE: raise TermInitializationError() get_console_screen_buffer_info(self.console_handle, byref(self.backbuffer_info)) get_console_cursor_info(self.console_handle, byref(self.cursor_info)) self._show_cursor(False) self.cols = self.backbuffer_info.size.x self.rows = self.backbuffer_info.size.y self.size = COORD(self.cols, self.rows) self.rect = SMALL_RECT(0, 0, self.cols - 1, self.rows - 1) self.char_buffer = (CHAR_INFO * (self.size.x * self.size.y))() self.backbuffer_handle = create_console_screen_buffer(GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, None, CONSOLE_TEXTMODE_BUFFER, None) if self.backbuffer_handle == INVALID_HANDLE_VALUE: raise TermInitializationError() set_console_active_screen_buffer(self.backbuffer_handle)
def parse_ipv6_address(self, address): """ Parses an IPv6 address. The function remapped is WinDivertHelperParseIPv6Address: BOOL WinDivertHelperParseIPv6Address( __in const char *addrStr, __out_opt UINT32 *pAddr ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_help_parse_ipv6_address """ ip_addr = ARRAY(c_uint8, 16)() self._lib.WinDivertHelperParseIPv6Address(address.encode(self.encoding), byref(ip_addr)) return ip_addr
def get_param(self, name): """ Gets a WinDivert parameter. See WinDivert DivertSetParam() for the list of parameters. The remapped function is DivertGetParam: BOOL WinDivertGetParam( __in HANDLE handle, __in WINDIVERT_PARAM param, __out UINT64 *pValue ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param """ value = c_uint64(0) self._lib.WinDivertGetParam(self._handle, name, byref(value)) return value.value
def write_console(cls, charseq, new_line=True): """Outputs to a Windows console using UNICODE charset. Parameters ---------- charseq: str the sequence of characters to be written new_line: bool indicates if the output should be written on the new line """ if new_line: charseq += '\n' else: charseq += '\r' write_console_unicode(cls._stdout_handle, charseq, len(charseq), byref(c_ulong()), None)
def calc_checksums(self, packet, flags=0): """ (Re)calculates the checksum for any IPv4/ICMP/ICMPv6/TCP/UDP checksum present in the given packet. Individual checksum calculations may be disabled via the appropriate flag. Typically this function should be invoked on a modified packet before it is injected with send(). The function remapped is WinDivertHelperCalcChecksums: UINT WinDivertHelperCalcChecksums( __inout PVOID pPacket, __in UINT packetLen, __in UINT64 flags ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_helper_calc_checksums """ packet_len = len(packet) buff = create_string_buffer(packet, packet_len) self._lib.WinDivertHelperCalcChecksums(byref(buff), packet_len, flags) return buff
def parse_packet(self, *args): """ Parses a raw packet into a higher level object. Args could be a tuple or two different values. In each case the first one is the raw data and the second is the meta about the direction and interface to use. The function remapped is WinDivertHelperParsePacket: Parses a raw packet (e.g. from WinDivertRecv()) into the various packet headers and/or payloads that may or may not be present. BOOL WinDivertHelperParsePacket( __in PVOID pPacket, __in UINT packetLen, __out_opt PWINDIVERT_IPHDR *ppIpHdr, __out_opt PWINDIVERT_IPV6HDR *ppIpv6Hdr, __out_opt PWINDIVERT_ICMPHDR *ppIcmpHdr, __out_opt PWINDIVERT_ICMPV6HDR *ppIcmpv6Hdr, __out_opt PWINDIVERT_TCPHDR *ppTcpHdr, __out_opt PWINDIVERT_UDPHDR *ppUdpHdr, __out_opt PVOID *ppData, __out_opt UINT *pDataLen ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_helper_parse_packet """ if len(args) == 1: # Maybe this is a poor way to check the type, but it should work if hasattr(args[0], "__iter__") and not hasattr(args[0], "strip"): raw_packet, meta = args[0] else: raw_packet, meta = args[0], None elif len(args) == 2: raw_packet, meta = args[0], args[1] else: raise ValueError("Wrong number of arguments passed to parse_packet") packet_len = len(raw_packet) # Consider everything else not part of headers as payload # payload = ctypes.c_void_p(0) payload_len = c_uint(0) ip_hdr, ipv6_hdr = pointer(IpHeader()), pointer(Ipv6Header()) icmp_hdr, icmpv6_hdr = pointer(IcmpHeader()), pointer(Icmpv6Header()) tcp_hdr, udp_hdr = pointer(TcpHeader()), pointer(UdpHeader()) headers = (ip_hdr, ipv6_hdr, icmp_hdr, icmpv6_hdr, tcp_hdr, udp_hdr) self._lib.WinDivertHelperParsePacket( raw_packet, packet_len, byref(ip_hdr), byref(ipv6_hdr), byref(icmp_hdr), byref(icmpv6_hdr), byref(tcp_hdr), byref(udp_hdr), None, byref(payload_len), ) # headers_len = sum(ctypes.sizeof(hdr.contents) for hdr in headers if hdr) # headers_len = sum((getattr(hdr.contents, "HdrLength", 0) * 4) for hdr in headers if hdr) # clean headers, consider just those that are not None (!=NULL) headers = [hdr.contents for hdr in headers if hdr] headers_opts = [] offset = 0 for header in headers: if hasattr(header, "HdrLength"): header_len = getattr(header, "HdrLength", 0) * 4 opt_len = header_len - sizeof(header) if opt_len: opt = raw_packet[offset + header_len - opt_len : offset + header_len] headers_opts.append(opt) else: headers_opts.append("") else: headers_opts.append("") header_len = sizeof(header) offset += header_len return CapturedPacket( payload=raw_packet[offset:], raw_packet=raw_packet, headers=[HeaderWrapper(hdr, opt, self.encoding) for hdr, opt in zip(headers, headers_opts)], meta=meta, encoding=self.encoding, )
def _enum_handles(self, process_id=None): """Enumerates handle information. Enumerates handle info on the start of the kernel capture. Returns a dictionary of handle's information including the handle id, access mask, and the process which owns the handle. """ buff_size = MAX_BUFFER_SIZE size = c_ulong() # allocate the initial buffer buff = malloc(buff_size) handles = {} while True: status = zw_query_system_information(SYSTEM_HANDLE_INFORMATION_CLASS, buff, buff_size, byref(size)) if status == STATUS_INFO_LENGTH_MISMATCH: # the buffer is too small # increment the buffer size and try again buff_size += MAX_BUFFER_SIZE elif status == STATUS_SUCCESS: # cast the buffer to `SYSTEM_HANDLE_INFORMATION` struct # which contains an array of `SYSTEM_HANDLE` structures sys_handle_info = cast(buff, POINTER(SYSTEM_HANDLE_INFORMATION)) sys_handle_info = sys_handle_info.contents handle_count = sys_handle_info.number_of_handles # resize the array size to the # actual number of file handles sys_handles = (SYSTEM_HANDLE * buff_size).from_address(addressof(sys_handle_info.handles)) for i in range(handle_count): sys_handle = sys_handles[i] pid = sys_handle.process_id handle = sys_handle.handle obj = sys_handle.object obj_type_index = sys_handle.object_type_number access_mask = sys_handle.access_mask if process_id and process_id == pid: handles[obj] = ddict(pid=process_id, handle=handle, obj=obj, access_mask=access_mask, obj_type_index=obj_type_index) elif process_id is None: handles[obj] = ddict(pid=pid, handle=handle, obj=obj, access_mask=access_mask, obj_type_index=obj_type_index) break else: raise HandleEnumError(status) # reallocate the buffer buff = realloc(buff, buff_size) # free the buffer memory free(buff) return handles
def write_output(self, charseq, color=LIGHT_WHITE): """Writes character and color attribute data to the frame buffer. The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer. Parameters ---------- charseq: str the sequence of characters to be written on the frame buffer color: int the terminal output color """ col = 0 x = 0 crlf = False if not charseq or len(charseq) <= 0: return try: for char in charseq: if char == '\n': crlf = True col += 1 # the last column has been reached. # If there was a carriage return # then stop the iteration if col == self._cols: col = 0 if crlf: crlf = False continue if crlf: crlf = False space = col # keep filling the rectangle with spaces # until we reach the last column while space <= self._cols: self._char_buffer[space - 1].char.unicode_char = ' ' space += 1 x += 1 # reset the column and # stop the current iteration col = 0 continue self._char_buffer[x].char.unicode_char = char self._char_buffer[x].attributes = color x += 1 except IndexError: pass # write the character attribute data # to the screen buffer write_console_output(self._framebuffer, self._char_buffer, self._size, self._coord, byref(self._rect))
def restore_console(self): if self._console: set_console_active_screen_buffer(self._console) self._cursor_info.visible = True set_console_cursor_info(self._console, byref(self._cursor_info))
def _show_cursor(self, visible=True): self.cursor_info.visible = visible set_console_cursor_info(self.console_handle, byref(self.cursor_info))