Exemple #1
0
func Md5file(path string) (hash_hex string, err error) {
	var file *os.File
	if file, err = os.OpenFile(path, os.O_RDONLY, 0644); err != nil {
		return
	}
	defer file.Close()

	h := md5.New()
	//io.Copy(h, file)
	var data []byte = make([]byte, 8192)
	var size int
	for {
		size, err = file.Read(data)
		if err != nil {
			break
		}
		h.Write(data[:size])
		h.Sum(nil)
	}
	if err != nil && err != io.EOF {
		return
	}
	hash_hex = fmt.Sprintf("%x", h.Sum(nil))
	err = nil
	return
}
Exemple #2
0
// GetChar reads a single byte.
func GetChar(f *os.File) (b byte, err error) {
	bs := make([]byte, 1, 1)
	if _, err = f.Read(bs); err != nil {
		return 0, err
	}
	return bs[0], err
}
Exemple #3
0
func (wndb *WordNetDb) dataLookup(fh *os.File, offset int64) ([]byte, error) {
	_, err := fh.Seek(offset, os.SEEK_SET)
	if err != nil {
		return nil, err
	}

	buffer := make([]byte, BUFFSIZE) // initial size of the buffer is 3kb
	line := make([]byte, 0, BUFFSIZE)
	prevLen := 0
	for {
		prevLen = len(line)
		n, err := fh.Read(buffer) // we read the next 3kb (or less)
		if err != nil && err != io.EOF {
			return nil, err
		}
		line = append(line, buffer[:]...)
		until := bytes.IndexByte(buffer, '\n')
		if until > 0 { // We have a full line
			return line[:prevLen+until], nil
		}
		if err == io.EOF || n < BUFFSIZE {
			return line, nil
		}
	}
	return nil, ERR_MSG(UNREACHABLE_CODE)
}
Exemple #4
0
func LoadConfig(fname string) (cfg Config, err error) {
	var fd *os.File
	var fs os.FileInfo
	var data []byte

	// Check if the config file exists, and create a buffer to hold it's content
	if fs, err = os.Stat(fname); err != nil {
		return
	}
	data = make([]byte, fs.Size())

	// Open and read the file into the buffer
	if fd, err = os.Open(fname); err != nil {
		return
	}
	defer fd.Close()

	if _, err = fd.Read(data); err != nil {
		return
	}

	// Parse the yaml into a struct
	cfg = Config{}

	err = yaml.Unmarshal(data, &cfg)
	if err != nil {
		return
	}

	// Set the hostname
	cfg.Hostname, _ = os.Hostname()

	return
}
Exemple #5
0
func main() {
	var src, dst *os.File
	src, _ = os.Open("base64")
	defer func() {
		src.Close()
		dst.Close()
	}()

	dst, _ = os.OpenFile("base64_2", os.O_WRONLY|os.O_CREATE, 0644)

	//_, err := io.Copy(dst, src)
	//fmt.Println(err)
	buf := make([]byte, 1024)
	for {
		nr, er := src.Read(buf)
		if nr > 0 {
			nw, _ := dst.Write(buf[0:nr])
			fmt.Println("write size:", nw)
		}
		if er == io.EOF {
			break
		}
	}

}
Exemple #6
0
func ReadPassword() ([]byte, error) {
	var err error
	var data []byte = make([]byte, KeySize)
	var tty *os.File

	if tty, err = os.Open("/dev/tty"); err != nil {
		return nil, err
	}

	C.savetermios(C.int(os.Stdin.Fd()))
	C.setnoecho(C.int(os.Stdin.Fd()))

	_, err = tty.Read(data)

	C.resettermios(C.int(os.Stdin.Fd()))

	if err != nil {
		return nil, err
	}

	tty.Close()

	fmt.Fprintln(os.Stderr)

	for k, c := range data {
		if c == '\n' {
			data[k] = 0
		}
	}

	return data, nil
}
Exemple #7
0
func (km *KeyManager) LoadKeys(file *os.File) (err error) {
	//load file
	km.keyPair = new(common.PrivateKey)
	km.keyPair.AllocateNew()

	n, err := file.Read(km.keyPair.Key[:])
	if err == nil {
		if n != 64 {
			err = errors.New(" n != ed25519.PrivateKeySize ")
		}
	}

	if err != nil {
		return
	}

	n, err = file.Read(km.keyPair.Pub.Key[:])
	if err == nil {
		if n != 32 {
			err = errors.New(" n != ed25519.PublicSize ")
		}
	}

	return
}
Exemple #8
0
// rawReadline tries to return a single line, not including the end-of-line
// bytes with raw Mode (without prompting nothing). Or if provided show some
// value instead of actual value.
func (i *UI) rawReadline(f *os.File) (string, error) {
	var resultBuf []byte
	for {
		var buf [1]byte
		n, err := f.Read(buf[:])
		if err != nil && err != io.EOF {
			return "", err
		}

		if n == 0 || buf[0] == '\n' || buf[0] == '\r' {
			break
		}

		if buf[0] == 3 {
			return "", ErrInterrupted
		}

		if i.mask {
			fmt.Fprintf(i.Writer, i.maskVal)
		}

		resultBuf = append(resultBuf, buf[0])
	}

	fmt.Fprintf(i.Writer, "\n")
	return string(resultBuf), nil
}
Exemple #9
0
func openRegion(f *os.File, writeable bool, offset int64) (*region, error) {
	_, err := f.Seek(offset, os.SEEK_SET)
	if err != nil {
		return nil, err
	}
	header := make([]byte, regionHeaderSize)
	_, err = f.Read(header)
	if err != nil {
		return nil, err
	}
	if bytes.Compare(header[:8], signature) != 0 {
		return nil, InvalidSignature
	}
	size := *(*int64)(unsafe.Pointer(&header[regionSizeOffset]))
	rid := *(*int64)(unsafe.Pointer(&header[regionId]))
	flags := syscall.PROT_READ
	if writeable {
		flags |= syscall.PROT_WRITE
	}
	d, err := syscall.Mmap(int(f.Fd()), offset, int(size), flags, syscall.MAP_SHARED)
	if err != nil {
		return nil, err
	}
	r := &region{
		id:                 rid,
		f:                  f,
		d:                  d,
		freePtr:            d[regionFreePointerOffset : regionFreePointerOffset+8],
		blockListNextIdPtr: d[len(d)-8 : len(d)],
	}
	return r, nil
}
Exemple #10
0
Fichier : undo.go Projet : rwl/gorf
func UndoCmd(args []string) (err error) {
	if len(args) != 0 {
		return errors.New("Usage: gorf [flags] undo")
	}

	lastChangePath := filepath.Join(LocalRoot, ".change.0.gorfc")

	var srcFile *os.File
	srcFile, err = os.Open(lastChangePath)
	if err != nil {
		return
	}

	buf := make([]byte, 1024)
	var n int
	n, err = srcFile.Read(buf)
	fmt.Printf("Undoing \"%s\"\n", strings.TrimSpace(string(buf[:n])))

	filepath.Walk(LocalRoot, undoscanner(0).Walk)

	ur := UndoRoller{incr: -1}
	filepath.Walk(LocalRoot, ur.Walk)
	return ur.err

	return
}
Exemple #11
0
func ReadAChunk(inFile *os.File) int {
	// make a buffer to keep chunks that are read
	if LastBlockSent {
		return 0
	}
	LastBlockSent = false
	chunk.blocknum++
	if chunk.blocknum > 0 {
		mybuf := make([]byte, 512)
		// read a chunk
		fmt.Println("About to read Block num ", chunk.blocknum, "the handle is", inFile, "END OF HANDLE***************************")
		n, err := inFile.Read(mybuf)
		if err != nil && err != io.EOF {
			panic(err)
		}
		chunk.nbytes = n
		chunk.buf = mybuf
		if n < 512 {
			LastBlockSent = true
		}
		return n
	} else {
		return 512
	}
}
Exemple #12
0
func readLine(file *os.File, bytes []byte) (int, error) {
	var i int
	b := make([]byte, 1)
	escaped := false

	for i = 0; i < len(bytes); i++ {
		_, err := file.Read(b)
		if err != nil {
			return i, err
		}

		if rune(b[0]) == '\\' {
			escaped = true
		} else if rune(b[0]) == '\n' {
			if escaped {
				escaped = false
				i -= 2
				continue
			} else {
				break
			}
		} else {
			escaped = false
		}

		bytes[i] = b[0]
	}

	return i, nil
}
Exemple #13
0
func readContents(file *os.File, length int32) {
	data := make([]byte, length)
	_, err := file.Read(data)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #14
0
func (b *Buffer) Load(q0 uint, fd *os.File, nulls *int) int {
	if q0 > b.nc {
		panic("internal error: buffer.Load")
	}

	p := make([]byte, MaxBlock+utf8.UTFMax+1)

	m := 0
	n := 1
	q1 := q0
	var err error

	for n > 0 {
		n, err = fd.Read(p[m:])
		if err != nil {
			panic(err)
		}
		m += n
		l := m
		if n > 0 {
			l -= utf8.UTFMax
		}
		r := bytes.Runes(p[:l])
		nr := len(r)
		//nb := len([]byte(string(r)))
		copy(p, p[:m])
		b.Insert(q1, uint(nr), r)
		q1 += uint(nr)
	}
	return int(q1 - q0)
}
func maxIpInPart(part *os.File) (ip3 int, max int) {
	ip3Array := make([]int, 1<<24, 1<<24)
	b := make([]byte, 1<<16*3)
	part.Seek(0, 0)
	for {
		n, err := part.Read(b)
		if n > 0 {
			for i := 0; i < n; i += 3 {
				ip3Array[int(Ip3BytesToUint32(b[i:i+3]))]++
			}

		}
		if err != nil {
			break
		}
	}

	for i := 0; i < len(ip3Array); i++ {
		if ip3Array[i] > max {
			max = ip3Array[i]
			ip3 = i
		}
	}
	return
}
Exemple #16
0
// Read a whole data segment and send to the inbound bytes
func (wal *WriteAheadLog) readDataPart(file *os.File, size int64) int64 {
	var _buf [BUFFER_SIZE]uint8
	var chunk int64
	left := size
	var nRead int64

	// Iterate over chunks
	for {
		if left > BUFFER_SIZE {
			chunk = BUFFER_SIZE
		} else {
			chunk = left
		}
		n, err := file.Read(_buf[:chunk])
		fmt.Printf("file read, n=%v, err=%v\n", n, err)
		if err == os.EOF {
			break
		}
		left -= int64(n)
		if err != nil {
			log.Fatalf("Failed to read %s\n", err)
		}
		// Replay the Inbound likes its a new bits
		wal.outProcessor <- pipe.NewReplayChunk(_buf[:n])
		nRead += int64(n)
	}
	return nRead
}
Exemple #17
0
func line(file *os.File) int {
	var b [1]byte
	buf := make([]byte, 0)
	for {
		_, err := file.Read(b[:])
		if err == io.EOF {
			if len(buf) == 0 {
				ret = 1
			}
			break
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, "read:", err)
			os.Exit(1)
		}
		buf = append(buf, b[0])
		if b[0] == '\n' {
			break
		}
	}
	if len(buf) > 0 {
		os.Stdout.Write(buf)
	}
	return len(buf)
}
Exemple #18
0
// Check if the file is a binary STL file
func isBinary(f *os.File) bool {

	fi, err := f.Stat()
	check(err)

	_, err = f.Seek(0, 0)
	check(err)

	buffer := make([]byte, 80)
	_, err = f.Read(buffer)
	check(err)

	buffer = make([]byte, 4)
	_, err = f.Read(buffer)
	check(err)

	var numTriangles int32 = 0
	reader := bytes.NewReader(buffer)
	err = binary.Read(reader, binary.LittleEndian, &numTriangles)
	check(err)

	if fi.Size() == int64(headerSize+triCountSize+int(numTriangles)*preTriSize) {
		return true
	}

	return false
}
Exemple #19
0
func dumpOutput(source *os.File) {
	if source == nil {
		return
	}

	defer source.Close()

	b := make([]byte, 256)
	for {
		n, err := source.Read(b)
		if err == io.EOF {
			log.Print("The output file descriptor has been closed")
			return
		}

		for o := 0; o < n; {
			m, err := os.Stdout.Write(b[o:n])
			if err != nil {
				log.Panic(err)
				return
			}
			o += m
		}
	}
}
Exemple #20
0
func (u *U16x16) GetData2(key string) (data []byte, err error) {
	var (
		found bool
		path  string
	)
	path, err = u.GetPathForKey(key)
	if err == nil {
		found, err = xf.PathExists(path)
	}
	if err == nil && !found {
		err = FileNotFound
	}
	if err == nil {
		var src *os.File
		if src, err = os.Open(path); err != nil {
			return
		}
		defer src.Close()
		var count int
		// XXX THIS WILL NOT WORK FOR LARGER FILES!  It will ignore
		//     anything over 128 KB
		data = make([]byte, DEFAULT_BUFFER_SIZE)
		count, err = src.Read(data)
		// XXX COUNT IS IGNORED
		_ = count
	}
	return
}
Exemple #21
0
func VersionTwo(pass, clear []byte, file *os.File) ([]byte, error) {
	var plain, cipher, blockpass []byte

	cipher = make([]byte, aes.BlockSize)
	blockpass = make([]byte, KeySize)

	copy(blockpass, pass)

	for {
		blockpass = TwoCreateNewPass(blockpass, clear)

		n, err := file.Read(cipher)
		if n != aes.BlockSize {
			break
		} else if err != nil {
			return []byte(nil), err
		}

		conv, err := aes.NewCipher(blockpass)
		if err != nil {
			return []byte(nil), err
		}

		conv.Decrypt(clear, cipher)

		plain = append(plain, clear[:8]...)
	}

	return plain, nil
}
Exemple #22
0
func ReadFile(name string) (b []byte, e os.Error) {
	var (
		raw  []byte
		err  os.Error
		file *os.File
		dir  *os.Dir
	)

	file, err = os.Open(name, os.O_RDONLY, 0)
	if err != nil {
		return raw, err
	}

	dir, err = file.Stat()
	if err != nil {
		return raw, err
	}

	var size uint64 = dir.Size
	raw = make([]byte, size)
	_, err = file.Read(raw)
	if err != nil {
		return raw, err
	}

	return raw, err
}
Exemple #23
0
func (storage *Storage) ReadMessage(file *os.File) *IMMessage {
	var size int32
	err := binary.Read(file, binary.BigEndian, &size)
	if err != nil {
		return nil
	}
	if size < 16 {
		return nil
	}
	var sender int64
	var receiver int64
	err = binary.Read(file, binary.BigEndian, &sender)
	if err != nil {
		return nil
	}

	err = binary.Read(file, binary.BigEndian, &receiver)
	if err != nil {
		return nil
	}

	buf := make([]byte, size-16)
	n, err := file.Read(buf)
	if err != nil || n != int(size-16) {
		return nil
	}
	return &IMMessage{sender, receiver, string(buf)}
}
Exemple #24
0
// returns string property prop
func (proc *SProcess) GetProperty(prop string) string {
	var (
		file *os.File
		err  error
	)

	// file exists
	if proc.files[prop] != nil {
		file = proc.files[prop]
		file.Seek(0, 0)

		// doesn't exist; create
	} else {
		file, err = os.Create("/system/process/" + strconv.Itoa(proc.pid) + "/" + prop)
		file.Chmod(0755)
	}

	// read up to 1024 bytes
	b := make([]byte, 1024)
	_, err = file.Read(b)

	// an error occured, and it was not an EOF
	if err != nil && err != io.EOF {
		return "(undefined)"
	}

	// file was more than 1M
	if err != io.EOF {
		return "(maxed out)"
	}

	return string(b)
}
Exemple #25
0
// GetPass reads password from a TTY with no echo.
func GetPass(prompt string, f *os.File, pbuf []byte) ([]byte, error) {
	t, err := Attr(f)
	if err != nil {
		return nil, err
	}
	defer t.Set(f)
	noecho := t
	noecho.Lflag = noecho.Lflag &^ ECHO
	if err := noecho.Set(f); err != nil {
		return nil, err
	}
	b := make([]byte, 1, 1)
	i := 0
	if _, err := f.Write([]byte(prompt)); err != nil {
		return nil, err
	}
	for ; i < len(pbuf); i++ {
		if _, err := f.Read(b); err != nil {
			b[0] = 0
			clearbuf(pbuf[:i+1])
		}
		if b[0] == '\n' || b[0] == '\r' {
			return pbuf[:i], nil
		}
		pbuf[i] = b[0]
		b[0] = 0
	}
	clearbuf(pbuf[:i+1])
	return nil, errors.New("ran out of bufferspace")
}
Exemple #26
0
func (a *analogPin) analogRead() int {
	var err error
	var fi *os.File

	ocp, err := filepath.Glob(Ocp)
	if err != nil {
		panic(err)
	}

	helper, err := filepath.Glob(fmt.Sprintf("%v/helper.*", ocp[0]))
	if err != nil {
		panic(err)
	}

	fi, err = os.Open(fmt.Sprintf("%v/%v", helper[0], a.pinNum))
	if err != nil {
		panic(err)
	}

	var buf = make([]byte, 1024)
	fi.Read(buf)
	fi.Close()

	i, _ := strconv.Atoi(strings.Split(string(buf), "\n")[0])
	return i
}
Exemple #27
0
func MakeRedirect(base string) (handler func(ctx *web.Context, val string)) {
	handler = func(ctx *web.Context, val string) {
		var fin *os.File
		var err os.Error
		fin, err = os.Open(path.Join(base, val), os.O_RDONLY, 0)
		if err != nil {
			ctx.WriteString(err.String())
			return
		}
		buf := make([]byte, 1024)
		for {
			var n int
			n, err = fin.Read(buf)
			if err != nil {
				ctx.WriteString(err.String())
				return
			}
			if n == 0 || err != nil {
				break
			}
			ctx.Write(buf[0:n])
		}
		fin.Close()
	}
	return
}
Exemple #28
0
func dataLookup(fh *os.File, offset int64) []byte {
	_, err := fh.Seek(offset, os.SEEK_SET)
	if err != nil {
		log.Fatal(err)
	}

	buffer := make([]byte, BUFFSIZE) // initial size of the buffer is 3kb
	line := make([]byte, 0, BUFFSIZE)
	prevLen := 0
	for {
		prevLen = len(line)
		n, err := fh.Read(buffer) // we read the next 3kb (or less)
		if err != nil && err != io.EOF {
			log.Fatal(err)
		}
		line = append(line, buffer[:]...)
		until := bytes.IndexByte(buffer, '\n')
		if until > 0 { // We have a full line
			return line[:prevLen+until]
		}
		if err == io.EOF || n < BUFFSIZE {
			return line
		}
	}
	log.Fatal("We can't be here")
	return nil
}
Exemple #29
0
func main() {
	filename := flag.String("s", "./log", "log file")
	flag.Parse()
	filename1 := "./1.log"
	filename2 := "./2.log"
	filename3 := "./3.log"
	filename4 := "./4.log"

	var (
		fd  *os.File
		fds [4]*os.File
		err error
	)

	fd, err = os.OpenFile(*filename, os.O_RDWR, 0660)
	fds[0], err = os.OpenFile(filename1, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	fds[1], err = os.OpenFile(filename2, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	fds[2], err = os.OpenFile(filename3, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	fds[3], err = os.OpenFile(filename4, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)

	buff := make([]byte, 2048)
	for i := 0; i < 4; i++ {
		_, err = fd.Read(buff)
		if err != nil {
			return
		}
		go func() {
			for i := 0; i < 4; i++ {
				go write_buff(fds[i], buff)
			}
		}()
	}
}
Exemple #30
0
func readDataHeader(file_in *os.File) uint32 {
	id := readString(file_in)
	chunk_size := readInt32(file_in)

	if id != "data" {
		fmt.Println("Unknown chunk id " + id)
		return 0
	}

	fmt.Println("              ID:", id)
	fmt.Println("      Chunk Size:", chunk_size)

	data := make([]uint8, chunk_size)
	file_in.Read(data)

	for i := 0; i < len(data); i++ {
		if i%8 == 0 {
			fmt.Print("\n  db")
		}

		d := fmt.Sprintf("0x%02x", int(data[i]))

		if i%8 == 0 {
			fmt.Print(" " + d)
		} else {
			fmt.Print(", " + d)
		}
	}

	fmt.Println("")

	return chunk_size
}