Exemple #1
0
// Run starts reading bytes from the serial port, (re)opening it if needed
// and sends the read bytes to the channel.
// Run blocks so should be called as a go routine.
func (sc *serialToChan) Run() {
	// Ser is nil when closed.
	var ser io.ReadWriteCloser

	for {
		// Open the serial port.
		if ser == nil {
			// Open serial port.
			log.Printf("LoopSerial: Opening the port.\n")
			var err error
			// Open the serial port.
			ser, err = openSerial(sc.port)
			if err != nil {
				log.Printf("LoopSerial: Error opening the port: %s.\n", err.Error())
				ser = nil
				time.Sleep(5 * time.Second)
			}
		}

		// b is nil if no bytes were received.
		var b []byte

		if ser != nil {
			// Read buf from serial.
			b = getBuffer("LoopSerial: asking for buffer.")
			n, err := ser.Read(b)
			if err != nil || n == 0 {
				// Error reading the serial port.
				log.Printf("LoopSerial: Error reading the serial port. Closing it.")
				// Return and invalidate the buffer.
				putBuffer(b, "LoopSerial: returning buffer because of read error.")
				b = nil
				// Close serial.
				ser.Close()
				ser = nil
			} else {
				b = b[:n]
			}
		}

		if b != nil {
			// Send the bytes to the channel.
			sc.bytesChan <- b
			// Set b to nil to indicate that it has been sent.
			b = nil
		}

		// Check if the done channel has been closed, but don't wait.
		select {
		case <-sc.done:
			// Time to stop.
			if ser != nil {
				ser.Close()
			}
			close(sc.bytesChan)
			return
		default:
		}
	}
}
Exemple #2
0
func PipeThenClose(src, dst io.ReadWriteCloser) {
	defer dst.Close()
	buf := make([]byte, MaxPacketSize)
	for {
		n, err := src.Read(buf)
		// read may return EOF with n > 0
		// should always process n > 0 bytes before handling error
		if n > 0 {
			// Note: avoid overwrite err returned by Read.
			if _, err := dst.Write(buf[0:n]); err != nil {
				log.Println("write:", err)
				break
			}
		}
		if err != nil {
			// Always "use of closed network connection", but no easy way to
			// identify this specific error. So just leave the error along for now.
			// More info here: https://code.google.com/p/go/issues/detail?id=4373
			/*
				if bool(Debug) && err != io.EOF {
					Debug.Println("read:", err)
				}
			*/
			log.Println("read:", err)
			break
		}
	}
}
Exemple #3
0
func handleScgiRequest(fd io.ReadWriteCloser) {
	var buf bytes.Buffer
	var tmp [1024]byte
	n, err := fd.Read(&tmp)
	if err != nil || n == 0 {
		return
	}

	colonPos := bytes.IndexByte(tmp[0:], ':')

	read := n
	length, _ := strconv.Atoi(string(tmp[0:colonPos]))
	buf.Write(tmp[0:n])

	for read < length {
		n, err := fd.Read(&tmp)
		if err != nil || n == 0 {
			break
		}

		buf.Write(tmp[0:n])
		read += n
	}

	req, err := readScgiRequest(&buf)

	if err != nil {
		log.Stderrf("SCGI read error", err.String())
		return
	}

	sc := scgiConn{fd, make(map[string][]string), false}
	routeHandler(req, &sc)
	fd.Close()
}
Exemple #4
0
func (s *Server) handleScgiRequest(fd io.ReadWriteCloser) {
	var buf bytes.Buffer
	tmp := make([]byte, 1024)
	n, err := fd.Read(tmp)
	if err != nil || n == 0 {
		return
	}

	colonPos := bytes.IndexByte(tmp[0:], ':')

	read := n
	length, _ := strconv.Atoi(string(tmp[0:colonPos]))
	buf.Write(tmp[0:n])

	for read < length {
		n, err := fd.Read(tmp)
		if err != nil || n == 0 {
			break
		}

		buf.Write(tmp[0:n])
		read += n
	}

	req, err := readScgiRequest(&buf)
	if err != nil {
		s.Logger.Println("SCGI read error", err.Error())
		return
	}

	sc := scgiConn{fd, req, make(map[string][]string), false}
	s.routeHandler(req, &sc)
	sc.finishRequest()
	fd.Close()
}
Exemple #5
0
func (client *Conn) proxy(rwc io.ReadWriteCloser) (bool, error) {
	var closed bool
	for job := range client.jobs {
		if closed {
			job.results <- rillResult{err: ErrClosedConnection{}}
			continue
		}
		switch job.op {
		case _read:
			n, err := rwc.Read(job.data)
			job.results <- rillResult{n, err}
			if err != nil {
				rwc.Close()
				return false, err
			}
		case _write:
			n, err := rwc.Write(job.data)
			job.results <- rillResult{n, err}
			if err != nil {
				rwc.Close()
				return false, err
			}
		case _close:
			closed = true
			err := rwc.Close()
			job.results <- rillResult{err: err}
			return true, err
		}
	}
	return false, nil
}
// Write an image into the led matrix
func WriteLEDMatrix(image *image.RGBA, s io.ReadWriteCloser) {

	//spew.Dump("writing image", image)

	finalFrame := ConvertImage(image)

	_, err := s.Write([]byte{cmdWriteBuffer})
	if err != nil {
		log.Fatalf("Failed writing write buffer command: %s", err)
	}

	_, err = s.Write(finalFrame[:])
	if err != nil {
		log.Fatalf("Failed writing frame: %s", err)
	}

	_, err = s.Write([]byte{cmdSwapBuffers})
	if err != nil {
		log.Fatalf("Failed writing swap buffer command: %s", err)
	}

	//log.Println("Wrote frame", n)
	buf := make([]byte, 1)
	_, err = s.Read(buf)
	if err != nil {
		log.Infof("Failed to read char after sending frame : %s", err)
	}
	if buf[0] != byte('F') {
		log.Infof("Expected an 'F', got '%q'", buf[0])
	}
}
Exemple #7
0
func assertEcho(t *testing.T, rwc io.ReadWriteCloser, m ma.Multiaddr) {
	str := "test string"
	done := make(chan struct{})
	defer rwc.Close()

	go func() {
		defer close(done)

		_, err := fmt.Fprint(rwc, str)
		if err != nil {
			t.Error(err)
			return
		}

		buf := make([]byte, 256)
		n, err := rwc.Read(buf)
		if err != nil {
			t.Error(err)
			return
		}
		got := string(buf[:n])

		if got != str {
			t.Errorf("expected \"%s\", got \"%s\"", str, got)
		}
	}()

	select {
	case <-done:
	case <-time.After(time.Second):
		t.Errorf("assertEcho: %s timed out", m.String())
	}
}
Exemple #8
0
func acceptAndWrite(rwc io.ReadWriteCloser, t *testing.T) {
	// write
	buf := []byte(msg)
	for len(buf) > 0 {
		n, err := rwc.Write(buf)
		if err != nil {
			t.Fatalf("write: %s", err)
		}
		buf = buf[n:]
	}

	// read
	buf2 := make([]byte, len(msg))
	free := buf2
	for len(free) > 0 {
		n, err := rwc.Read(free)
		if err != nil {
			t.Fatalf("write/read: %s", err)
		}
		free = free[n:]
	}
	if string(buf2) != msg {
		t.Fatalf("write/read crc fail")
	}

	// close
	if err := rwc.Close(); err != nil {
		t.Fatalf("write/close: %s", err)
	}
}
Exemple #9
0
func ProcessTroubleShooting(rwc io.ReadWriteCloser) {
	data := make([]byte, 0)
	buf := make([]byte, 1024)
	for {
		n, err := rwc.Read(buf)
		if nil != err {
			break
		}
		if len(data) == 0 {
			data = buf[0:n]
		} else {
			data = append(data, buf[0:n]...)
		}
		if len(data) > 1024 {
			fmt.Fprintf(rwc, "Too long command from input.")
			break
		}
		i := bytes.IndexByte(data, '\n')
		if -1 == i {
			continue
		}
		line := strings.TrimSpace(string(data[0:i]))
		data = data[i+1:]
		if len(line) == 0 {
			continue
		}

		err = Handle(line, rwc)
		if err == io.EOF {
			break
		}
	}
	rwc.Close()
}
Exemple #10
0
func ReceiveConnRequest(c io.ReadWriteCloser) bool {
	var buf [len("new")]byte
	c.Read(buf[0:])

	if string(buf[0:]) == "new" {
		return true
	}
	return true
}
// CallTestSequence to Davis Weather Station
// it must return "TEST"
func CallTestSequence(connection io.ReadWriteCloser) string {
	nb, err := connection.Write([]byte("TEST\n"))
	check(err)

	buf := make([]byte, 100)
	nb, err = connection.Read(buf)
	check(err)
	log.Infof("%d bytes: %s\n", nb, string(buf))
	return string(buf)
}
Exemple #12
0
// clientWrite gets data from c and prints it to Stdin.
func clientWrite(c io.ReadWriteCloser) {
	buf := make([]byte, 32000)
	for {
		n, err := c.Read(buf)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("[server]> %s\n>", buf[:n])
	}
}
func echoMsg(s io.ReadWriteCloser) error {
	b2 := make([]byte, 1024)
	n, err := s.Read(b2)
	if err != nil {
		return err
	}

	n, err = s.Write(b2[:n])
	if err != nil {
		return err
	}

	return nil
}
Exemple #14
0
func echo(rwc io.ReadWriteCloser, handler func(string) string) {
	for {
		buf := make([]byte, 256)
		n, err := rwc.Read(buf)
		if err != nil {
			log.Println(err)
			rwc.Close()
			return
		}
		s := strings.TrimRight(string(buf[:n]), "\n")
		s = handler(s)
		_, err = rwc.Write([]byte(s))
	}
}
Exemple #15
0
func (p *Process) exitWaitChannel(exitFd io.ReadWriteCloser) chan int {
	exitChan := make(chan int)
	go func(exitFd io.Reader, exitChan chan<- int, streaming *sync.WaitGroup) {
		b := make([]byte, 1)
		n, err := exitFd.Read(b)
		if n == 0 && err != nil {
			b[0] = UnknownExitStatus
		}

		exitChan <- int(b[0])
	}(exitFd, exitChan, p.streaming)

	return exitChan
}
Exemple #16
0
func (rpc *RPC) Accept(conn io.ReadWriteCloser) (*Peer, error) {
	peer := NewPeer(rpc, conn)
	buf := make([]byte, 32)
	_, err := conn.Read(buf)
	if err != nil {
		return nil, err
	}
	// TODO: check handshake
	_, err = conn.Write([]byte(HandshakeAccept))
	if err != nil {
		return nil, err
	}
	go peer.route()
	return peer, nil
}
// WakeUp davis Station with sending bites sequence
func WakeUp(connection io.ReadWriteCloser) bool {
	nb, err := connection.Write([]byte("\n"))
	check(err)

	buf := make([]byte, 10)
	nb, err = connection.Read(buf)
	check(err)
	log.Infof("%d bytes read from USB port on Wake Up connection: %s\n", nb, string(buf))
	if nb == 2 {
		time.Sleep(time.Second * 2)
		return true
	} else {
		return WakeUp(connection)
	}
}
Exemple #18
0
func sendJSON(conn io.ReadWriteCloser, json_data []byte, verb_type uint8) string {
	// send the two header bytes
	header := []byte{verb_type, uint8(len(json_data))} // len(json_data) MUST < 128
	_, err := conn.Write(header)
	checkErr("Unable to send header:", err)

	// send the actual json-encoded data
	_, err = conn.Write(json_data)
	checkErr("Unable to send data:", err)

	// wait for a response from the server
	response := make([]byte, 255)
	_, err = conn.Read(response)
	checkErr("Unable to read response:", err)

	return string(response)
}
Exemple #19
0
// handshake implements the client/server key exchange
// and returns a secure io.ReadWriteCloser if successful
// else it returns an error.
// Reads and writes are preformed concurrently, allowing
// both the client and server to call the same function
// without knowing who will read/write first.
func handshake(pub, priv *[32]byte, conn io.ReadWriteCloser) (io.ReadWriteCloser, error) {
	readDone := make(chan error)
	writeDone := make(chan error)
	peersPublicKey := make([]byte, 32)
	ppkArray := [32]byte{}

	go func(readDone chan<- error) {
		if n, err := conn.Read(peersPublicKey); n != 32 {
			readDone <- fmt.Errorf("key length error %d != 32\n", n)
			return
		} else if err != nil {
			readDone <- err
			return
		}
		for idx, val := range peersPublicKey {
			ppkArray[idx] = val
		}
		readDone <- nil
	}(readDone)

	go func(writeDone chan<- error) {
		if _, err := conn.Write(pub[:]); err != nil {
			writeDone <- err
			return
		}
		writeDone <- nil
	}(writeDone)

	// wait for read to finish
	err := <-readDone
	if err != nil {
		return nil, err
	}

	// wait for write to finish
	err = <-writeDone
	if err != nil {
		return nil, err
	}

	sr := NewSecureReader(conn, priv, &ppkArray)
	sw := NewSecureWriter(conn, priv, &ppkArray)
	return NewConnWrapper(sr, sw, conn), nil
}
Exemple #20
0
func (rpc *RPC) Handshake(conn io.ReadWriteCloser) (*Peer, error) {
	peer := NewPeer(rpc, conn)
	handshake := []byte(fmt.Sprintf("%s/%s;%s",
		ProtocolName, ProtocolVersion, rpc.codec.Name))
	_, err := conn.Write(handshake)
	if err != nil {
		return nil, err
	}
	buf := make([]byte, 32)
	_, err = conn.Read(buf)
	if err != nil {
		return nil, err
	}
	if buf[0] != '+' {
		panic(string(buf))
	}
	go peer.route()
	return peer, nil
}
Exemple #21
0
func copypaste(in, out io.ReadWriteCloser, close_in bool, msg string) {
	var buf [512]byte

	defer func() {
		if close_in {
			l.Log("eof closing connection")
			in.Close()
			out.Close()
		}
	}()

	for {
		n, err := in.Read(buf[0:])
		// on readerror, only bail if no other choice.
		if err == io.EOF {
			l.Log("msg: ", msg)
			// fmt.Print(msg)
			// time.Sleep(1e9)
			l.Log("eof", msg)
			return
		}
		l.Log("-- read ", n)
		if err != nil {
			l.Log("something wrong while copying in ot out ", msg)
			l.Log("error: ", err)
			return
		}
		// if n < 1 {
		// 	fmt.Println("nothign to read")
		// 	return
		// }

		l.Log("-- wrote msg bytes", n)

		_, err = out.Write(buf[0:n])
		if err != nil {
			l.Log("something wrong while copying out to in ")
			// l.Fatal("something wrong while copying out to in", err)
			return
		}
	}
}
Exemple #22
0
func parseHeader(rwc io.ReadWriteCloser, seq *uint64, method *string, plen *int32) error {
	var err error
	var sz int32
	setError(&err, binary.Read(rwc, binary.LittleEndian, seq))
	setError(&err, binary.Read(rwc, binary.LittleEndian, &sz))
	setError(&err, binary.Read(rwc, binary.LittleEndian, plen))
	if err != nil {
		return err
	}
	buf := make([]byte, sz)
	n, err := rwc.Read(buf)
	if err != nil {
		return err
	}
	if n != int(sz) {
		return fmt.Errorf("Expected: %v. Got: %v\n", sz, n)
	}
	*method = string(buf)
	return nil
}
Exemple #23
0
func readSerial(s io.ReadWriteCloser) ([]byte, error) {
	var inbuf, tmpbuf []byte
	for {
		tmpbuf = make([]byte, 256)
		n, err := s.Read(tmpbuf)
		inbuf = append(inbuf, tmpbuf[:n]...)
		if err != nil {
			//	if err == io.EOF {
			//		break
			//	}
			return nil, err
		}
		if len(inbuf) > 1 {
			term := []byte{'\n', '\r'}
			if bytes.Compare(inbuf[len(inbuf)-2:], term) == 0 {
				break
			}
		}
	}
	return inbuf, nil
}
Exemple #24
0
func echo(rwc io.ReadWriteCloser) (err error) {
	/*
		_, err = io.Copy(rwc, rwc)
		if err != nil {
			return err
		}
		return err
	*/
	buf := make([]byte, 1048)
	n, err := rwc.Read(buf)
	if err != nil {
		fmt.Println("read completed", err)
		return err
	}
	buf = buf[:n]
	_, err = rwc.Write(buf)
	if err != nil {
		return err
	}
	return err
}
Exemple #25
0
// Don't use this. It's used for the demo only.
func keyExchangeSendFirst(transport io.ReadWriteCloser) (*[32]byte, *[32]byte, *[32]byte) {
	publicKey := new([32]byte)
	privateKey := new([32]byte)
	peerKey := new([32]byte)
	publicKey, privateKey, err := box.GenerateKey(rand.Reader)
	if err != nil {
		defer transport.Close()
		panic(err)
	}
	_, err = transport.Write(publicKey[:])
	if err != nil {
		defer transport.Close()
		panic(err)
	}
	_, err = transport.Read(peerKey[:])
	if err != nil {
		defer transport.Close()
		panic(err)
	}
	return publicKey, privateKey, peerKey
}
func GetCurrentData(connection io.ReadWriteCloser, loopNumber int16, dataChannel chan<- *WeatherData, wg *sync.WaitGroup) error {
	_, err := connection.Write([]byte("LOOP " + string(loopNumber) + "\n"))
	log.Infof("Asked for %d LOOP\n", loopNumber)
	check(err)
	i := loopNumber
	ackBuf := make([]byte, 1)
	//log.Info("try to read for ACK")
	_, err = connection.Read(ackBuf)
	check(err)
	log.Infof("ACK bytes collected : %q\n", ackBuf)
	if ackBuf[0] == ACK || string(ackBuf[0]) == "L" {
		for i >= 1 {
			buf := make([]byte, 99)
			//log.Infof("Wait %d times for USB buffer read", i)
			nb, err := connection.Read(buf)
			if nb == 99 && err == nil {
				//log.Printf("%d bytes collected on WeatherStation: %q\n", nb, buf)
				weatherData := new(WeatherData)
				err = DecodeData(buf, weatherData)
				if err == nil {
					dataChannel <- weatherData
					time.Sleep(time.Second * 2)

				}
			} else {
				//log.Infof("error is %q", err)
				time.Sleep(time.Second * 2)

				log.Warnf("cannot decode %d bytes collected : %q\n", nb, buf)
			}
			i--
		}

	} else {
		log.Critical("can't get data from weather Station")
	}
	wg.Done()
	return nil
}
Exemple #27
0
func (link *Link) receive(port io.ReadWriteCloser) {
	got := make([]byte, 1)
	frame := make([]byte, 0)
	rx := make([]byte, 0)

	var xor byte

	for {
		n, err := port.Read(got)
		if err != nil {
			log.Fatal(err)
		}
		//		log.Println("got", got[:n])

		for _, ch := range got[:n] {
			rx = append(rx, ch)
			switch ch {
			case Mark:
				//				log.Println("rx", len(rx), rx)
				link.dispatch(frame)
				frame = make([]byte, 0)
				rx = make([]byte, 0)
			case Escape:
				xor = Xor
				link.Escaped += 1
			default:
				frame = append(frame, ch^xor)
				xor = 0

				if len(frame) > 100 {
					link.Overruns += 1
					log.Println("err: overrun")
					frame = make([]byte, 0)
				}
			}
		}
	}
}
Exemple #28
0
func (pf *fakePortForwarder) PortForward(name string, uid types.UID, port uint16, stream io.ReadWriteCloser) error {
	defer stream.Close()

	// read from the client
	received := make([]byte, len(pf.expected[port]))
	n, err := stream.Read(received)
	if err != nil {
		return fmt.Errorf("error reading from client for port %d: %v", port, err)
	}
	if n != len(pf.expected[port]) {
		return fmt.Errorf("unexpected length read from client for port %d: got %d, expected %d. data=%q", port, n, len(pf.expected[port]), string(received))
	}

	// store the received content
	pf.lock.Lock()
	pf.received[port] = string(received)
	pf.lock.Unlock()

	// send the hardcoded data to the client
	io.Copy(stream, strings.NewReader(pf.send[port]))

	return nil
}
Exemple #29
0
func cpflate(dst, src io.ReadWriteCloser) {
	w := lz4.NewWriter(dst)

	errc := make(chan error)
	rbuf := make(chan []byte)

	go func() {
		for {
			buf := make([]byte, 32*512)
			rlen, err := src.Read(buf)
			if err != nil {
				errc <- err
			}
			rbuf <- buf[0:rlen]
		}
	}()

loop:
	for {
		select {
		case <-time.Tick(time.Millisecond * 16):
			w.Flush()
		case buf := <-rbuf:
			_, err := w.Write(buf)
			if err != nil {
				break loop
			}
			w.Flush()

		case <-errc:

			break loop
		}

	}
}
// viaRTU is a private method which applies the given function validator,
// to make sure the functionCode passed is valid for the operation
// desired. If correct, it creates an RTUFrame given the corresponding
// information, attempts to open the serialDevice, and if successful, transmits
// it to the modbus server (slave device) specified by the given serial connection,
// and returns a byte array of the slave device's reply, and error (if any)
func viaRTU(connection io.ReadWriteCloser, fnValidator func(byte) bool, slaveAddress, functionCode byte, startRegister, numRegisters uint16, data []byte, timeOut int, debug bool) ([]byte, error) {
	if fnValidator(functionCode) {
		frame := new(RTUFrame)
		frame.TimeoutInMilliseconds = timeOut
		frame.SlaveAddress = slaveAddress
		frame.FunctionCode = functionCode
		frame.StartRegister = startRegister
		frame.NumberOfRegisters = numRegisters
		if len(data) > 0 {
			frame.Data = data
		}

		// generate the ADU from the RTU frame
		adu := frame.GenerateRTUFrame()
		if debug {
			log.Println(fmt.Sprintf("Tx: %x", adu))
		}

		// transmit the ADU to the slave device via the
		// serial port represented by the fd pointer
		_, werr := connection.Write(adu)
		if werr != nil {
			if debug {
				log.Println(fmt.Sprintf("RTU Write Err: %s", werr))
			}
			return []byte{}, werr
		}

		// allow the slave device adequate time to respond
		time.Sleep(time.Duration(frame.TimeoutInMilliseconds) * time.Millisecond)

		// then attempt to read the reply
		response := make([]byte, RTU_FRAME_MAXSIZE)
		n, rerr := connection.Read(response)
		if rerr != nil {
			if debug {
				log.Println(fmt.Sprintf("RTU Read Err: %s", rerr))
			}
			return []byte{}, rerr
		}

		// check the validity of the response
		if response[0] != frame.SlaveAddress || response[1] != frame.FunctionCode {
			if debug {
				log.Println("RTU Response Invalid")
			}
			if response[0] == frame.SlaveAddress && (response[1]&0x7f) == frame.FunctionCode {
				switch response[2] {
				case EXCEPTION_ILLEGAL_FUNCTION:
					return []byte{}, MODBUS_EXCEPTIONS[EXCEPTION_ILLEGAL_FUNCTION]
				case EXCEPTION_DATA_ADDRESS:
					return []byte{}, MODBUS_EXCEPTIONS[EXCEPTION_DATA_ADDRESS]
				case EXCEPTION_DATA_VALUE:
					return []byte{}, MODBUS_EXCEPTIONS[EXCEPTION_DATA_VALUE]
				case EXCEPTION_SLAVE_DEVICE_FAILURE:
					return []byte{}, MODBUS_EXCEPTIONS[EXCEPTION_SLAVE_DEVICE_FAILURE]
				}
			}
			return []byte{}, MODBUS_EXCEPTIONS[EXCEPTION_UNSPECIFIED]
		}

		// confirm the checksum (crc)
		response_crc := crc(response[:(n - 2)])
		if response[(n-2)] != byte((response_crc&0xff)) ||
			response[(n-1)] != byte((response_crc>>8)) {
			// crc failed (odd that there's no specific code for it)
			if debug {
				log.Println("RTU Response Invalid: Bad Checksum")
			}
			// return the response bytes anyway, and let the caller decide
			return response[:n], MODBUS_EXCEPTIONS[EXCEPTION_BAD_CHECKSUM]
		}

		// return only the number of bytes read
		return response[:n], nil
	}

	return []byte{}, MODBUS_EXCEPTIONS[EXCEPTION_ILLEGAL_FUNCTION]
}