Exemplo n.º 1
0
func (p *Port) read(b []byte) (n int, err error) {
	var done uint32
	err = syscall.ReadFile(p.handle, b, &done, nil)
	n = int(done)

	return
}
Exemplo n.º 2
0
func (p *serialPort) Read(buf []byte) (int, error) {
	//fmt.Printf("read(<%d bytes>)\n", len(buf))
	if p == nil || p.f == nil {
		return 0, fmt.Errorf("Invalid port on read %v %v", p, p.f)
	}

	p.rl.Lock()
	defer p.rl.Unlock()

	if err := resetEvent(p.ro.HEvent); err != nil {
		return 0, err
	}
	var done uint32
	//fmt.Printf("calling ReadFile... ")
	err := syscall.ReadFile(p.fd, buf, &done, p.ro)
	//fmt.Printf(" done. %d, %v\n", done, err)
	if err != nil && err != syscall.ERROR_IO_PENDING {
		return int(done), err
	}

	//fmt.Printf("getting OverlappedResult... ")
	n, err := getOverlappedResult(p.fd, p.ro)
	//fmt.Printf(" done. n %d err %v\n", n, err)
	if n == 0 && err == nil {
		return n, winSersTimeout{}
	}
	return n, err
}
Exemplo n.º 3
0
func (t *tun) Read(ch chan []byte) (err error) {
	overlappedRx := syscall.Overlapped{}
	var hevent windows.Handle
	hevent, err = windows.CreateEvent(nil, 0, 0, nil)
	if err != nil {
		return
	}
	overlappedRx.HEvent = syscall.Handle(hevent)
	buf := make([]byte, t.mtu)
	var l uint32
	for {
		if err := syscall.ReadFile(t.fd, buf, &l, &overlappedRx); err != nil {
		}
		if _, err := syscall.WaitForSingleObject(overlappedRx.HEvent, syscall.INFINITE); err != nil {
			fmt.Println(err)
		}
		overlappedRx.Offset += l
		totalLen := 0
		switch buf[0] & 0xf0 {
		case 0x40:
			totalLen = 256*int(buf[2]) + int(buf[3])
		case 0x60:
			continue
			totalLen = 256*int(buf[4]) + int(buf[5]) + IPv6_HEADER_LENGTH
		}
		fmt.Println("read data", buf[:totalLen])
		send := make([]byte, totalLen)
		copy(send, buf)
		ch <- send
	}
}
Exemplo n.º 4
0
func (p *Port) Read(buf []byte) (int, error) {
	if p == nil || p.f == nil {
		return 0, fmt.Errorf("Invalid port on read %v %v", p, p.f)
	}

	p.rl.Lock()
	defer p.rl.Unlock()

	fmt.Println("Reset Event")

	if err := resetEvent(p.ro.HEvent); err != nil {
		return 0, err
	}

	fmt.Println("Reset Event Done")

	var done uint32

	//Public Declare Auto Function ReadFile Lib "kernel32.dll" (ByVal hFile As IntPtr, _
	//   ByVal lpBuffer As Byte(), ByVal nNumberOfBytesToRead As Int32, _
	//      ByRef lpNumberOfBytesRead As Int32, ByVal lpOverlapped As IntPtr) As Boolean
	err := syscall.ReadFile(p.fd, buf, &done, p.ro)

	fmt.Println("WriteFile Done")

	if err != nil && err != syscall.ERROR_IO_PENDING {
		return int(done), err
	}
	return getOverlappedResult(p.fd, p.ro)
}
Exemplo n.º 5
0
// Read implements the net.Conn Read method.
func (c *PipeConn) Read(b []byte) (int, error) {
	// Use ReadFile() rather than Read() because the latter
	// contains a workaround that eats ERROR_BROKEN_PIPE.
	overlapped, err := newOverlapped()
	if err != nil {
		return 0, err
	}
	var n uint32
	err = syscall.ReadFile(c.handle, b, &n, overlapped)
	return c.completeRequest(iodata{n, err}, c.readDeadline, overlapped)
}
Exemplo n.º 6
0
// Read reads from serial port.
// It is blocked until data received or timeout after p.timeout.
func (p *port) Read(b []byte) (n int, err error) {
	var done uint32
	if err = syscall.ReadFile(p.handle, b, &done, nil); err != nil {
		return
	}
	if done == 0 {
		err = ErrTimeout
		return
	}
	n = int(done)
	return
}
Exemplo n.º 7
0
func (p *pipe) Read(b []byte) (int, error) {
	// syscall.Read returns 0, nil on ERROR_BROKEN_PIPE, but for
	// our purposes this should indicate EOF. This may be a go bug.
	var read uint32
	err := syscall.ReadFile(p.handle, b, &read, nil)
	if err != nil {
		if err == syscall.ERROR_BROKEN_PIPE {
			return 0, io.EOF
		}
		return 0, err
	}
	return int(read), nil
}
Exemplo n.º 8
0
// readConsole reads utf16 characters from console File,
// encodes them into utf8 and stores them in buffer b.
// It returns the number of utf8 bytes read and an error, if any.
func (f *File) readConsole(b []byte) (n int, err error) {
	if len(b) == 0 {
		return 0, nil
	}
	if len(f.readbuf) == 0 {
		numBytes := len(b)
		// Windows  can't read bytes over max of int16.
		if numBytes > 32767 {
			numBytes = 32767
		}
		mbytes := make([]byte, numBytes)
		var nmb uint32
		err := syscall.ReadFile(f.fd, mbytes, &nmb, nil)
		if err != nil {
			return 0, err
		}
		if nmb > 0 {
			var pmb *byte
			if len(b) > 0 {
				pmb = &mbytes[0]
			}
			acp, err := windows.GetACP()
			if err != nil {
				return 0, err
			}
			nwc, err := windows.MultiByteToWideChar(acp, 2, pmb, int32(nmb), nil, 0)
			if err != nil {
				return 0, err
			}
			wchars := make([]uint16, nwc)
			pwc := &wchars[0]
			nwc, err = windows.MultiByteToWideChar(acp, 2, pmb, int32(nmb), pwc, int32(nwc))
			if err != nil {
				return 0, err
			}
			f.readbuf = utf16.Decode(wchars[:nwc])
		}
	}
	for i, r := range f.readbuf {
		if utf8.RuneLen(r) > len(b) {
			f.readbuf = f.readbuf[i:]
			return n, nil
		}
		nr := utf8.EncodeRune(b, r)
		b = b[nr:]
		n += nr
	}
	f.readbuf = nil
	return n, nil
}
Exemplo n.º 9
0
func (p *virtioPort) Read(buf []byte) (int, error) {
	if p == nil || p.f == nil {
		return 0, fmt.Errorf("Invalid port on read %v %v", p, p.f)
	}
	p.rl.Lock()
	defer p.rl.Unlock()
	if err := resetEvent(p.ro.HEvent); err != nil {
		return 0, err
	}
	var done uint32
	err := syscall.ReadFile(p.fd, buf, &done, p.ro)
	if err != nil && err != syscall.ERROR_IO_PENDING {
		return int(done), err
	}
	return getOverlappedResult(p.fd, p.ro)
}
Exemplo n.º 10
0
// Read reads from a file handle.
func (f *win32File) Read(b []byte) (int, error) {
	c, err := f.prepareIo()
	if err != nil {
		return 0, err
	}
	var bytes uint32
	err = syscall.ReadFile(f.handle, b, &bytes, &c.o)
	n, err := f.asyncIo(c, f.readDeadline, bytes, err)

	// Handle EOF conditions.
	if err == nil && n == 0 && len(b) != 0 {
		return 0, io.EOF
	} else if err == syscall.ERROR_BROKEN_PIPE {
		return 0, io.EOF
	} else {
		return n, err
	}
}
Exemplo n.º 11
0
// pread reads len(b) bytes from the File starting at byte offset off.
// It returns the number of bytes read and the error, if any.
// EOF is signaled by a zero count with err set to 0.
func (f *File) pread(b []byte, off int64) (n int, err error) {
	f.l.Lock()
	defer f.l.Unlock()
	curoffset, e := syscall.Seek(f.fd, 0, 1)
	if e != nil {
		return 0, e
	}
	defer syscall.Seek(f.fd, curoffset, 0)
	o := syscall.Overlapped{
		OffsetHigh: uint32(off >> 32),
		Offset:     uint32(off),
	}
	var done uint32
	e = syscall.ReadFile(syscall.Handle(f.fd), b, &done, &o)
	if e != nil {
		return 0, e
	}
	return int(done), nil
}
Exemplo n.º 12
0
func (t *Interface) Read(ch chan []byte) (err error) {
	rx := syscall.Overlapped{}
	var hevent windows.Handle
	hevent, err = windows.CreateEvent(nil, 0, 0, nil)
	if err != nil {
		return
	}
	rx.HEvent = syscall.Handle(hevent)
	buf := make([]byte, 1500)
	var l uint32
	for {
		if err := syscall.ReadFile(t.file, buf, &l, &rx); err != nil {
		}
		if _, err := syscall.WaitForSingleObject(rx.HEvent, syscall.INFINITE); err != nil {
			Log(Error, "Failed to read from TUN/TAP: %v", err)
		}
		rx.Offset += l
		ch <- buf
	}
}
Exemplo n.º 13
0
func (p *dev) Read(buf []byte) (int, error) {
	var done uint32

	for {
		var ov syscall.Overlapped

		ov.HEvent = p.ev.r
		if e := syscall.ReadFile(p.fd, buf, &done, &ov); e != nil {
			if e != syscall.ERROR_IO_PENDING {
				return 0, &os.PathError{"reading from", p.name, e}
			}
			if e = win.GetOverlappedResult(p.fd, &ov, &done, 1); e != nil {
				return 0, &os.PathError{"reading from", p.name, e}
			}
		}
		if done > 0 {
			break
		}
	}
	return int(done), nil
}
Exemplo n.º 14
0
func (port *windowsPort) Read(p []byte) (int, error) {
	var readed uint32
	params := &dcb{}
	for {
		if err := syscall.ReadFile(port.handle, p, &readed, nil); err != nil {
			return int(readed), err
		}
		if readed > 0 {
			return int(readed), nil
		}

		// At the moment it seems that the only reliable way to check if
		// a serial port is alive in Windows is to check if the SetCommState
		// function fails.

		getCommState(port.handle, params)
		if err := setCommState(port.handle, params); err != nil {
			port.Close()
			return 0, err
		}
	}
}
Exemplo n.º 15
0
func (dev *SerialDevice) Read(buf []byte) (int, error) {
	if dev == nil || dev.f == nil {
		return 0, fmt.Errorf("[ERROR] invalid port on read: %v %v", dev, dev.f)
	}

	dev.rl.Lock()
	defer dev.rl.Unlock()

	if err := syscallEvent(dev.ro.HEvent, "reset"); err != nil {
		fmt.Printf("[errr] %v\n", err)
		return 0, err
	}

	var done uint32
	err := syscall.ReadFile(dev.fd, buf, &done, dev.ro)
	if err != nil && err != syscall.ERROR_IO_PENDING {
		fmt.Printf("[errr] %v\n", err)
		return int(done), err
	}

	return getOverlapResult(dev.fd, dev.ro)
}
Exemplo n.º 16
0
// pread reads len(b) bytes from the File starting at byte offset off.
// It returns the number of bytes read and the error, if any.
// EOF is signaled by a zero count with err set to 0.
func (f *File) pread(b []byte, off int64) (n int, err error) {
	f.l.Lock()
	defer f.l.Unlock()
	curoffset, e := syscall.Seek(f.fd, 0, io.SeekCurrent)
	if e != nil {
		return 0, e
	}
	defer syscall.Seek(f.fd, curoffset, io.SeekStart)
	o := syscall.Overlapped{
		OffsetHigh: uint32(off >> 32),
		Offset:     uint32(off),
	}
	var done uint32
	e = syscall.ReadFile(f.fd, b, &done, &o)
	if e != nil {
		if e == syscall.ERROR_HANDLE_EOF {
			// end of file
			return 0, nil
		}
		return 0, e
	}
	return int(done), nil
}
Exemplo n.º 17
0
func main() {
	handle, err := syscall.CreateFile(syscall.StringToUTF16Ptr(port),
		syscall.GENERIC_READ|syscall.GENERIC_WRITE,
		0,   // mode
		nil, // security
		syscall.OPEN_EXISTING, // no creating new
		0,
		0)
	if err != nil {
		fmt.Print(err)
		return
	}
	fmt.Printf("handle created %d\n", handle)
	defer syscall.CloseHandle(handle)

	var dcb C.DCB
	dcb.BaudRate = 9600
	dcb.ByteSize = 8
	dcb.StopBits = C.ONESTOPBIT
	dcb.Parity = C.NOPARITY
	if C.SetCommState(C.HANDLE(handle), &dcb) == 0 {
		fmt.Printf("set comm state error %v\n", syscall.GetLastError())
		return
	}
	fmt.Printf("set comm state succeed\n")

	var timeouts C.COMMTIMEOUTS
	// time-out between charactor for receiving (ms)
	timeouts.ReadIntervalTimeout = 1000
	timeouts.ReadTotalTimeoutMultiplier = 0
	timeouts.ReadTotalTimeoutConstant = 1000
	timeouts.WriteTotalTimeoutMultiplier = 0
	timeouts.WriteTotalTimeoutConstant = 1000
	if C.SetCommTimeouts(C.HANDLE(handle), &timeouts) == 0 {
		fmt.Printf("set comm timeouts error %v\n", syscall.GetLastError())
		return
	}
	fmt.Printf("set comm timeouts succeed\n")

	var n uint32
	data := []byte("abc")
	err = syscall.WriteFile(handle, data, &n, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("write file succeed\n")
	fmt.Printf("Press Enter when ready for reading...")
	reader := bufio.NewReader(os.Stdin)
	_, _ = reader.ReadString('\n')

	data = make([]byte, 512)
	err = syscall.ReadFile(handle, data, &n, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("received data %v:\n", n)
	fmt.Printf("%x\n", data[:n])
	fmt.Printf("closed\n")
}
Exemplo n.º 18
0
func SerialChannels(name string, baud int, debug bool) (chan byte, chan byte, chan bool, chan bool, error) {
	var serFile *os.File
	var handle syscall.Handle
	var rl sync.Mutex
	var wl sync.Mutex
	var ro *syscall.Overlapped
	var wo *syscall.Overlapped

	chFromSerial := make(chan byte, 8192)
	chToSerial := make(chan byte, 8192)
	chQuitSerial := make(chan bool)
	chDTRSerial := make(chan bool)

	if len(name) > 0 && name[0] != '\\' {
		name = "\\\\.\\" + name
	}
	handle, err := syscall.CreateFile(syscall.StringToUTF16Ptr(name),
		syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING,
		syscall.FILE_ATTRIBUTE_NORMAL|syscall.FILE_FLAG_OVERLAPPED, 0)

	if err == nil {
		serFile = os.NewFile(uintptr(handle), name)
	}
	if err == nil {
		err = setCommState(handle, baud)
	}
	if err == nil {
		err = setupComm(handle, 64, 64)
	}
	if err == nil {
		err = setCommTimeouts(handle)
	}
	if err == nil {
		err = setCommMask(handle)
	}
	if err == nil {
		ro, err = newOverlapped()
	}
	if err == nil {
		wo, err = newOverlapped()
	}

	if err != nil {
		err = errors.New("OpenPort ERROR: " + err.Error())
	} else {
		chFromSerial = make(chan byte, 8192)
		chQuitFrom := make(chan bool)
		go func() {
			var count int
			var done uint32
			then := time.Now()
			datain := make([]byte, 8192)
			for q := false; q == false; {
				rl.Lock()
				readerr := resetEvent(ro.HEvent)
				if readerr == nil {
					readerr = syscall.ReadFile(handle, datain, &done, ro)
					if readerr == syscall.ERROR_IO_PENDING {
						count, readerr = getOverlappedResult(handle, ro)
					} else {
						count = int(done)
					}
				}
				rl.Unlock()

				din := datain[:count]

				if debug && len(din) > 0 {
					now := time.Now()
					fmt.Printf("\n(%v(%d)", now.Sub(then), len(din))
					then = now
					for _, c := range din {
						if c < byte(0x20) || c > byte(0x7E) {
							fmt.Printf("{%02X}", c)
						} else {
							fmt.Printf("%c", c)
						}
					}
					fmt.Print(")")
				}
				for _, c := range din {
					chFromSerial <- c
				}
				select {
				case q = <-chQuitFrom:
				default:
				}
				time.Sleep(10)
			}
		}()

		chToSerial = make(chan byte, 8192)
		chQuitTo := make(chan bool)
		go func() {
			dataout := make([]byte, 256)
			var count, wcount int
			var readflag bool
			then := time.Now()
			for q := false; q == false; {
				select {
				case q = <-chQuitTo:
				case dataout[0] = <-chToSerial:
					for readflag, wcount = true, 1; readflag && wcount < 256; wcount++ {
						select {
						case dataout[wcount] = <-chToSerial:
						default:
							readflag = false
							wcount--
						}
					}

					dout := dataout[:wcount]

					if debug {
						now := time.Now()
						fmt.Printf("\n\t[%v[%d]", now.Sub(then), len(dout))
						then = now
						for _, c := range dout {
							if c < byte(0x20) || c > byte(0x7E) {
								fmt.Printf("{%02X}", c)
							} else {
								fmt.Printf("%c", c)
							}
						}
						fmt.Print("]")
					}

					wl.Lock()

					writeerr := resetEvent(wo.HEvent)
					if writeerr == nil {
						var n uint32 = uint32(wcount)
						writeerr = syscall.WriteFile(handle, dout, &n, wo)
						count = int(n)
						if writeerr == syscall.ERROR_IO_PENDING {
							for i := 0; i < 10; i++ {
								count, writeerr = getOverlappedResult(handle, wo)
								if count != wcount {
									fmt.Printf("Serial port write erro3 %d %s %v %v %v\n", i, writeerr, writeerr, count, wcount)
								} else {
									break
								}
								time.Sleep(10)
							}
						}
					}
					wl.Unlock()
					if count != wcount {
						fmt.Printf("Serial port write error1 %s %v %v %v\n", writeerr, writeerr, count, wcount)
					}

				}
			}
		}()

		chQuitDTR := make(chan bool)
		go func() {
			for q := false; q == false; {
				select {
				case q = <-chQuitDTR:
				case dtr := <-chDTRSerial:
					if dtr {
						escapeCommFunction(handle, 5)
					} else {
						escapeCommFunction(handle, 6)
					}
				}
			}
		}()

		go func() {
			<-chQuitSerial
			serFile.Close()
			chQuitFrom <- true
			chQuitTo <- true
			chQuitDTR <- true
		}()
	}

	return chFromSerial, chToSerial, chDTRSerial, chQuitSerial, err
}