// wraps SCardSetAttrib func (card *Card) SetAttrib(id uint32, data []byte) error { r := C.SCardSetAttrib(card.handle, C.DWORD(id), (*C.BYTE)(&data[0]), C.DWORD(len(data))) if r != C.SCARD_S_SUCCESS { return newError(r) } return nil }
// wraps SCardStatus func (card *Card) Status() (*CardStatus, error) { var readerBuf [C.MAX_READERNAME + 1]byte var readerLen = C.DWORD(len(readerBuf)) var state, proto C.DWORD var atr [C.MAX_ATR_SIZE]byte var atrLen = C.DWORD(len(atr)) r := C.SCardStatus(card.handle, (C.LPSTR)(unsafe.Pointer(&readerBuf[0])), &readerLen, &state, &proto, (*C.BYTE)(&atr[0]), &atrLen) if r != C.SCARD_S_SUCCESS { return nil, scardError(r) } // strip terminating 0 reader := readerBuf[:readerLen] if z := bytes.IndexByte(reader, 0); z != -1 { reader = reader[:z] } status := &CardStatus{ Reader: string(reader), State: State(state), ActiveProtocol: Protocol(proto), ATR: atr[0:atrLen], } return status, nil }
// wraps SCardTransmit func (card *Card) Transmit(cmd []byte) ([]byte, error) { var sendpci *C.SCARD_IO_REQUEST var recvpci C.SCARD_IO_REQUEST switch card.activeProtocol { case PROTOCOL_T0: sendpci = &C.g_rgSCardT0Pci case PROTOCOL_T1: sendpci = &C.g_rgSCardT1Pci case PROTOCOL_RAW: sendpci = &C.g_rgSCardRawPci default: panic("unknown protocol") } var recv [C.MAX_BUFFER_SIZE_EXTENDED]byte var recvlen C.DWORD = C.DWORD(len(recv)) r := C.SCardTransmit(card.handle, sendpci, (*C.BYTE)(&cmd[0]), C.DWORD(len(cmd)), &recvpci, (*C.BYTE)(&recv[0]), &recvlen) if r != C.SCARD_S_SUCCESS { return nil, newError(r) } rsp := make([]byte, recvlen) copy(rsp, recv[0:recvlen]) return rsp, nil }
func (wi *windowInternal) switchToFullscreen(monitor *Monitor, mode VideoMode) error { devMode := C.DEVMODEW{ dmSize: C.DEVMODEW_size, dmPelsWidth: C.DWORD(mode.Width), dmPelsHeight: C.DWORD(mode.Height), dmBitsPerPel: C.DWORD(mode.BitsPerPixel), dmFields: C.DM_PELSWIDTH | C.DM_PELSHEIGHT | C.DM_BITSPERPEL, } // Apply fullscreen mode if err := ChangeDisplaySettingsExW(&monitor.internal.info.szDevice[0], &devMode, nil, C.CDS_FULLSCREEN, nil); err != nil { return err } // Make the window flags compatible with fullscreen mode C.SetWindowULong(wi.window.Handle, C.GWL_STYLE, C.WS_POPUP|C.WS_CLIPCHILDREN|C.WS_CLIPSIBLINGS) C.SetWindowLong(wi.window.Handle, C.GWL_EXSTYLE, C.WS_EX_APPWINDOW) // Resize the window so that it fits the entire screen C.SetWindowPos(wi.window.Handle, HWND_TOP, 0, 0, C.int(mode.Width), C.int(mode.Height), C.SWP_FRAMECHANGED) C.ShowWindow(wi.window.Handle, C.SW_SHOW) // Set this as the current fullscreen window wi.monitor = monitor wi.devMode = &devMode return nil }
// wraps SCardTransmit func (card *Card) Transmit(cmd []byte) ([]byte, error) { var sendpci C.SCARD_IO_REQUEST var recvpci C.SCARD_IO_REQUEST switch card.activeProtocol { case PROTOCOL_T0: sendpci.dwProtocol = C.SCARD_PROTOCOL_T0 case PROTOCOL_T1: sendpci.dwProtocol = C.SCARD_PROTOCOL_T1 default: panic("unknown protocol") } sendpci.cbPciLength = C.sizeof_SCARD_IO_REQUEST var recv [C.MAX_BUFFER_SIZE_EXTENDED]byte var recvlen C.DWORD = C.DWORD(len(recv)) r := C.SCardTransmit(card.handle, &sendpci, (*C.BYTE)(&cmd[0]), C.DWORD(len(cmd)), &recvpci, (*C.BYTE)(&recv[0]), &recvlen) if r != C.SCARD_S_SUCCESS { return nil, scardError(r) } rsp := make([]byte, recvlen) copy(rsp, recv[0:recvlen]) return rsp, nil }
func getNativeName(DeviceInfoSet C.HDEVINFO, DeviceInfoData C.PSP_DEVINFO_DATA) (string, error) { key := C.SetupDiOpenDevRegKey(DeviceInfoSet, DeviceInfoData, C.DICS_FLAG_GLOBAL, 0, C.DIREG_DEV, C.KEY_READ) defer C.RegCloseKey(key) if C.is_INVALID_HANDLE_VALUE(unsafe.Pointer(key)) != C.FALSE { return "", errors.New(fmt.Sprintf("Reg error: %d", int(C.GetLastError()))) } var i C.DWORD = 0 var keyType C.DWORD = 0 buffKeyName := make([]C.CHAR, 16384) buffKeyVal := make([]C.BYTE, 16384) for { var lenKeyName C.DWORD = C.DWORD(cap(buffKeyName)) var lenKeyValue C.DWORD = C.DWORD(cap(buffKeyVal)) ret := C.RegEnumValue(key, i, &buffKeyName[0], &lenKeyName, (*C.DWORD)(nil), &keyType, &buffKeyVal[0], &lenKeyValue) i++ if ret == C.ERROR_SUCCESS { if keyType == C.REG_SZ { itemName := C.GoString((*C.char)(&buffKeyName[0])) itemValue := C.GoString((*C.char)(unsafe.Pointer((&buffKeyVal[0])))) if strings.Contains(itemName, "PortName") { return itemValue, nil } } } else { break } } return "", errors.New("Empty response") }
// WriteToSoundBuffer locks the sound buffer and writes the given data into it, // starting at the given byte offset. The buffer is a ring buffer so writing // outside the bounds will wrap around and continue writing to the beginning. func WriteToSoundBuffer(data []byte, offset uint) error { buffer := C.CString(string(data)) defer C.free(unsafe.Pointer(buffer)) var errContext C.int result := C.copyToSoundBuffer(C.DWORD(offset), buffer, C.DWORD(len(data)), &errContext) return makeError("writeToSoundBuffer", result, errContext) }
func (device Device) GetPredefinedGuidAndPathProperty( prop, obj, how int, ) ( guid GUID, path string, err error, ) { var cProp C.DIPROPGUIDANDPATH cProp.diph.dwSize = C.sizeof_DIPROPGUIDANDPATH cProp.diph.dwHeaderSize = C.sizeof_DIPROPHEADER cProp.diph.dwObj = C.DWORD(obj) cProp.diph.dwHow = C.DWORD(how) err = toGetPropError(C.IDirectInputDevice8GetPredefinedProperty( device.handle, unsafe.Pointer(uintptr(prop)), &cProp.diph, )) guid.fromC(&cProp.guidClass) var buf [maxPath]uint16 length := 0 for ; length < maxPath; length++ { buf[length] = uint16(cProp.wszPath[length]) if cProp.wszPath[length] == 0 { break } } path = syscall.UTF16ToString(buf[:length]) return }
func virtualKeyCodeToSF(vkey C.WPARAM, flags C.LPARAM) Key { if key, ok := keyboard_vkeys_map[C.int(vkey)]; ok { return key } switch vkey { // Check the scancode to distinguish between left and right shift case C.VK_SHIFT: scancode := C.UINT((flags & (0xFF << 16)) >> 16) if scancode == lShift { return KeyLShift } return KeyRShift // Check the "extended" flag to distinguish between left and right alt case C.VK_MENU: if C.__HIWORD(C.DWORD(flags))&C.KF_EXTENDED != 0 { return KeyRAlt } return KeyLAlt // Check the "extended" flag to distinguish between left and right control case C.VK_CONTROL: if C.__HIWORD(C.DWORD(flags))&C.KF_EXTENDED != 0 { return KeyRControl } return KeyLControl } return KeyUnknown }
func (device Device) GetPredefinedStringProperty( prop, obj, how int, ) ( value string, err error, ) { var cProp C.DIPROPSTRING cProp.diph.dwSize = C.sizeof_DIPROPSTRING cProp.diph.dwHeaderSize = C.sizeof_DIPROPHEADER cProp.diph.dwObj = C.DWORD(obj) cProp.diph.dwHow = C.DWORD(how) err = toGetPropError(C.IDirectInputDevice8GetPredefinedProperty( device.handle, unsafe.Pointer(uintptr(prop)), &cProp.diph, )) var buf [maxPath]uint16 length := 0 for ; length < maxPath; length++ { buf[length] = uint16(cProp.wsz[length]) if cProp.wsz[length] == 0 { break } } value = syscall.UTF16ToString(buf[:length]) return }
func NewPlayer(sampleRate, channelNum, bytesPerSample int) (*Player, error) { numBlockAlign := channelNum * bytesPerSample f := C.WAVEFORMATEX{ wFormatTag: C.WAVE_FORMAT_PCM, nChannels: C.WORD(channelNum), nSamplesPerSec: C.DWORD(sampleRate), nAvgBytesPerSec: C.DWORD(sampleRate * numBlockAlign), wBitsPerSample: C.WORD(bytesPerSample * 8), nBlockAlign: C.WORD(numBlockAlign), } var w C.HWAVEOUT if err := C.waveOutOpen(&w, C.WAVE_MAPPER, &f, 0, 0, C.CALLBACK_NULL); err != C.MMSYSERR_NOERROR { return nil, fmt.Errorf("driver: waveOutOpen error: %d", err) } p := &Player{ out: w, buffer: []byte{}, headers: make([]*header, numHeader), } for i := 0; i < numHeader; i++ { var err error p.headers[i], err = newHeader(w, bufferSize) if err != nil { return nil, err } } return p, nil }
func NewPropDword(obj, how int, data uint32) propHeader { var p C.DIPROPDWORD p.diph.dwSize = C.sizeof_DIPROPDWORD p.diph.dwHeaderSize = C.sizeof_DIPROPHEADER p.diph.dwObj = C.DWORD(obj) p.diph.dwHow = C.DWORD(how) p.dwData = C.DWORD(data) return &propDword{p} }
func NewPropPointer(obj, how int, data uintptr) propHeader { var p C.DIPROPPOINTER p.diph.dwSize = C.sizeof_DIPROPPOINTER p.diph.dwHeaderSize = C.sizeof_DIPROPHEADER p.diph.dwObj = C.DWORD(obj) p.diph.dwHow = C.DWORD(how) p.uData = C.UINT_PTR(data) return &propPointer{p} }
func NewPropRange(obj, how, min, max int) propHeader { var p C.DIPROPRANGE p.diph.dwSize = C.sizeof_DIPROPRANGE p.diph.dwHeaderSize = C.sizeof_DIPROPHEADER p.diph.dwObj = C.DWORD(obj) p.diph.dwHow = C.DWORD(how) p.lMin = C.LONG(min) p.lMax = C.LONG(max) return &propRange{p} }
// AcquireCtx acquires new CSP context from container name, provider name, // type and flags. Empty strings for container and provider // names are typically used for CryptVerifyContext flag setting. Created context // must be eventually released with its Close method. func AcquireCtx(container, provider string, provType ProvType, flags CryptFlag) (*Ctx, error) { var hprov C.HCRYPTPROV cContainer := charPtr(container) cProvider := charPtr(provider) defer freePtr(cContainer) defer freePtr(cProvider) if C.CryptAcquireContext(&hprov, cContainer, cProvider, C.DWORD(provType), C.DWORD(flags)) == 0 { return nil, getErr("Error acquiring context") } return &Ctx{hProv: hprov}, nil }
// GetProperty is a base function for extracting certificate context properties func (c *Cert) GetProperty(propId CertPropertyId) ([]byte, error) { var slen C.DWORD var res []byte if C.CertGetCertificateContextProperty(c.pCert, C.DWORD(propId), nil, &slen) == 0 { return res, getErr("Error getting cert context property size") } res = make([]byte, slen) if C.CertGetCertificateContextProperty(c.pCert, C.DWORD(propId), unsafe.Pointer(&res[0]), &slen) == 0 { return res, getErr("Error getting cert context property body") } return res, nil }
// Returns whether or not a monitor supports a particular video mode func (mi *monitorInternal) supportsMode(mode VideoMode) bool { devMode := C.DEVMODEW{ dmSize: C.DEVMODEW_size, dmPelsWidth: C.DWORD(mode.Width), dmPelsHeight: C.DWORD(mode.Height), dmBitsPerPel: C.DWORD(mode.BitsPerPixel), dmFields: C.DM_PELSWIDTH | C.DM_PELSHEIGHT | C.DM_BITSPERPEL, } err := ChangeDisplaySettingsExW(&mi.info.szDevice[0], &devMode, nil, C.CDS_TEST, nil) return err == nil }
// wraps SCardReconnect func (card *Card) Reconnect(mode ShareMode, protocol Protocol, init Disposition) error { var activeProtocol C.DWORD r := C.SCardReconnect(card.handle, C.DWORD(mode), C.DWORD(protocol), C.DWORD(init), &activeProtocol) if r != C.SCARD_S_SUCCESS { return newError(r) } card.activeProtocol = Protocol(activeProtocol) return nil }
// AcquireCtx acquires new CSP context from container name, provider name, // type and flags. Empty strings for container and provider // names are typically used for CryptVerifyContext flag setting. Created context // must be eventually released with its Close method. func AcquireCtx(container, provider string, provType ProvType, flags CryptFlag) (res Ctx, err error) { cContainer := charPtr(container) defer freePtr(cContainer) cProvider := charPtr(provider) defer freePtr(cProvider) if C.CryptAcquireContext(&res.hProv, cContainer, cProvider, C.DWORD(provType), C.DWORD(flags)) == 0 { err = getErr("Error acquiring context") return } return }
func (t *Thread) resume() error { t.running = true var res C.WINBOOL t.dbp.execPtraceFunc(func() { //TODO: Note that we are ignoring the thread we were asked to continue and are continuing the //thread that we last broke on. res = C.ContinueDebugEvent(C.DWORD(t.dbp.Pid), C.DWORD(t.ID), C.DBG_CONTINUE) }) if res == C.FALSE { return fmt.Errorf("could not ContinueDebugEvent.") } return nil }
// wraps SCardConnect func (ctx *Context) Connect(reader string, mode ShareMode, proto Protocol) (*Card, error) { var card Card var activeProtocol C.DWORD creader := C.CString(reader) defer C.free(unsafe.Pointer(creader)) r := C.SCardConnect(ctx.ctx, creader, C.DWORD(mode), C.DWORD(proto), &card.handle, &activeProtocol) if r != C.SCARD_S_SUCCESS { return nil, newError(r) } card.activeProtocol = Protocol(activeProtocol) return &card, nil }
func getDeviceDetails(deviceInfoSet C.HDEVINFO, deviceInterfaceData *C.SP_DEVICE_INTERFACE_DATA) *DeviceInfo { devicePath := getCString(func(buffer unsafe.Pointer, size *C.DWORD) unsafe.Pointer { interfaceDetailData := (*C.SP_DEVICE_INTERFACE_DETAIL_DATA_A)(buffer) if interfaceDetailData != nil { interfaceDetailData.cbSize = C.DWORD(unsafe.Sizeof(interfaceDetailData)) } C.SetupDiGetDeviceInterfaceDetailA(deviceInfoSet, deviceInterfaceData, interfaceDetailData, *size, size, nil) if interfaceDetailData != nil { return (unsafe.Pointer)(&interfaceDetailData.DevicePath[0]) } else { return nil } }) if devicePath == "" { return nil } // Make sure this device is of Setup Class "HIDClass" and has a driver bound to it. var i C.DWORD var devinfoData C.SP_DEVINFO_DATA devinfoData.cbSize = C.DWORD(unsafe.Sizeof(devinfoData)) isHID := false for i = 0; ; i++ { if res := C.SetupDiEnumDeviceInfo(deviceInfoSet, i, &devinfoData); res == 0 { break } classStr := getCString(func(buffer unsafe.Pointer, size *C.DWORD) unsafe.Pointer { C.SetupDiGetDeviceRegistryPropertyA(deviceInfoSet, &devinfoData, C.SPDRP_CLASS, nil, (*C.BYTE)(buffer), *size, size) return buffer }) if classStr == "HIDClass" { driverName := getCString(func(buffer unsafe.Pointer, size *C.DWORD) unsafe.Pointer { C.SetupDiGetDeviceRegistryPropertyA(deviceInfoSet, &devinfoData, C.SPDRP_DRIVER, nil, (*C.BYTE)(buffer), *size, size) return buffer }) isHID = driverName != "" break } } if !isHID { return nil } d, _ := ByPath(devicePath) return d }
// EnumProviders returns slice of CryptoProvider structures, describing // available CSPs. func EnumProviders() ([]CryptoProvider, error) { var ( slen C.DWORD ) res := make([]CryptoProvider, 0) index := C.DWORD(0) for { var provType C.DWORD if C.CryptEnumProviders(index, nil, 0, &provType, nil, &slen) == 0 { break } buf := make([]byte, slen) // XXX: Some evil magic here if C.CryptEnumProviders(index, nil, 0, &provType, (*C.CHAR)(unsafe.Pointer(&buf[0])), &slen) == 0 { return res, getErr("Error during provider enumeration") } else { res = append(res, CryptoProvider{Name: string(buf), Type: ProvType(provType)}) } index++ } return res, nil }
// wraps SCardEndTransaction func (card *Card) EndTransaction(d Disposition) error { r := C.SCardEndTransaction(card.handle, C.DWORD(d)) if r != C.SCARD_S_SUCCESS { return newError(r) } return nil }
func SendInput(inputs []INPUT) uint32 { var validInputs []C.INPUT for _, oneInput := range inputs { input := C.INPUT{_type: C.DWORD(oneInput.Type)} switch oneInput.Type { case INPUT_MOUSE: (*MouseInput)(unsafe.Pointer(&input)).mi = oneInput.Mi case INPUT_KEYBOARD: (*KbdInput)(unsafe.Pointer(&input)).ki = oneInput.Ki case INPUT_HARDWARE: (*HardwareInput)(unsafe.Pointer(&input)).hi = oneInput.Hi default: panic("unkown type") } validInputs = append(validInputs, input) } ret, _, _ := procSendInput.Call( uintptr(len(validInputs)), uintptr(unsafe.Pointer(&validInputs[0])), uintptr(unsafe.Sizeof(C.INPUT{})), ) return uint32(ret) }
func (m Msg) update(buf []byte, n int, lastCall bool) bool { var lc C.BOOL if lastCall { lc = C.BOOL(1) } return C.CryptMsgUpdate(m.hMsg, (*C.BYTE)(unsafe.Pointer(&buf[0])), C.DWORD(n), lc) != 0 }
// wraps SCardDisconnect func (card *Card) Disconnect(d Disposition) error { r := C.SCardDisconnect(card.handle, C.DWORD(d)) if r != C.SCARD_S_SUCCESS { return newError(r) } return nil }
func (e *Element) SetHtml(html string) { szHtml := C.CString(html) defer C.free(unsafe.Pointer(szHtml)) if ret := C.HTMLayoutSetElementHtml(e.handle, (*C.BYTE)(unsafe.Pointer(szHtml)), C.DWORD(len(html)), SIH_REPLACE_CONTENT); ret != HLDOM_OK { domPanic(ret, "Failed to replace element's html") } }
func (e *Element) PrependHtml(prefix string) { szHtml := C.CString(prefix) defer C.free(unsafe.Pointer(szHtml)) if ret := C.HTMLayoutSetElementHtml(e.handle, (*C.BYTE)(unsafe.Pointer(szHtml)), C.DWORD(len(prefix)), SIH_INSERT_AT_START); ret != HLDOM_OK { domPanic(ret, "Failed to prepend to element's html") } }
func (e *Element) AppendHtml(suffix string) { szHtml := C.CString(suffix) defer C.free(unsafe.Pointer(szHtml)) if ret := C.HTMLayoutSetElementHtml(e.handle, (*C.BYTE)(unsafe.Pointer(szHtml)), C.DWORD(len(suffix)), SIH_APPEND_AFTER_LAST); ret != HLDOM_OK { domPanic(ret, "Failed to append to element's html") } }