Exemplo n.º 1
0
func (a *ADAM4000) GetConfig() error {
	resp, err := a.comResF("$%02X2\r", a.address)
	if err != nil {
		return err
	}

	addr := make([]byte, 1)
	typecode := make([]byte, 1)
	baud := make([]byte, 1)
	data := make([]byte, 1)

	hex.Decode(addr, resp[1:3])
	hex.Decode(typecode, resp[3:5])
	hex.Decode(baud, resp[5:7])
	hex.Decode(data, resp[7:9])

	a.Address = addr[0]
	a.InputRange = InputRangeCode(typecode[0])
	a.BaudRate = BaudRateCode(baud[0])
	fmt.Printf("%X\n", data)
	a.Integration_time = data[0]&byte(1<<7) > 0
	a.Checksum = data[0]&byte(1<<6) > 0
	a.DataFormat = DataFormatCode(data[0] & byte(2))
	if a.Address != a.address {
		fmt.Printf("Warning: Configured address (%d) differs from connected address (%d), in init mode?\n", a.Address, a.address)
	}
	return nil
}
Exemplo n.º 2
0
func (o *Commit) SetBytes(b []byte) (err error) {
	o.Content = b
	lines := bytes.Split(b, []byte{'\n'})
	for i := range lines {
		if len(lines[i]) > 0 {
			split := bytes.SplitN(lines[i], []byte{' '}, 2)
			switch string(split[0]) {
			case "tree":
				o.Tree = make([]byte, 20)
				_, err = hex.Decode(o.Tree, split[1])
			case "parent":
				h := make([]byte, 20)
				_, err = hex.Decode(h, split[1])
				if err == nil {
					o.Parents = append(o.Parents, h)
				}
			case "author":
				o.Author = string(split[1])
			case "committer":
				o.Committer = string(split[1])
			}
			if err != nil {
				return
			}
		} else {
			o.Message = string(bytes.Join(append(lines[i+1:]), []byte{'\n'}))
			break
		}
	}
	return
}
Exemplo n.º 3
0
func (c *Color) UnmarshalText(b []byte) (err error) {
	s := string(b)
	if s == "none" {
		c.RGBA.R = 0x00
		c.RGBA.G = 0x00
		c.RGBA.B = 0x00
		c.RGBA.A = 0x00
		return nil
	}
	var buf [4]byte
	switch len(b) {
	case 6:
		_, err = hex.Decode(buf[:3], b)
		buf[3] = 0xFF
	case 8:
		_, err = hex.Decode(buf[:], b)
	default:
		return fmt.Errorf("Color.UnmarshalText: expected a hexadecimal string in the form RRGGBB or RRGGBBAA, or \"none\" (not %q)", s)
	}
	if err != nil {
		return fmt.Errorf("Color.UnmarshalText: expected a hexadecimal string in the form RRGGBB or RRGGBBAA, or \"none\" (not %q)", s)
	}
	c.RGBA.R = buf[0]
	c.RGBA.G = buf[1]
	c.RGBA.B = buf[2]
	c.RGBA.A = buf[3]
	return nil
}
Exemplo n.º 4
0
func parseColor(colors []string) []dmx.Color {
	dmxcolors := make([]dmx.Color, 0, len(colors))
	for _, color := range colors {
		var data [1]byte
		_, err := hex.Decode(data[:], []byte(color[:2]))
		if err != nil {
			panic(err)
		}
		r := data[0]
		_, err = hex.Decode(data[:], []byte(color[2:4]))
		if err != nil {
			panic(err)
		}
		g := data[0]
		_, err = hex.Decode(data[:], []byte(color[4:6]))
		if err != nil {
			panic(err)
		}
		b := data[0]

		dmxcolors = append(dmxcolors, dmx.Color{r, g, b})
	}

	return dmxcolors
}
Exemplo n.º 5
0
func (d *UUID) byte_set(uuid []byte) (err error) {
	t_uuid := [16]byte{}
	t_d := bytes.Split(uuid, []byte{'-'})

	if len(t_d) != 5 {
		return errors.New("not a uuid : [" + string(uuid) + "]")
	}

	if len(t_d[0]) != 8 {
		return errors.New("not a uuid : [" + string(uuid) + "]")
	}
	_, err = hex.Decode(t_uuid[0:4], t_d[0])
	if err != nil {
		return
	}

	if len(t_d[1]) != 4 || len(t_d[2]) != 4 || len(t_d[3]) != 4 {
		return errors.New("not a uuid : [" + string(uuid) + "]")
	}
	_, err = hex.Decode(t_uuid[4:6], t_d[1])
	if err != nil {
		return
	}
	_, err = hex.Decode(t_uuid[6:8], t_d[2])
	if err != nil {
		return
	}
	_, err = hex.Decode(t_uuid[8:10], t_d[3])
	if err != nil {
		return
	}

	if len(t_d[4]) != 12 {
		return errors.New("not a uuid : [" + string(uuid) + "]")
	}
	_, err = hex.Decode(t_uuid[10:16], t_d[4])
	if err != nil {
		return
	}

	switch t_uuid[6] & 0xf0 {
	case UUIDv1, UUIDv2, UUIDv3, UUIDv4, UUIDv5:
	default:
		return errors.New("unknown version : [" + string(uuid) + "]")
	}

	switch {
	case (t_uuid[8] & 0x80) == UUID_NCS:
	case (t_uuid[8] & 0xc0) == UUID_RFC:
	case (t_uuid[8] & 0xe0) == UUID_MS:
	case (t_uuid[8] & 0xe0) == UUID_UNUSED:
	default:
		err = errors.New("unknown variant : [" + string(uuid) + "]")
		return
	}
	*d = UUID(t_uuid)

	return nil
}
Exemplo n.º 6
0
Arquivo: uuid.go Projeto: wallyqs/util
// Converts a string representation of a UUID into a UUID object.
func FromString(s string) (u UUID, e error) {
	if len(s) != UUIDStringLen {
		return nil, &BadUUIDStringError{"length is not 36 bytes: " + s}
	}

	// Make enough space for the storage.
	u = make([]byte, UUIDByteLen)
	s_byte := []byte(s)

	var i int
	var err error

	i, err = hex.Decode(u[0:4], s_byte[0:8])
	if err != nil || i != 4 {
		return nil, &BadUUIDStringError{"Invalid first component: " + s}
	}

	if s_byte[8] != '-' {
		return nil, &BadUUIDStringError{"Position 8 is not a dash: " + s}
	}

	i, err = hex.Decode(u[4:6], s_byte[9:13])
	if err != nil || i != 2 {
		return nil, &BadUUIDStringError{"Invalid second component: " + s}
	}

	if s_byte[13] != '-' {
		return nil, &BadUUIDStringError{"Position 13 is not a dash: " + s}
	}

	i, err = hex.Decode(u[6:8], s_byte[14:18])
	if err != nil || i != 2 {
		return nil, &BadUUIDStringError{"Invalid third component: " + s}
	}

	if s_byte[18] != '-' {
		return nil, &BadUUIDStringError{"Position 18 is not a dash: " + s}
	}

	i, err = hex.Decode(u[8:10], s_byte[19:23])
	if err != nil || i != 2 {
		return nil, &BadUUIDStringError{"Invalid fourth component: " + s}
	}

	if s_byte[23] != '-' {
		return nil, &BadUUIDStringError{"Position 23 is not a dash: " + s}
	}

	i, err = hex.Decode(u[10:16], s_byte[24:36])
	if err != nil || i != 6 {
		return nil, &BadUUIDStringError{"Invalid fifth component: " + s}
	}

	if u[8]&0xc0 != 0x80 {
		return nil, &BadUUIDStringError{"Reserved bits used: " + s}
	}

	return u, nil
}
// SetHex takes two hexidecimal strings and decodes them into the receiver.
func (p *Point) SetHex(x, y string) error {
	if len(x) != 64 || len(y) != 64 {
		return errors.New("invalid hex string length")
	}
	if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
		return err
	}
	_, err := hex.Decode(p.y[:], []byte(y))
	return err
}
Exemplo n.º 8
0
// returns true if the sha256 hex password hash (of $name|$pass)
// stored at $basePath/$name/.password matches the user/pass
// arguements here.
func (a *authorizer) Authorized(name, pass string) bool {
	nameCleaned := cleanUser(name)
	// basically, if we detect any path manipulation stuff, bail
	if len(nameCleaned) == 0 || nameCleaned != name || strings.Index(nameCleaned, "/") != -1 {
		return false
	}

	passwordPath := path.Join(a.basePath, ".auth", nameCleaned)
	expectedHashHex, err := ioutil.ReadFile(passwordPath)
	if err != nil {
		log.Print("reading password file failed: ", err)
		return false
	}
	expectedHash := make([]byte, sha256.Size)
	_, err = hex.Decode(expectedHash, expectedHashHex)
	if err != nil {
		log.Printf("%s: hex.Decode: %s\n", passwordPath, err)
		return false
	}

	// hash the user supplied password
	inputHash := sha256.New()
	inputHash.Write([]byte(nameCleaned))
	inputHash.Write([]byte("|"))
	inputHash.Write([]byte(pass))

	// and check if it matches the one on disk
	return subtle.ConstantTimeCompare(expectedHash, inputHash.Sum(nil)) == 1
}
Exemplo n.º 9
0
func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
	challenge := make([]byte, len(data)/2)
	_, err := hex.Decode(challenge, data)
	if err != nil {
		return nil, AuthError
	}
	b := bytes.Split(challenge, []byte{' '})
	if len(b) != 3 {
		return nil, AuthError
	}
	context := b[0]
	id := b[1]
	svchallenge := b[2]
	cookie := a.getCookie(context, id)
	if cookie == nil {
		return nil, AuthError
	}
	clchallenge := a.generateChallenge()
	if clchallenge == nil {
		return nil, AuthError
	}
	hash := sha1.New()
	hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
	hexhash := make([]byte, 2*hash.Size())
	hex.Encode(hexhash, hash.Sum(nil))
	data = append(clchallenge, ' ')
	data = append(data, hexhash...)
	resp := make([]byte, 2*len(data))
	hex.Encode(resp, data)
	return resp, AuthOk
}
Exemplo n.º 10
0
//NewSimpleSessionManager returns an instance of seven5.SessionManager.
//This keeps the sessions in memory, not on disk or database but does try to
//insure that sessions are stable across runs by encrypting the session ids
//with a key only the session manager knows. The key must be supplied in
//the environment variable SERVER_SESSION_KEY or this function panics. That
//key should be a 32 character hex string (see key2hex).  If you pass nil
//as your generator, we are assuming that you will explicitly connect each
//user session via a call to Assign.
func NewSimpleSessionManager(g Generator) *SimpleSessionManager {
	if os.Getenv("SERVER_SESSION_KEY") == "" {
		log.Fatalf("unable to find environment variable SERVER_SESSION_KEY")
	}
	keyRaw := strings.TrimSpace(os.Getenv("SERVER_SESSION_KEY"))
	if len(keyRaw) != aes.BlockSize*2 {
		log.Fatalf("expected SERVER_SESSION_KEY length to be %d, but was %d", aes.BlockSize*2, len(keyRaw))
	}
	buf := make([]byte, aes.BlockSize)
	l, err := hex.Decode(buf, []byte(keyRaw))
	if err != nil {
		log.Fatalf("Unable to decode SERVER_SESSION_KEY, maybe it's not in hex? %v", err)
	}
	if l != aes.BlockSize {
		log.Fatalf("expected SERVER_SESSION_KEY decoded length to be %d, but was %d", aes.BlockSize, l)
	}
	key := buf[0:l]

	result := &SimpleSessionManager{
		out:       make(chan *sessionPacket),
		generator: g,
	}
	go handleSessionChecks(result.out, key)
	return result
}
Exemplo n.º 11
0
func copyBinary(sourceName, targetName, sourceDir, targetDir string) error {
	source := filepath.Join(sourceDir, sourceName)
	dest := filepath.Join(targetDir, targetName)
	if _, err := os.Stat(source); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("missing file %s", source)
		}
		return err
	}
	if err := CopyFile(source, dest, 0755); err != nil {
		return err
	}
	if b, err := ioutil.ReadFile(source + ".sha256"); err == nil {
		if i := bytes.IndexRune(b, ' '); i > 0 {
			b = b[:i]
		}
		expectedHash := make([]byte, hex.DecodedLen(len(b)))
		if _, err := hex.Decode(expectedHash, b); err != nil {
			return err
		}
		if err := hashCheck(dest, expectedHash, sha256.New()); err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 12
0
func DecodePrivateKeyString(privateKeyString string) [32]byte {
	var privateKey [32]byte
	_, err := hex.Decode(privateKey[:], []byte(privateKeyString))
	checkFatal(err)

	return privateKey
}
Exemplo n.º 13
0
// ParseString converts an UUID in string form to object.
func ParseString(str string) (*UUID, error) {
	text := []byte(str)
	if len(text) < 32 {
		return nil, errors.New("Invalid UUID: ", str)
	}

	uuid := new(UUID)
	b := uuid.Bytes()

	for _, byteGroup := range byteGroups {
		if text[0] == '-' {
			text = text[1:]
		}

		_, err := hex.Decode(b[:byteGroup/2], text[:byteGroup])

		if err != nil {
			return nil, err
		}

		text = text[byteGroup:]
		b = b[byteGroup/2:]
	}

	return uuid, nil
}
Exemplo n.º 14
0
// TODO: leverage a full functional UUID library
func UUIDToID(uuid string) (v ID, err error) {
	text := []byte(uuid)
	if len(text) < 32 {
		err = log.Error("uuid: invalid UUID string: %s", text)
		return
	}

	b := v[:]

	for _, byteGroup := range byteGroups {
		if text[0] == '-' {
			text = text[1:]
		}

		_, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])

		if err != nil {
			return
		}

		text = text[byteGroup:]
		b = b[byteGroup/2:]
	}

	return
}
Exemplo n.º 15
0
// Sign the given hex-endcoded hash checksum and return a Signature
// @@TODO Remove this -- undeeded
func (pk PrivateKey) SignSHA256(hexbytes []byte) (Signature, error) {
	if hex.DecodedLen(len(hexbytes)) != sha256.Size {
		return nil, ErrPrivateKeySHA256
	}

	// Decode hex bytes into raw bytes
	decodedBytes := make([]byte, hex.DecodedLen(len(hexbytes)))
	_, err := hex.Decode(decodedBytes, hexbytes)
	if err != nil {
		return nil, errors.Wrap(err, ErrPrivateKeySHA256)
	}

	// Get the rsa cryptokey for signing
	cryptoKey, err := pk.GetCryptoKey()
	if err != nil {
		return nil, errors.Wrap(err, ErrPrivatKeySign)
	}

	// Compute the signature and return the results
	rawSignature, err := rsa.SignPKCS1v15(rand.Reader, cryptoKey, crypto.SHA256, decodedBytes)
	if err != nil {
		return nil, errors.Wrap(err, ErrPrivatKeySign)
	}
	return Signature(rawSignature), nil
}
Exemplo n.º 16
0
func NewMemoryDB(path string) (*MemoryDB, error) {
	mem := NewEmptyMemoryDB()
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	r, err := gzip.NewReader(f)
	if err != nil {
		return nil, err
	}
	defer r.Close()
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		parts := strings.Split(scanner.Text(), ":")
		var nodeid data.Hash256
		if _, err := hex.Decode(nodeid[:], []byte(parts[0])); err != nil {
			return nil, err
		}
		value, err := hex.DecodeString(parts[1])
		if err != nil {
			return nil, err
		}
		node, err := data.ReadPrefix(bytes.NewReader(value), nodeid)
		if err != nil {
			return nil, err
		}
		mem.nodes[nodeid] = node
	}
	if scanner.Err() != nil {
		return nil, scanner.Err()
	}
	return mem, nil
}
Exemplo n.º 17
0
func startTCP(cb func([]byte)) net.Listener {
	listener, err := net.Listen("tcp", ":0")

	if err != nil {
		log.Fatal("Can't start:", err)
	}

	go func() {
		for {
			conn, _ := listener.Accept()
			defer conn.Close()

			go func() {
				reader := bufio.NewReader(conn)
				scanner := bufio.NewScanner(reader)

				for scanner.Scan() {
					encodedPayload := scanner.Bytes()
					// Hex encoding always 2x number of bytes
					decoded := make([]byte, len(encodedPayload)/2)
					hex.Decode(decoded, encodedPayload)
					cb(decoded)
				}
			}()
		}
	}()

	return listener
}
Exemplo n.º 18
0
//given a blob of text to decode, checks a few things and returns either
//the originally given unique id and true or "" and false.
func decryptSessionId(encryptedHex string, block cipher.Block) (string, bool) {
	ciphertext := make([]byte, len(encryptedHex)/2)
	l, err := hex.Decode(ciphertext, []byte(encryptedHex))
	if err != nil {
		log.Printf("unable to decode the hex bytes of session id (%s,%d): %v", encryptedHex, len(encryptedHex), err)
		return "", false
	}
	iv := ciphertext[:aes.BlockSize]
	stream := cipher.NewCTR(block, iv)

	cleartext := make([]byte, l-len(iv))
	stream.XORKeyStream(cleartext, ciphertext[aes.BlockSize:])
	s := string(cleartext)
	if !strings.HasPrefix(s, s5CookiePrefix) {
		log.Printf("No cookie prefix found, probably keys changed")
		return "", false
	}
	s = strings.TrimPrefix(s, s5CookiePrefix+":")
	parts := strings.Split(s, ",")
	if len(parts) != 2 {
		log.Printf("Failed to understand parts of session id: %s", s)
		return "", false
	}
	t, err := strconv.ParseInt(parts[1], 10, 64)
	if err != nil {
		log.Printf("Could not understand expiration time in session id: %s", s)
		return "", false
	}
	expires := time.Unix(t, 0)
	if expires.Before(time.Now()) {
		return "", false
	}
	return parts[0], true
}
Exemplo n.º 19
0
// Parse address from raw json data
func (a *Address) UnmarshalJSON(data []byte) error {
	if len(data) > 2 && data[0] == '"' && data[len(data)-1] == '"' {
		data = data[1 : len(data)-1]
	}

	if len(data) > 2 && data[0] == '0' && data[1] == 'x' {
		data = data[2:]
	}

	if len(data) != 2*AddressLength {
		return fmt.Errorf("Invalid address length, expected %d got %d bytes", 2*AddressLength, len(data))
	}

	n, err := hex.Decode(a[:], data)
	if err != nil {
		return err
	}

	if n != AddressLength {
		return fmt.Errorf("Invalid address")
	}

	a.Set(HexToAddress(string(data)))
	return nil
}
Exemplo n.º 20
0
Arquivo: mem.go Projeto: aryaya/ripple
func readInput(mem *MemoryDB, path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()
	r, err := gzip.NewReader(f)
	if err != nil {
		return err
	}
	defer r.Close()
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		parts := strings.Split(scanner.Text(), ":")
		var nodeid data.Hash256
		if _, err := hex.Decode(nodeid[:], []byte(parts[0])); err != nil {
			return err
		}
		value, err := hex.DecodeString(parts[1])
		if err != nil {
			return err
		}
		node, err := data.ReadPrefix(bytes.NewReader(value), nodeid)
		if err != nil {
			return err
		}
		mem.nodes[nodeid] = node
	}
	return scanner.Err()
}
Exemplo n.º 21
0
func main() {
	var err error

	argParse()
	codec := collatejson.NewCodec(100)
	out := make([]byte, 0, len(options.inp)*3+collatejson.MinBufferSize)
	if options.encode {
		out, err = codec.Encode([]byte(options.inp), out)
		if err != nil {
			log.Fatal(err)
		}
		hexout := make([]byte, len(out)*5)
		n := hex.Encode(hexout, out)
		fmt.Printf("in : %q\n", options.inp)
		fmt.Printf("out: %q\n", string(out))
		fmt.Printf("hex: %q\n", string(hexout[:n]))

	} else if options.decode {
		inpbs := make([]byte, len(options.inp)*5)
		n, err := hex.Decode(inpbs, []byte(options.inp))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(n, inpbs[:n])
		out, err = codec.Decode([]byte(inpbs[:n]), out)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("in : %q\n", options.inp)
		fmt.Printf("out: %q\n", string(out))
	}
}
Exemplo n.º 22
0
// Converting from our Magnet type to URL string.
func TestMagnetString(t *testing.T) {
	hex.Decode(exampleMagnet.InfoHash[:], []byte("51340689c960f0778a4387aef9b4b52fd08390cd"))
	s := exampleMagnet.String()
	if s != exampleMagnetURI {
		t.Fatalf("\nexpected:\n\t%q\nactual\n\t%q", exampleMagnetURI, s)
	}
}
Exemplo n.º 23
0
Arquivo: hash.go Projeto: decred/dcrd
// Decode decodes the byte-reversed hexadecimal string encoding of a Hash to a
// destination.
func Decode(dst *Hash, src string) error {
	// Return error if hash string is too long.
	if len(src) > MaxHashStringSize {
		return ErrHashStrSize
	}

	// Hex decoder expects the hash to be a multiple of two.  When not, pad
	// with a leading zero.
	var srcBytes []byte
	if len(src)%2 == 0 {
		srcBytes = []byte(src)
	} else {
		srcBytes = make([]byte, 1+len(src))
		srcBytes[0] = '0'
		copy(srcBytes[1:], src)
	}

	// Hex decode the source bytes to a temporary destination.
	var reversedHash Hash
	_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)
	if err != nil {
		return err
	}

	// Reverse copy from the temporary hash to destination.  Because the
	// temporary was zeroed, the written result will be correctly padded.
	for i, b := range reversedHash[:HashSize/2] {
		dst[i], dst[HashSize-1-i] = reversedHash[HashSize-1-i], b
	}

	return nil
}
Exemplo n.º 24
0
func getShaFor(url string) ([]byte, error) {
	res, err := http.Get(url + ".sha1")
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP Status: %d", res.StatusCode)
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	b = bytes.TrimSpace(b)

	b = b[:40]

	s := make([]byte, hex.DecodedLen(len(b)))

	if _, err := hex.Decode(s, b); err != nil {
		return nil, err
	}

	return s, nil
}
Exemplo n.º 25
0
// Scan implements database/sql Scanner interface.
// It expectes EWKB with SRID 4326 (WGS 84).
func (p *PostGISPoint) Scan(value interface{}) error {
	if value == nil {
		*p = PostGISPoint{}
		return nil
	}

	v, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("pq_types: expected []byte, got %T (%v)", value, value)
	}

	ewkb := make([]byte, hex.DecodedLen(len(v)))
	n, err := hex.Decode(ewkb, v)
	if err != nil {
		return err
	}

	var ewkbP ewkbPoint
	err = binary.Read(bytes.NewReader(ewkb[:n]), binary.LittleEndian, &ewkbP)
	if err != nil {
		return err
	}

	if ewkbP.ByteOrder != 1 || ewkbP.WkbType != 0x20000001 || ewkbP.SRID != 4326 {
		return fmt.Errorf("pq_types: unexpected ewkb %#v", ewkbP)
	}
	*p = ewkbP.Point
	return nil
}
Exemplo n.º 26
0
// Keeps reading shallows until a flush-pkt is found
func decodeShallow(p *Decoder) decoderStateFn {
	if !bytes.HasPrefix(p.line, shallow) {
		p.error("malformed shallow prefix, found %q... instead", p.line[:len(shallow)])
		return nil
	}
	p.line = bytes.TrimPrefix(p.line, shallow)

	if len(p.line) != hashSize {
		p.error(fmt.Sprintf(
			"malformed shallow hash: wrong length, expected 40 bytes, read %d bytes",
			len(p.line)))
		return nil
	}

	text := p.line[:hashSize]
	var h plumbing.Hash
	if _, err := hex.Decode(h[:], text); err != nil {
		p.error("invalid hash text: %s", err)
		return nil
	}

	p.data.Shallows = append(p.data.Shallows, h)

	if ok := p.nextLine(); !ok {
		return nil
	}

	if len(p.line) == 0 {
		return nil // succesfull parse of the advertised-refs message
	}

	return decodeShallow
}
Exemplo n.º 27
0
// UnmarshalText implements the encoding.TextUnmarshaler interface.
// Following formats are supported:
// "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
func (u *UUID) UnmarshalText(text []byte) (err error) {
	if len(text) < 32 {
		err = fmt.Errorf("uuid: invalid UUID string: %s", text)
		return
	}

	if bytes.Equal(text[:9], urnPrefix) {
		text = text[9:]
	} else if text[0] == '{' {
		text = text[1:]
	}

	b := u[:]

	for _, byteGroup := range byteGroups {
		if text[0] == '-' {
			text = text[1:]
		}

		_, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])

		if err != nil {
			return
		}

		text = text[byteGroup:]
		b = b[byteGroup/2:]
	}

	return
}
Exemplo n.º 28
0
func New(buf string) (*UATMsg, error) {
	ret := new(UATMsg)

	buf = strings.Trim(buf, "\r\n") // Remove newlines.
	x := strings.Split(buf, ";")    // We want to discard everything before the first ';'.

	s := x[0]

	// Only want "long" uplink messages.
	if (len(s)-1)%2 != 0 || (len(s)-1)/2 != UPLINK_FRAME_DATA_BYTES {
		return ret, errors.New(fmt.Sprintf("New UATMsg: short read (%d).", len(s)))
	}

	if s[0] != '+' { // Only want + ("Uplink") messages currently. - (Downlink) or messages that start with other are discarded.
		return ret, errors.New("New UATMsg: expecting uplink frames.")
	}

	s = s[1:]

	// Convert the hex string into a byte array.
	frame := make([]byte, UPLINK_FRAME_DATA_BYTES)
	hex.Decode(frame, []byte(s))
	ret.msg = frame

	return ret, nil
}
Exemplo n.º 29
0
func parseInput(buf string) []byte {
	buf = strings.Trim(buf, "\r\n") // Remove newlines.
	x := strings.Split(buf, ";")    // We want to discard everything before the first ';'.
	if len(x) == 0 {
		return nil
	}
	s := x[0]
	if len(s) == 0 {
		return nil
	}
	if s[0] != '+' {
		return nil // Only want + ("Uplink") messages currently. - (Downlink) or messages that start with other are discarded.
	}

	s = s[1:]

	if len(s)%2 != 0 { // Bad format.
		return nil
	}

	if len(s)/2 != UPLINK_FRAME_DATA_BYTES {
		fmt.Printf("UPLINK_FRAME_DATA_BYTES=%d, len(s)=%d\n", UPLINK_FRAME_DATA_BYTES, len(s))
		//		panic("Error")
		return nil
	}

	// Now, begin converting the string into a byte array.
	frame := make([]byte, UPLINK_FRAME_DATA_BYTES)
	hex.Decode(frame, []byte(s))

	return frame
}
Exemplo n.º 30
0
func (m *Middleware) read(from io.Reader) {
	reader := bufio.NewReader(from)
	var line []byte
	var e error

	for {
		if line, e = reader.ReadBytes('\n'); e != nil {
			if e == io.EOF {
				continue
			} else {
				break
			}
		}

		buf := make([]byte, len(line)/2)
		if _, err := hex.Decode(buf, line[:len(line)-1]); err != nil {
			fmt.Fprintln(os.Stderr, "Failed to decode input payload", err, len(line))
		}

		if Settings.debug {
			Debug("[MIDDLEWARE-MASTER] Received:", string(buf))
		}

		m.data <- buf
	}

	return
}