Пример #1
0
// Register a DNS Service of name, service type stype, with txt record specified, on
// a certain port. This gets added to a list of registered services which can be
// deregistered by calling ServiceDeregister(). I'm fairly sure that closing the program
// causes the socket connection to mDNSResponder to be closed, which will also deregister
// the services.
func ServiceRegister(name, stype string, txt map[string]string, port uint16) error {
	txtblob, err := mapToBytes(txt)
	if err != nil {
		return err
	}

	// Network order is big-endian
	bport := (port&0xff)<<8 + port>>8

	var ref C.DNSServiceRef
	dnserr := C.DNSServiceRegister(
		&ref,                        // DNSServiceRegister
		0,                           // DNSServiceFlags
		0,                           // Interface (0 => all interfaces)
		C.CString(name),             // Service name (const char *)
		C.CString(stype),            // Service type (const char *)
		nil,                         // Domain (const char *) empty => default domain
		nil,                         // Host (const char *), empty => machine default host
		C.uint16_t(bport),           // Port, in network byte order
		C.uint16_t(len(txtblob)),    // TXT Record length
		unsafe.Pointer(&txtblob[0]), // TXT Record
		nil, // Callback on register/fail (TODO: do something here)
		nil) // Application Context
	if dnserr != C.kDNSServiceErr_NoError {
		return errors.New("Could not register service")
	}

	services = append(services, ref)
	return nil
}
Пример #2
0
func (diff *Diff) FindSimilar(opts *DiffFindOptions) error {

	var copts *C.git_diff_find_options
	if opts != nil {
		copts = &C.git_diff_find_options{
			version:                       C.GIT_DIFF_FIND_OPTIONS_VERSION,
			flags:                         C.uint32_t(opts.Flags),
			rename_threshold:              C.uint16_t(opts.RenameThreshold),
			copy_threshold:                C.uint16_t(opts.CopyThreshold),
			rename_from_rewrite_threshold: C.uint16_t(opts.RenameFromRewriteThreshold),
			break_rewrite_threshold:       C.uint16_t(opts.BreakRewriteThreshold),
			rename_limit:                  C.size_t(opts.RenameLimit),
		}
	}

	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	ecode := C.git_diff_find_similar(diff.ptr, copts)
	if ecode < 0 {
		return MakeGitError(ecode)
	}

	return nil
}
Пример #3
0
func AllocTransientBuffers(verts interface{}, idxs *[]uint16, decl VertexDecl, numVerts, numIndices int) (tvb TransientVertexBuffer, tib TransientIndexBuffer, ok bool) {
	val := reflect.ValueOf(verts)
	if val.Kind() != reflect.Ptr || val.Elem().Kind() != reflect.Slice {
		panic(errors.New("bgfx: expected pointer to slice"))
	}
	ok = bool(C.bgfx_alloc_transient_buffers(
		&tvb.tvb,
		&decl.decl,
		C.uint16_t(numVerts),
		&tib.tib,
		C.uint16_t(numIndices),
	))
	if !ok {
		return
	}
	slice := (*reflect.SliceHeader)(unsafe.Pointer(val.Pointer()))
	slice.Data = uintptr(unsafe.Pointer(tvb.tvb.data))
	slice.Len = numVerts
	slice.Cap = numVerts
	slice = (*reflect.SliceHeader)(unsafe.Pointer(idxs))
	slice.Data = uintptr(unsafe.Pointer(tib.tib.data))
	slice.Len = numIndices
	slice.Cap = numIndices
	return
}
Пример #4
0
func (dev *linuxDevice) writeReport(hid_report_type int, data []byte) error {
	if dev.handle == nil {
		return errors.New("No USB device opend before.")
	}
	if len(data) > 0xffff {
		return errors.New("data longer than 65535 bytes, means overflow, isn't supported")
	}
	if len(data) == 0 {
		return nil
	}

	const reportId = 1
	const index = 0
	const timeout = 1000

	written := C.libusb_control_transfer(dev.handle,
		C.uint8_t(ENDPOINT_OUT|RECIPIENT_DEVICE|DT_REPORT|hid_report_type),
		C.uint8_t(HID_SET_REPORT),
		C.uint16_t(reportId),
		C.uint16_t(index),
		(*C.uchar)(&data[0]),
		C.uint16_t(len(data)),
		C.uint(timeout))

	if int(written) == len(data) {
		return nil
	}
	return usbError(written)
}
Пример #5
0
// Send a new port mapping NAT-PMP request to the network gateway
//
// Arguments :
// protocol is either golibnatpmp.TCP or golibnatpmp.UDP,
// lifetime is in seconds.
//
// To remove a port mapping, set lifetime to zero.
//
// To remove all port mappings to the host, set lifetime and both ports
// to zero.
func (self NATPMP) SendNewPortMappingRequest(protocol protocol,
	privateport, publicport uint16,
	lifetimeInSeconds uint32) <-chan NewPortMappingResponse {
	c := make(chan NewPortMappingResponse, 1)
	ret, err := C.sendnewportmappingrequest(self.ctype, C.int(protocol),
		C.uint16_t(privateport), C.uint16_t(publicport),
		C.uint32_t(lifetimeInSeconds))
	if err == nil && ret != 12 {
		err = strNATPMPerr(ret)
	}
	if err != nil {
		c <- NewPortMappingResponse{
			Err: err,
		}
	} else {
		go func() {
			resp, err := self.waitForAndReadNATPMPResponse()
			c <- NewPortMappingResponse{
				PrivatePort:       uint16(resp.privateport),
				MappedPublicPort:  uint16(resp.mappedpublicport),
				LifetimeInSeconds: uint32(resp.lifetime),
				Err:               err,
			}
		}()
	}
	return c
}
Пример #6
0
func CreateFrameBuffer(width, height int, format TextureFormat, flags TextureFlags) FrameBuffer {
	h := C.bgfx_create_frame_buffer(
		C.uint16_t(width),
		C.uint16_t(height),
		C.bgfx_texture_format_t(format),
		C.uint32_t(flags),
	)
	return FrameBuffer{h: h}
}
Пример #7
0
func SetViewRect(view ViewID, x, y, w, h int) {
	C.bgfx_set_view_rect(
		C.uint8_t(view),
		C.uint16_t(x),
		C.uint16_t(y),
		C.uint16_t(w),
		C.uint16_t(h),
	)
}
Пример #8
0
// Open a device by vendor/product id. If more than one device
// matches, return the first.
func (ctx *Context) Open(vendor, product int) (*DeviceHandle, *UsbError) {
	handle := &DeviceHandle{ctx, nil, 0, make(map[byte]*Interface, 0)}
	dev := C.libusb_open_device_with_vid_pid(ctx.ctx, C.uint16_t(vendor), C.uint16_t(product))

	if dev == nil {
		return nil, UsbErrorMisc
	}
	handle.handle = dev
	return handle, nil
}
Пример #9
0
// With an unsafe.Pointer to the block of C memory NewUdpHdr returns a filled in UdpHdr struct.
func NewUdpHdr(p unsafe.Pointer) (*UdpHdr, unsafe.Pointer) {
	udpHead := &UdpHdr{
		cptr: (*C.struct_udphdr)(p),
	}
	udpHead.Source = uint16(C.ntohs(C.uint16_t(udpHead.cptr.source)))
	udpHead.Dest = uint16(C.ntohs(C.uint16_t(udpHead.cptr.dest)))
	udpHead.Len = uint16(C.ntohs(C.uint16_t(udpHead.cptr.len)))
	udpHead.Check = uint16(C.ntohs(C.uint16_t(udpHead.cptr.check)))
	udpHead.payload = unsafe.Pointer(uintptr(p) + 8)
	return udpHead, udpHead.payload
}
Пример #10
0
func (a *DnetAddr) CAddr(tmp *C.struct_dnet_addr) {
	length := len(a.Addr)
	if length > int(C.DNET_ADDR_SIZE) {
		length = int(C.DNET_ADDR_SIZE)
	}
	if length > 0 {
		C.memcpy(unsafe.Pointer(&tmp.addr[0]), unsafe.Pointer(&a.Addr[0]), C.size_t(length))
	}
	tmp.addr_len = C.uint16_t(length)
	tmp.family = C.uint16_t(a.Family)
}
Пример #11
0
func CalcTextureSize(width, height, depth, numMips int, format TextureFormat) TextureInfo {
	var ti C.bgfx_texture_info_t
	C.bgfx_calc_texture_size(
		&ti,
		C.uint16_t(width),
		C.uint16_t(height),
		C.uint16_t(depth),
		C.uint8_t(numMips),
		C.bgfx_texture_format_t(format),
	)
	return newTextureInfo(ti)
}
Пример #12
0
func (v *Repository) DiffTreeToTree(oldTree, newTree *Tree, opts *DiffOptions) (*Diff, error) {
	var diffPtr *C.git_diff
	var oldPtr, newPtr *C.git_tree

	if oldTree != nil {
		oldPtr = oldTree.cast_ptr
	}

	if newTree != nil {
		newPtr = newTree.cast_ptr
	}

	cpathspec := C.git_strarray{}
	var copts *C.git_diff_options
	var notifyData *diffNotifyData
	if opts != nil {
		notifyData = &diffNotifyData{
			Callback: opts.NotifyCallback,
		}
		if opts.Pathspec != nil {
			cpathspec.count = C.size_t(len(opts.Pathspec))
			cpathspec.strings = makeCStringsFromStrings(opts.Pathspec)
			defer freeStrarray(&cpathspec)
		}

		copts = &C.git_diff_options{
			version:           C.GIT_DIFF_OPTIONS_VERSION,
			flags:             C.uint32_t(opts.Flags),
			ignore_submodules: C.git_submodule_ignore_t(opts.IgnoreSubmodules),
			pathspec:          cpathspec,
			context_lines:     C.uint16_t(opts.ContextLines),
			interhunk_lines:   C.uint16_t(opts.InterhunkLines),
			id_abbrev:         C.uint16_t(opts.IdAbbrev),
			max_size:          C.git_off_t(opts.MaxSize),
		}

		if opts.NotifyCallback != nil {
			C._go_git_setup_diff_notify_callbacks(copts)
			copts.notify_payload = unsafe.Pointer(notifyData)
		}
	}

	ecode := C.git_diff_tree_to_tree(&diffPtr, v.ptr, oldPtr, newPtr, copts)
	if ecode < 0 {
		return nil, MakeGitError(ecode)
	}

	if notifyData != nil && notifyData.Diff != nil {
		return notifyData.Diff, nil
	}
	return newDiffFromC(diffPtr), nil
}
Пример #13
0
// Create a C struct to hold the Tox client startup options. This struct
// contains C heap items that must be freed to prevent memory leaks.
func (options *ToxOptions) cOptions() (c_options *C.struct_Tox_Options) {
	// Initialize the return object.
	c_options = &C.struct_Tox_Options{}
	// Copy the fields.
	c_options.ipv6_enabled = C.bool(options.IPv6Enabled)
	c_options.udp_enabled = C.bool(options.UDPEnabled)
	c_options.proxy_type = C.TOX_PROXY_TYPE(options.ProxyType)
	c_options.proxy_host = C.CString(options.ProxyHost)
	c_options.proxy_port = C.uint16_t(options.ProxyPort)
	c_options.start_port = C.uint16_t(options.StartPort)
	c_options.end_port = C.uint16_t(options.EndPort)
	return
}
Пример #14
0
Файл: usb.go Проект: hanwen/usb
func (h *DeviceHandle) ControlTransfer(reqType, req byte, value, index uint16,
	data []byte, timeout int) error {
	var ptr *byte
	if len(data) > 0 {
		ptr = &data[0]
	}
	if len(data) > 0xffff {
		return fmt.Errorf("overflow")
	}
	err := C.libusb_control_transfer(h.me(),
		C.uint8_t(reqType), C.uint8_t(req), C.uint16_t(value), C.uint16_t(index),
		(*C.uchar)(ptr), C.uint16_t(len(data)), C.uint(timeout))
	return toErr(err)
}
Пример #15
0
func CreateTexture2D(width, height, numMips int, format TextureFormat, flags TextureFlags, data []byte) Texture {
	var mem *C.bgfx_memory_t
	if data != nil {
		mem = C.bgfx_copy(unsafe.Pointer(&data[0]), C.uint32_t(len(data)))
	}
	h := C.bgfx_create_texture_2d(
		C.uint16_t(width),
		C.uint16_t(height),
		C.uint8_t(numMips),
		C.bgfx_texture_format_t(format),
		C.uint32_t(flags),
		mem,
	)
	return Texture{h: h}
}
Пример #16
0
func (v *Repository) BlameFile(path string, opts *BlameOptions) (*Blame, error) {
	var blamePtr *C.git_blame

	var copts *C.git_blame_options
	if opts != nil {
		copts = &C.git_blame_options{
			version:              C.GIT_BLAME_OPTIONS_VERSION,
			flags:                C.uint32_t(opts.Flags),
			min_match_characters: C.uint16_t(opts.MinMatchCharacters),
			min_line:             C.uint32_t(opts.MinLine),
			max_line:             C.uint32_t(opts.MaxLine),
		}
		if opts.NewestCommit != nil {
			copts.newest_commit = *opts.NewestCommit.toC()
		}
		if opts.OldestCommit != nil {
			copts.oldest_commit = *opts.OldestCommit.toC()
		}
	}

	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))

	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	ecode := C.git_blame_file(&blamePtr, v.ptr, cpath, copts)
	if ecode < 0 {
		return nil, MakeGitError(ecode)
	}

	return newBlameFromC(blamePtr), nil
}
Пример #17
0
func (buffer *RingBuffer) Claim(count uint16) (*Batch, error) {
	batch, err := C.rb_claim(buffer.buffer_ptr, C.uint16_t(count))
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Unable to claim [%d]: %s", count, err))
	}
	return (*Batch)(unsafe.Pointer(batch)), nil
}
Пример #18
0
// nurs_input_in6_addr(const struct nurs_input *input, uint16_t idx);
func nursInputIn6Addr(input *Input, idx uint16) (net.IP, error) {
	ret, err := C.nurs_input_in6_addr((*C.struct_nurs_input)(input), C.uint16_t(idx))
	if err != nil {
		return nil, err
	}
	return net.ParseIP(InetNtop(C.AF_INET6, unsafe.Pointer(ret))), err
}
Пример #19
0
//export goUdpGwClient_NewConnection
// goUdpGwClient_NewConnection creates a connection and returns a connection ID
// given local and remote addresses.
func goUdpGwClient_NewConnection(cLocalAddr C.BAddr, cRemoteAddr C.BAddr) C.uint16_t {

	// Open a connection for localAddr and remoteAddr
	laddr := C.baddr_to_str(&cLocalAddr)
	raddr := C.baddr_to_str(&cRemoteAddr)

	defer func() {
		C.free(unsafe.Pointer(laddr))
		C.free(unsafe.Pointer(raddr))
	}()

	localAddr := C.GoString(laddr)
	remoteAddr := C.GoString(raddr)

	connID, err := udpgwLookupOrCreateConnId(localAddr, remoteAddr)
	if err != nil {
		return 0
	}

	client, _ := getUdpGwClientById(connID)

	client.cLocalAddr = cLocalAddr
	client.cRemoteAddr = cRemoteAddr

	return C.uint16_t(connID)
}
Пример #20
0
func process_sample(qname string, qtype int, addr net.IP, secure bool) {
	var qtype_str [16]byte
	C.knot_rrtype_to_string(C.uint16_t(qtype), (*C.char)(unsafe.Pointer(&qtype_str[0])), C.size_t(16))
	// Sample NS country code
	var cc string
	switch len(addr) {
	case 4:
		if geo_db != nil {
			cc, _ = geo_db.GetCountry(addr.String())
		}
	case 16:
		if geo_db6 != nil {
			cc, _ = geo_db6.GetCountry_v6(addr.String())
		}
	default:
		return
	}
	// Count occurences
	if freq, exists := geo_freq[cc]; exists {
		geo_freq[cc] = freq + 1
	} else {
		geo_freq[cc] = 1
	}
	fifo_metrics[fifo_metrics_i] = QueryInfo{qname, string(qtype_str[:]), addr.String(), secure, cc}
	fifo_metrics_i = (fifo_metrics_i + 1) % len(fifo_metrics)
}
Пример #21
0
Файл: uwsgi.go Проект: ahua/c
// get an item from the cache
func CacheGet(key string, cache string) []byte {

	k := C.CString(key)
	defer C.free(unsafe.Pointer(k))
	kl := len(key)
	var vl C.uint64_t = C.uint64_t(0)

	c := (*C.char)(nil)
	if len(cache) > 0 {
		c = C.CString(cache)
		defer C.free(unsafe.Pointer(c))
	}

	var p []byte

	c_value := C.uwsgi_cache_magic_get(k, C.uint16_t(kl), &vl, c)

	if c_value != nil {
		p = C.GoBytes((unsafe.Pointer)(c_value), C.int(vl))
	} else {
		p = nil
	}

	return p
}
Пример #22
0
// This function sends a "get nodes" request to the given seed node with IP,
// port, and public key to setup connections. It will attempt to connect to the
// node using UDP and TCP at the same time. Tox will use the node as a TCP
// relay in case ToxOptions.UDPEnabled was false, and also to connect to
// friends that are in TCP-only mode. Tox will also use the TCP connection when
// NAT hole punching is slow, and later switch to UDP if hole punching succeeds.
func (tox *Tox) Bootstrap(seedNode *SeedNode) (throw error) {
	// Create and initialize variables.
	c_host := C.CString(seedNode.Host)
	defer C.free(unsafe.Pointer(c_host))
	c_port := C.uint16_t(seedNode.Port)
	pubkey, err := hex.DecodeString(seedNode.PublicKey)
	if err != nil {
		throw = err
	}
	c_public_key := (*C.uint8_t)(&pubkey[0])
	var c_error C.TOX_ERR_BOOTSTRAP
	// Bootstrap the network connection.
	C.tox_bootstrap(tox.handle, c_host, c_port, c_public_key, &c_error)
	// Check if an error occurred.
	if c_error != C.TOX_ERR_BOOTSTRAP_OK {
		// Assign the error to the return value.
		switch c_error {
		case C.TOX_ERR_BOOTSTRAP_NULL:
			throw = ToxErrBootstrapNull
		case C.TOX_ERR_BOOTSTRAP_BAD_HOST:
			throw = ToxErrBootstrapBadHost
		case C.TOX_ERR_BOOTSTRAP_BAD_PORT:
			throw = ToxErrBootstrapBadPort
		default:
			throw = ToxErrUnknown
		}
	}
	return
}
Пример #23
0
// get an item from the cache
func CacheGet(key string) []byte {
	if int(C.uwsgi_cache_enabled()) == 0 {
		return nil
	}

	k := C.CString(key)
	defer C.free(unsafe.Pointer(k))
	kl := len(key)
	var vl C.uint64_t = C.uint64_t(0)

	C.uwsgi_cache_rlock()

	c_value := C.uwsgi_cache_get(k, C.uint16_t(kl), &vl)

	var p []byte

	if vl > 0 {
		p = C.GoBytes((unsafe.Pointer)(c_value), C.int(vl))
	} else {
		p = nil
	}

	C.uwsgi_cache_rwunlock()

	return p
}
Пример #24
0
func diffOptionsToC(opts *DiffOptions) (copts *C.git_diff_options, notifyData *diffNotifyData) {
	cpathspec := C.git_strarray{}
	if opts != nil {
		notifyData = &diffNotifyData{
			Callback: opts.NotifyCallback,
		}
		if opts.Pathspec != nil {
			cpathspec.count = C.size_t(len(opts.Pathspec))
			cpathspec.strings = makeCStringsFromStrings(opts.Pathspec)
		}

		copts = &C.git_diff_options{
			version:           C.GIT_DIFF_OPTIONS_VERSION,
			flags:             C.uint32_t(opts.Flags),
			ignore_submodules: C.git_submodule_ignore_t(opts.IgnoreSubmodules),
			pathspec:          cpathspec,
			context_lines:     C.uint32_t(opts.ContextLines),
			interhunk_lines:   C.uint32_t(opts.InterhunkLines),
			id_abbrev:         C.uint16_t(opts.IdAbbrev),
			max_size:          C.git_off_t(opts.MaxSize),
			old_prefix:        C.CString(opts.OldPrefix),
			new_prefix:        C.CString(opts.NewPrefix),
		}

		if opts.NotifyCallback != nil {
			C._go_git_setup_diff_notify_callbacks(copts)
			copts.notify_payload = unsafe.Pointer(notifyData)
		}
	}
	return
}
Пример #25
0
func dmTaskSetCookieFct(task *CDmTask, cookie *uint, flags uint16) int {
	cCookie := C.uint32_t(*cookie)
	defer func() {
		*cookie = uint(cCookie)
	}()
	return int(C.dm_task_set_cookie((*C.struct_dm_task)(task), &cCookie, C.uint16_t(flags)))
}
Пример #26
0
func (t *tcpClient) enqueue(chunk []byte) error {
	cchunk := C.CString(string(chunk))
	defer C.free(unsafe.Pointer(cchunk))

	sleepTime := time.Millisecond * 5

	for j := 0; j < maxEnqueueAttempts; j++ {
		err_t := C.tcp_write(t.client.pcb, unsafe.Pointer(cchunk), C.uint16_t(len(chunk)), 1)
		if err_t == C.ERR_OK {
			return nil
		}

		if err_t == C.ERR_MEM {
			// Could not enqueue anymore, let's flush and try again.
			err_t := C.tcp_output(t.client.pcb)
			if err_t == C.ERR_OK {
				// Last part was flushed, now continue and try again...
				time.Sleep(sleepTime)
				if sleepTime < maxWaitingTime {
					sleepTime = sleepTime * 2
				}
				continue
			}
			return fmt.Errorf("tcp_output: %d", int(err_t))
		}
	}

	return fmt.Errorf("Could not flush data. Giving up.")
}
Пример #27
0
// const char *nurs_input_string(const struct nurs_input *input, uint16_t idx);
func nursInputString(input *Input, idx uint16) (string, error) {
	ret, err := C.nurs_input_string((*C.struct_nurs_input)(input), C.uint16_t(idx))
	if err != nil {
		return "", err
	}
	// return C.GoStringN((*C.char)(ret), C.int(C.nurs_input_size((*C.struct_nurs_input)(input), C.uint16_t(idx)))), nil
	return C.GoString((*C.char)(ret)), nil
}
Пример #28
0
func (d *Device) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) {
	//log.Printf("control xfer: %d:%d/%d:%d %x", idx, rType, request, val, string(data))
	dataSlice := (*reflect.SliceHeader)(unsafe.Pointer(&data))
	n := C.libusb_control_transfer(
		d.handle,
		C.uint8_t(rType),
		C.uint8_t(request),
		C.uint16_t(val),
		C.uint16_t(idx),
		(*C.uchar)(unsafe.Pointer(dataSlice.Data)),
		C.uint16_t(len(data)),
		C.uint(d.ControlTimeout/time.Millisecond))
	if n < 0 {
		return int(n), usbError(n)
	}
	return int(n), nil
}
Пример #29
0
func (u *uc) RegWriteMmr(reg int, value *X86Mmr) error {
	var val C.uc_x86_mmr
	val.selector = C.uint16_t(value.Selector)
	val.base = C.uint64_t(value.Base)
	val.limit = C.uint32_t(value.Limit)
	val.flags = C.uint32_t(value.Flags)
	ucerr := C.uc_reg_write(u.handle, C.int(reg), unsafe.Pointer(&val))
	return errReturn(ucerr)
}
Пример #30
0
func (t *HashTree) Add(key string, item *Item) {
	p := C.CString(key)
	defer C.free(unsafe.Pointer(p))
	pos := (uint32(item.Bucket)) + uint32(item.Pos)
	C.ht_add(t.tree, p,
		C.uint32_t(pos),
		C.uint16_t(item.Hash),
		C.int32_t(item.Version))
}