Exemple #1
0
func (d *Device) beginPoll() {
	// Entry point for the goroutine.
	go d.recvResponse()
	buf := make([]byte, 4)
	for {
		var n int
		var err error
		n, err = unix.Read(d.uioFd, buf)
		if n == -1 && err != nil {
			fmt.Println(err)
			break
		}
		for {
			cmd, err := d.getNextCommand()
			if err != nil {
				log.Errorf("error getting next command: %s", err)
				break
			}
			if cmd == nil {
				break
			}
			d.cmdChan <- cmd
		}
	}
	close(d.cmdChan)
}
func (tfd testFd) get(t *testing.T) {
	buf := make([]byte, 10)
	_, errno := unix.Read(tfd[0], buf)
	if errno != nil {
		t.Fatalf("Failed to read from pipe: %v", errno)
	}
}
Exemple #3
0
func TestDup(t *testing.T) {
	file, err := ioutil.TempFile("", "TestDup")
	if err != nil {
		t.Fatalf("Tempfile failed: %v", err)
	}
	defer os.Remove(file.Name())
	defer file.Close()
	f := int(file.Fd())

	newFd, err := unix.Dup(f)
	if err != nil {
		t.Fatalf("Dup: %v", err)
	}

	err = unix.Dup2(newFd, newFd+1)
	if err != nil {
		t.Fatalf("Dup2: %v", err)
	}

	b1 := []byte("Test123")
	b2 := make([]byte, 7)
	_, err = unix.Write(newFd+1, b1)
	if err != nil {
		t.Fatalf("Write to dup2 fd failed: %v", err)
	}
	_, err = unix.Seek(f, 0, 0)
	_, err = unix.Read(f, b2)
	if err != nil {
		t.Fatalf("Read back failed: %v", err)
	}
	if string(b1) != string(b2) {
		t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
	}
}
Exemple #4
0
func (c conn) Read(b []byte) (n int, err error) {
	n, err = unix.Read(c.fd, b)
	if n == 0 && err == nil {
		err = io.EOF
	}
	if err != nil {
		err = Err{err}
	}
	return
}
func (poller *fdPoller) clearWake() error {
	// You have to be woken up a LOT in order to get to 100!
	buf := make([]byte, 100)
	n, errno := unix.Read(poller.pipe[0], buf)
	if n == -1 {
		if errno == unix.EAGAIN {
			// Buffer is empty, someone else cleared our wake.
			return nil
		}
		return errno
	}
	return nil
}
Exemple #6
0
// readEvents reads from the inotify file descriptor, converts the
// received events into Event objects and sends them via the Events channel
func (w *Watcher) readEvents() {
	var (
		buf   [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
		n     int                                  // Number of bytes read with read()
		errno error                                // Syscall errno
		ok    bool                                 // For poller.wait
	)

	defer close(w.doneResp)
	defer close(w.Errors)
	defer close(w.Events)
	defer unix.Close(w.fd)
	defer w.poller.close()

	for {
		// See if we have been closed.
		if w.isClosed() {
			return
		}

		ok, errno = w.poller.wait()
		if errno != nil {
			select {
			case w.Errors <- errno:
			case <-w.done:
				return
			}
			continue
		}

		if !ok {
			continue
		}

		n, errno = unix.Read(w.fd, buf[:])
		// If a signal interrupted execution, see if we've been asked to close, and try again.
		// http://man7.org/linux/man-pages/man7/signal.7.html :
		// "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable"
		if errno == unix.EINTR {
			continue
		}

		// unix.Read might have been woken up by Close. If so, we're done.
		if w.isClosed() {
			return
		}

		if n < unix.SizeofInotifyEvent {
			var err error
			if n == 0 {
				// If EOF is received. This should really never happen.
				err = io.EOF
			} else if n < 0 {
				// If an error occurred while reading.
				err = errno
			} else {
				// Read was too short.
				err = errors.New("notify: short read in readEvents()")
			}
			select {
			case w.Errors <- err:
			case <-w.done:
				return
			}
			continue
		}

		var offset uint32
		// We don't know how many events we just read into the buffer
		// While the offset points to at least one whole event...
		for offset <= uint32(n-unix.SizeofInotifyEvent) {
			// Point "raw" to the event in the buffer
			raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset]))

			mask := uint32(raw.Mask)
			nameLen := uint32(raw.Len)
			// If the event happened to the watched directory or the watched file, the kernel
			// doesn't append the filename to the event, but we would like to always fill the
			// the "Name" field with a valid filename. We retrieve the path of the watch from
			// the "paths" map.
			w.mu.Lock()
			name := w.paths[int(raw.Wd)]
			w.mu.Unlock()
			if nameLen > 0 {
				// Point "bytes" at the first byte of the filename
				bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))
				// The filename is padded with NULL bytes. TrimRight() gets rid of those.
				name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
			}

			event := newEvent(name, mask)

			// Send the events that are not ignored on the events channel
			if !event.ignoreLinux(w, raw.Wd, mask) {
				select {
				case w.Events <- event:
				case <-w.done:
					return
				}
			}

			// Move to the next event in the buffer
			offset += unix.SizeofInotifyEvent + nameLen
		}
	}
}
Exemple #7
0
func main() {
	fmt.Println("Listening on port :", port)
	counter := new(connCounter)

	// create socket
	fd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, 0)
	if err != nil {
		log.Fatal("socket-error: ", err)
	}

	// sa struct
	sa := new(unix.SockaddrInet4)
	sa.Port = 9090

	// bind
	err = unix.Bind(fd, sa)
	if err != nil {
		log.Fatal("bind: ", err)
	}

	// listen
	err = unix.Listen(fd, 3)
	if err != nil {
		log.Fatal("listen: ", err)
	}

	for {
		connInfo := new(connection)
		// accept connection, discard SA struct
		newFd, _, err := unix.Accept(fd)
		connInfo.fd = newFd
		if err != nil {
			log.Fatal("accept: ", err)
		}

		// client reads until closes, adding
		// a gorutine allows dealing with more
		// requests.
		counter.mu.Lock()
		counter.num += 1
		counter.mu.Unlock()
		fmt.Println("Number of connections: ", counter.num)
		go func(c *connection, counter *connCounter) {
			fmt.Printf("Conn.fd=%d\n", c.fd)
			for {
				// read
				c.buf = make([]byte, 50)
				n, err := unix.Read(c.fd, c.buf)
				if err != nil {
					log.Fatal("read: ", err)
				}

				fmt.Printf("Read: %d Value: %s\n", n, string(c.buf[0:n]))

				// close
				if string(c.buf[0:5]) == "close" {
					_, err = unix.Write(c.fd, []byte(`Bye bye buddy`))
					if err != nil {
						log.Fatal("close: ", err)
					}

					err = unix.Close(c.fd)
					if err != nil {
						log.Fatal("close: ", err)
					}
					counter.mu.Lock()
					counter.num = counter.num - 1
					counter.mu.Unlock()
					return
				}
			}
		}(connInfo, counter)
	}
}
Exemple #8
0
func (s *Socket) Read(p []byte) (int, error) {
	s.rmu.Lock()
	defer s.rmu.Unlock()
	n, err := unix.Read(s.fd, p)
	return n, errors.Wrap(err, "can't read hci socket")
}
Exemple #9
0
// ReadPassword reads characters from the input until press Enter or until
// fill in the given slice.
//
// Only reads characters that include letters, marks, numbers, punctuation,
// and symbols from Unicode categories L, M, N, P, S, besides of the
// ASCII space character.
// Ctrl-C interrumpts, and backspace removes the last character read.
//
// Returns the number of bytes read.
func ReadPassword(password []byte) (n int, err error) {
	ter, err := New()
	if err != nil {
		return 0, err
	}
	defer func() {
		err2 := ter.Restore()
		if err2 != nil && err == nil {
			err = err2
		}
	}()

	if err = ter.RawMode(); err != nil {
		return 0, err
	}

	key := make([]byte, 4) // In-memory representation of a rune.
	lenPassword := 0       // Number of characters read.

	if PasswordShadowed {
		rand.Seed(int64(time.Now().Nanosecond()))
	}

L:
	for {
		n, err = unix.Read(InputFD, key)
		if err != nil {
			return 0, err
		}

		if n == 1 {
			switch key[0] {
			case sys.K_RETURN:
				break L
			case sys.K_BACK:
				if lenPassword != 0 {
					lenPassword--
					password[lenPassword] = 0
				}
				continue
			case sys.K_CTRL_C:
				unix.Write(unix.Stdout, _CTRL_C)
				// Clean data stored, if any.
				for i, v := range password {
					if v == 0 {
						break
					}
					password[i] = 0
				}
				return 0, nil
			}
		}

		char, _ := utf8.DecodeRune(key)
		if unicode.IsPrint(char) {
			password[lenPassword] = key[0] // Only want a character by key
			lenPassword++

			if PasswordShadowed {
				unix.Write(unix.Stdout, bytes.Repeat(_SHADOW_CHAR, rand.Intn(3)+1))
			}
			if lenPassword == len(password) {
				break
			}
		}
	}

	unix.Write(unix.Stdout, _RETURN)
	n = lenPassword
	return
}