Beispiel #1
1
func (d *UDPClient) Start(uri *url.URL) error {
	d.url = uri
	d.stop = make(chan struct{})

	params := uri.Query()
	// The address must not have a port, as otherwise both announce and lookup
	// sockets would try to bind to the same port.
	addr, err := net.ResolveUDPAddr(d.url.Scheme, params.Get("listenaddress")+":0")
	if err != nil {
		return err
	}
	d.listenAddress = addr

	broadcastSeconds, err := strconv.ParseUint(params.Get("broadcast"), 0, 0)
	if err != nil {
		d.globalBroadcastInterval = DefaultGlobalBroadcastInterval
	} else {
		d.globalBroadcastInterval = time.Duration(broadcastSeconds) * time.Second
	}

	retrySeconds, err := strconv.ParseUint(params.Get("retry"), 0, 0)
	if err != nil {
		d.errorRetryInterval = DefaultErrorRetryInternval
	} else {
		d.errorRetryInterval = time.Duration(retrySeconds) * time.Second
	}

	d.wg.Add(1)
	go d.broadcast()
	return nil
}
Beispiel #2
0
// branchesBehindAhead returns the behind/ahead commit counts information for branch, against base branch.
func (r *Repository) branchesBehindAhead(branch, base string) (*vcs.BehindAhead, error) {
	if err := checkSpecArgSafety(branch); err != nil {
		return nil, err
	}
	if err := checkSpecArgSafety(base); err != nil {
		return nil, err
	}

	cmd := exec.Command("git", "rev-list", "--count", "--left-right", fmt.Sprintf("refs/heads/%s...refs/heads/%s", base, branch))
	cmd.Dir = r.Dir
	out, err := cmd.Output()
	if err != nil {
		return nil, err
	}
	behindAhead := strings.Split(strings.TrimSuffix(string(out), "\n"), "\t")
	b, err := strconv.ParseUint(behindAhead[0], 10, 0)
	if err != nil {
		return nil, err
	}
	a, err := strconv.ParseUint(behindAhead[1], 10, 0)
	if err != nil {
		return nil, err
	}
	return &vcs.BehindAhead{Behind: uint32(b), Ahead: uint32(a)}, nil
}
Beispiel #3
0
func parseCPUStat(usage, statContents string) (stat garden.ContainerCPUStat) {
	cpuUsage, err := strconv.ParseUint(strings.Trim(usage, "\n"), 10, 0)
	if err != nil {
		return
	}

	stat.Usage = cpuUsage

	scanner := bufio.NewScanner(strings.NewReader(statContents))

	scanner.Split(bufio.ScanWords)

	for scanner.Scan() {
		field := scanner.Text()

		if !scanner.Scan() {
			break
		}

		value, err := strconv.ParseUint(scanner.Text(), 10, 0)
		if err != nil {
			continue
		}

		switch field {
		case "user":
			stat.User = value
		case "system":
			stat.System = value
		}
	}

	return
}
Beispiel #4
0
func (ctl *controller) getActivity(c web.C, w http.ResponseWriter, r *http.Request) {
	teamID, _ := c.Env["team_id"].(string)

	p := api.ActivityQueryParams{
		AppID:      r.URL.Query().Get("app"),
		GroupID:    r.URL.Query().Get("group"),
		ChannelID:  r.URL.Query().Get("channel"),
		InstanceID: r.URL.Query().Get("instance"),
		Version:    r.URL.Query().Get("version"),
	}
	p.Severity, _ = strconv.Atoi(r.URL.Query().Get("severity"))
	p.Start, _ = time.Parse(time.RFC3339, r.URL.Query().Get("start"))
	p.End, _ = time.Parse(time.RFC3339, r.URL.Query().Get("end"))
	p.Page, _ = strconv.ParseUint(r.URL.Query().Get("page"), 10, 64)
	p.PerPage, _ = strconv.ParseUint(r.URL.Query().Get("perpage"), 10, 64)

	activityEntriesJSON, err := ctl.api.GetActivityJSON(teamID, p)
	switch err {
	case nil:
		w.Write(activityEntriesJSON)
	case sql.ErrNoRows:
		w.Write([]byte(`[]`))
	default:
		logger.Error("getActivity", "error", err, "teamID", teamID, "p", p)
		http.Error(w, http.StatusText(400), 400)
	}
}
Beispiel #5
0
func (p *Part) parseYencHeader(line string) {
	pairs := p.getKeyValuePairs(line)
	for key, value := range pairs {
		switch key {
		case "part":
			if i, e := strconv.ParseUint(value, 10, 32); e == nil {
				p.Part = uint32(i)
			}
		case "total":
			if i, e := strconv.ParseUint(value, 10, 32); e == nil {
				p.Total = uint32(i)
			}
		case "line":
			if i, e := strconv.ParseUint(value, 10, 32); e == nil {
				p.LineSize = uint32(i)
			}
		case "size":
			if i, e := strconv.ParseUint(value, 10, 32); e == nil {
				p.TotalSize = uint32(i)
			}
		case "name":
			p.Name = value
		}
	}
}
Beispiel #6
0
// runAs takes a user id as a string and looks up the user, and sets the command
// to execute as that user.
func (e *UniversalExecutor) runAs(userid string) error {
	u, err := user.Lookup(userid)
	if err != nil {
		return fmt.Errorf("Failed to identify user %v: %v", userid, err)
	}

	// Convert the uid and gid
	uid, err := strconv.ParseUint(u.Uid, 10, 32)
	if err != nil {
		return fmt.Errorf("Unable to convert userid to uint32: %s", err)
	}
	gid, err := strconv.ParseUint(u.Gid, 10, 32)
	if err != nil {
		return fmt.Errorf("Unable to convert groupid to uint32: %s", err)
	}

	// Set the command to run as that user and group.
	if e.cmd.SysProcAttr == nil {
		e.cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	if e.cmd.SysProcAttr.Credential == nil {
		e.cmd.SysProcAttr.Credential = &syscall.Credential{}
	}
	e.cmd.SysProcAttr.Credential.Uid = uint32(uid)
	e.cmd.SysProcAttr.Credential.Gid = uint32(gid)

	return nil
}
Beispiel #7
0
func (h *HTTPHashFilters) Set(value string) error {
	valArr := strings.SplitN(value, ":", 2)
	if len(valArr) < 2 {
		return errors.New("need both header and value, colon-delimited (ex. user_id:50%)")
	}

	f := hashFilter{name: []byte(valArr[0])}

	val := strings.TrimSpace(valArr[1])

	if strings.Contains(val, "%") {
		p, _ := strconv.ParseInt(val[:len(val)-1], 0, 0)
		f.percent = uint32(p)
	} else if strings.Contains(val, "/") {
		// DEPRECATED format
		var num, den uint64

		fracArr := strings.Split(val, "/")
		num, _ = strconv.ParseUint(fracArr[0], 10, 64)
		den, _ = strconv.ParseUint(fracArr[1], 10, 64)

		f.percent = uint32((float64(num) / float64(den)) * 100)
	} else {
		return errors.New("Value should be percent and contain '%'")
	}

	*h = append(*h, f)

	return nil
}
Beispiel #8
0
func (s *GeneralStats) Set(key string, value []byte) error {
	reflectValue := reflect.ValueOf(s).Elem()
	reflectField := reflectValue.FieldByName(snake2Camel(key))
	switch reflectField.Kind() {
	case reflect.Uint32:
		i, err := strconv.ParseUint(string(value), 10, 32)
		if err != nil {
			return err
		}
		reflectField.SetUint(i)
	case reflect.Uint64:
		i, err := strconv.ParseUint(string(value), 10, 64)
		if err != nil {
			return err
		}
		reflectField.SetUint(i)
	case reflect.Float64:
		i, err := strconv.ParseFloat(string(value), 64)
		if err != nil {
			return err
		}
		reflectField.SetFloat(i)
	case reflect.Bool:
		i, err := strconv.ParseBool(string(value))
		if err != nil {
			return err
		}
		reflectField.SetBool(i)
	case reflect.String:
		reflectField.SetString(string(value))
	default:
		return ErrInvalidStatsKey
	}
	return nil
}
Beispiel #9
0
// Return the UID and GID of this process.
func MyUserAndGroup() (uid uint32, gid uint32, err error) {
	// Ask for the current user.
	user, err := user.Current()
	if err != nil {
		panic(err)
	}

	// Parse UID.
	uid64, err := strconv.ParseUint(user.Uid, 10, 32)
	if err != nil {
		err = fmt.Errorf("Parsing UID (%s): %v", user.Uid, err)
		return
	}

	// Parse GID.
	gid64, err := strconv.ParseUint(user.Gid, 10, 32)
	if err != nil {
		err = fmt.Errorf("Parsing GID (%s): %v", user.Gid, err)
		return
	}

	uid = uint32(uid64)
	gid = uint32(gid64)

	return
}
Beispiel #10
0
func (d *decoder) parseTrailer(line string) error {
	// split on space for headers
	parts := strings.Split(line, " ")
	for i, _ := range parts {
		kv := strings.Split(strings.TrimSpace(parts[i]), "=")
		if len(kv) < 2 {
			continue
		}
		switch kv[0] {
		case "size":
			d.part.Size, _ = strconv.ParseInt(kv[1], 10, 64)
		case "pcrc32":
			if crc64, err := strconv.ParseUint(kv[1], 16, 64); err == nil {
				d.part.crc32 = uint32(crc64)
			}
		case "crc32":
			if crc64, err := strconv.ParseUint(kv[1], 16, 64); err == nil {
				d.crc32 = uint32(crc64)
			}
		case "part":
			partNum, _ := strconv.Atoi(kv[1])
			if partNum != d.part.Number {
				return fmt.Errorf("yenc: =yend header out of order expected part %d got %d", d.part.Number, partNum)
			}
		}
	}
	return nil
}
Beispiel #11
0
// We don't support multi source replication, so the mariadb gtid set may have only domain-server-sequence
func ParseMariadbGTIDSet(str string) (GTIDSet, error) {
	if len(str) == 0 {
		return MariadbGTID{0, 0, 0}, nil
	}

	seps := strings.Split(str, "-")

	var gtid MariadbGTID

	if len(seps) != 3 {
		return gtid, errors.Errorf("invalid Mariadb GTID %v, must domain-server-sequence", str)
	}

	domainID, err := strconv.ParseUint(seps[0], 10, 32)
	if err != nil {
		return gtid, errors.Errorf("invalid MariaDB GTID Domain ID (%v): %v", seps[0], err)
	}

	serverID, err := strconv.ParseUint(seps[1], 10, 32)
	if err != nil {
		return gtid, errors.Errorf("invalid MariaDB GTID Server ID (%v): %v", seps[1], err)
	}

	sequenceID, err := strconv.ParseUint(seps[2], 10, 64)
	if err != nil {
		return gtid, errors.Errorf("invalid MariaDB GTID Sequence number (%v): %v", seps[2], err)
	}

	return MariadbGTID{
		DomainID:       uint32(domainID),
		ServerID:       uint32(serverID),
		SequenceNumber: sequenceID}, nil
}
Beispiel #12
0
func stringValue(s string, fieldVal interface{}) error {
	var err error

	switch v := fieldVal.(type) {
	case *bool:
		*v, err = strconv.ParseBool(s)
	case *string:
		*v = s
	case *[]byte:
		*v = []byte(s)
	case *int:
		*v, err = strconv.Atoi(s)
	case *int64:
		*v, err = strconv.ParseInt(s, 10, 64)
	case *uint:
		var a uint64
		a, err = strconv.ParseUint(s, 10, 32)
		*v = uint(a)
	case *uint64:
		*v, err = strconv.ParseUint(s, 10, 64)
	case *float64:
		*v, err = strconv.ParseFloat(s, 64)
	case *time.Duration:
		*v, err = time.ParseDuration(s)
	default:
		return fmt.Errorf("unhandled parameter type %T", fieldVal)
	}

	return err
}
Beispiel #13
0
// if the raft algorithm making progress in leader, if not, the leader is isolated from cluster
func isValid(tr *http.Transport, ep string) bool {
	httpclient := http.Client{
		Transport: tr,
	}
	// we only need the header of response
	resp0, err := httpclient.Head(ep + "/v2/keys")
	if err != nil {
		return false
	}
	rt0, err1 := strconv.ParseUint(resp0.Header.Get("X-Raft-Term"), 10, 64)
	ri0, err2 := strconv.ParseUint(resp0.Header.Get("X-Raft-Index"), 10, 64)
	if err1 != nil || err2 != nil {
		return false
	}

	time.Sleep(time.Second)
	// we only need the header of response
	resp1, err := httpclient.Head(ep + "/v2/keys")
	if err != nil {
		return false
	}
	rt1, err1 := strconv.ParseUint(resp1.Header.Get("X-Raft-Term"), 10, 64)
	ri1, err2 := strconv.ParseUint(resp1.Header.Get("X-Raft-Index"), 10, 64)
	if err1 != nil || err2 != nil {
		return false
	}

	// raft algorithm doesn't make progress, leader is invalid
	if rt0 != rt1 || ri0 == ri1 {
		return false
	}
	return true
}
Beispiel #14
0
// parseMariadbGTID is registered as a GTID parser.
func parseMariadbGTID(s string) (GTID, error) {
	// Split into parts.
	parts := strings.Split(s, "-")
	if len(parts) != 3 {
		return nil, fmt.Errorf("invalid MariaDB GTID (%v): expecting Domain-Server-Sequence", s)
	}

	// Parse Domain ID.
	Domain, err := strconv.ParseUint(parts[0], 10, 32)
	if err != nil {
		return nil, fmt.Errorf("invalid MariaDB GTID Domain ID (%v): %v", parts[0], err)
	}

	// Parse Server ID.
	Server, err := strconv.ParseUint(parts[1], 10, 32)
	if err != nil {
		return nil, fmt.Errorf("invalid MariaDB GTID Server ID (%v): %v", parts[1], err)
	}

	// Parse Sequence number.
	Sequence, err := strconv.ParseUint(parts[2], 10, 64)
	if err != nil {
		return nil, fmt.Errorf("invalid MariaDB GTID Sequence number (%v): %v", parts[2], err)
	}

	return MariadbGTID{
		Domain:   uint32(Domain),
		Server:   uint32(Server),
		Sequence: Sequence,
	}, nil
}
func (p PlackPlugin) parseStats(body io.Reader) (map[string]interface{}, error) {
	stat := make(map[string]interface{})
	decoder := json.NewDecoder(body)

	var s PlackServerStatus
	err := decoder.Decode(&s)
	if err != nil {
		return nil, err
	}

	stat["busy_workers"], err = strconv.ParseFloat(s.BusyWorkers, 64)
	if err != nil {
		return nil, errors.New("cannot get values")
	}

	stat["idle_workers"], err = strconv.ParseFloat(s.IdleWorkers, 64)
	if err != nil {
		return nil, errors.New("cannot get values")
	}

	stat["requests"], err = strconv.ParseUint(s.TotalAccesses, 10, 64)
	if err != nil {
		return nil, errors.New("cannot get values")
	}

	stat["bytes_sent"], err = strconv.ParseUint(s.TotalKbytes, 10, 64)
	if err != nil {
		return nil, errors.New("cannot get values")
	}
	return stat, nil
}
Beispiel #16
0
func parseColor(rs, gs, bs string) (color uint32, err error) {
	var r, g, b uint64
	color = 0
	err = nil
	r, err = strconv.ParseUint(rs, 0, 32)
	if err != nil {
		return
	}
	g, gerror := strconv.ParseUint(gs, 0, 32)
	if gerror != nil {
		return
	}
	b, berror := strconv.ParseUint(bs, 0, 32)
	if berror != nil {
		return
	}

	color64 :=
		((r & 0xFF) << 16) |
			((g & 0xFF) << 8) |
			(b & 0xFF)

	color = uint32(color64)
	return
}
Beispiel #17
0
func (c *ChatService) onGetChatHistory(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
	log.Println("Get chat history...")
	groupId := p.ByName("id")

	queryParams := req.URL.Query()
	var offset uint = 0
	var limit uint = 20

	if o, err := strconv.ParseUint(queryParams.Get("offset"), 10, 32); err == nil {
		offset = uint(o)
	}

	if l, err := strconv.ParseUint(queryParams.Get("limit"), 10, 32); err == nil {
		limit = uint(l)
	}

	log.Println("Limit =", limit, "Offset =", offset)
	log, err := c.chatStore.GetMessagesFor(groupId, offset, limit)
	if err == nil {
		response := make(map[string]interface{})
		response["limit"] = limit
		response["offset"] = offset
		response["messages"] = log
		response["id"] = groupId
		json.NewEncoder(w).Encode(response)
	} else {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(ErrorMessage{
			Error: err.Error(),
		})
	}
}
Beispiel #18
0
//This function determines whether streaming is behind replication as it should be.
func (blp *Blp) slavePosBehindReplication() bool {
	repl, err := blp.globalState.getReplicationPosition()
	if err != nil {
		relog.Error(err.Error())
		panic(NewBinlogParseError(REPLICATION_ERROR, fmt.Sprintf("Error in obtaining current replication position %v", err)))
	}
	if repl.MasterFilename == blp.currentPosition.Position.MasterFilename {
		if blp.currentPosition.Position.MasterPosition <= repl.MasterPosition {
			return true
		}
	} else {
		replExt, err := strconv.ParseUint(strings.Split(repl.MasterFilename, ".")[1], 10, 64)
		if err != nil {
			relog.Error(err.Error())
			panic(NewBinlogParseError(CODE_ERROR, fmt.Sprintf("Error in extracting replication position %v", err)))
		}
		parseExt, err := strconv.ParseUint(strings.Split(blp.currentPosition.Position.MasterFilename, ".")[1], 10, 64)
		if err != nil {
			relog.Error(err.Error())
			panic(NewBinlogParseError(CODE_ERROR, fmt.Sprintf("Error in extracting replication position %v", err)))
		}
		if replExt >= parseExt {
			return true
		}
	}
	return false
}
Beispiel #19
0
// Returns user and kernel usage breakdown in nanoseconds.
func getCpuUsageBreakdown(path string) (uint64, uint64, error) {
	userModeUsage := uint64(0)
	kernelModeUsage := uint64(0)
	const (
		userField   = "user"
		systemField = "system"
	)

	// Expected format:
	// user <usage in ticks>
	// system <usage in ticks>
	data, err := ioutil.ReadFile(filepath.Join(path, cgroupCpuacctStat))
	if err != nil {
		return 0, 0, err
	}
	fields := strings.Fields(string(data))
	if len(fields) != 4 {
		return 0, 0, fmt.Errorf("failure - %s is expected to have 4 fields", filepath.Join(path, cgroupCpuacctStat))
	}
	if fields[0] != userField {
		return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[0], cgroupCpuacctStat, userField)
	}
	if fields[2] != systemField {
		return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[2], cgroupCpuacctStat, systemField)
	}
	if userModeUsage, err = strconv.ParseUint(fields[1], 10, 64); err != nil {
		return 0, 0, err
	}
	if kernelModeUsage, err = strconv.ParseUint(fields[3], 10, 64); err != nil {
		return 0, 0, err
	}

	return (userModeUsage * nanosecondsInSecond) / clockTicks, (kernelModeUsage * nanosecondsInSecond) / clockTicks, nil
}
Beispiel #20
0
// Check reports whether the given password and hashed key match
func Check(passwd, hash string) bool {

	if len(hash) < 36 {
		return false
	}

	if hash[:4] == AlgoDefault {
		N, _ := strconv.ParseUint(hash[4:5], 36, 32)
		r, _ := strconv.ParseUint(hash[5:6], 36, 32)
		p, _ := strconv.ParseUint(hash[6:7], 36, 32)
		salt, _ := b64Encoding.DecodeString(hash[7:27])

		key, _ := scrypt.Key([]byte(passwd), salt, 1<<N, int(r), int(p), 36)

		return hash[27:] == b64Encoding.EncodeToString(key)

	} else if hash[:4] == AlgoMd5 {

		h := md5.New()
		io.WriteString(h, passwd)

		return hash[4:] == fmt.Sprintf("%x", h.Sum(nil))
	}

	return false
}
Beispiel #21
0
// Color in HEX format: FAFAFA
func (g *Gummy) DrawText(text, textColor string, fontSize, xPosition, yPosition int) error {

	// Get black or white depending on the background
	if textColor == "" {
		c := (*g.Color).(color.RGBA)
		if blackWithBackground(float64(c.R), float64(c.G), float64(c.B)) {
			textColor = "000000"
		} else {
			textColor = "FFFFFF"
		}
	}

	fc := freetype.NewContext()
	fc.SetDst(g.Img)
	fc.SetFont(g.Font)
	fc.SetClip(g.Img.Bounds())

	// Color parsing
	cr, _ := strconv.ParseUint(string(textColor[:2]), 16, 64)
	cg, _ := strconv.ParseUint(string(textColor[2:4]), 16, 64)
	cb, _ := strconv.ParseUint(string(textColor[4:]), 16, 64)
	c := image.NewUniform(color.RGBA{R: uint8(cr), G: uint8(cg), B: uint8(cb), A: 255})

	fc.SetSrc(c)
	fc.SetFontSize(float64(fontSize))

	_, err := fc.DrawString(text, freetype.Pt(xPosition, yPosition))

	return err
}
Beispiel #22
0
func loadCasefold() {
	if *casefoldingURL == "" {
		flag.Set("casefolding", *url+"CaseFolding.txt")
	}
	input := open(*casefoldingURL)
	defer input.close()
	scanner := bufio.NewScanner(input)
	for scanner.Scan() {
		line := scanner.Text()
		if len(line) == 0 || line[0] == '#' || len(strings.TrimSpace(line)) == 0 {
			continue
		}
		field := strings.Split(line, "; ")
		if len(field) != 4 {
			logger.Fatalf("CaseFolding.txt %.5s...: %d fields (expected %d)\n", line, len(field), 4)
		}
		kind := field[1]
		if kind != "C" && kind != "S" {
			// Only care about 'common' and 'simple' foldings.
			continue
		}
		p1, err := strconv.ParseUint(field[0], 16, 64)
		if err != nil {
			logger.Fatalf("CaseFolding.txt %.5s...: %s", line, err)
		}
		p2, err := strconv.ParseUint(field[2], 16, 64)
		if err != nil {
			logger.Fatalf("CaseFolding.txt %.5s...: %s", line, err)
		}
		chars[p1].foldCase = rune(p2)
	}
	if scanner.Err() != nil {
		logger.Fatal(scanner.Err())
	}
}
func (p partedPartitioner) GetDeviceSizeInBytes(devicePath string) (uint64, error) {
	p.logger.Debug(p.logTag, "Getting size of disk remaining after first partition")

	stdout, _, _, err := p.cmdRunner.RunCommand("parted", "-m", devicePath, "unit", "B", "print")
	if err != nil {
		return 0, bosherr.WrapErrorf(err, "Getting remaining size of `%s'", devicePath)
	}

	allLines := strings.Split(stdout, "\n")
	if len(allLines) < 3 {
		return 0, bosherr.Errorf("Getting remaining size of `%s'", devicePath)
	}

	partitionInfoLines := allLines[1:3]
	deviceInfo := strings.Split(partitionInfoLines[0], ":")
	deviceFullSizeInBytes, err := strconv.ParseUint(strings.TrimRight(deviceInfo[1], "B"), 10, 64)
	if err != nil {
		return 0, bosherr.WrapErrorf(err, "Getting remaining size of `%s'", devicePath)
	}

	firstPartitionInfo := strings.Split(partitionInfoLines[1], ":")
	firstPartitionEndInBytes, err := strconv.ParseUint(strings.TrimRight(firstPartitionInfo[2], "B"), 10, 64)
	if err != nil {
		return 0, bosherr.WrapErrorf(err, "Getting remaining size of `%s'", devicePath)
	}

	remainingSizeInBytes := deviceFullSizeInBytes - firstPartitionEndInBytes - 1

	return remainingSizeInBytes, nil
}
Beispiel #24
0
func parseScript(line string, scripts map[string][]Script) {
	comment := strings.Index(line, "#")
	if comment >= 0 {
		line = line[0:comment]
	}
	line = strings.TrimSpace(line)
	if len(line) == 0 {
		return
	}
	field := strings.Split(line, ";")
	if len(field) != 2 {
		logger.Fatalf("%s: %d fields (expected 2)\n", line, len(field))
	}
	matches := scriptRe.FindStringSubmatch(line)
	if len(matches) != 4 {
		logger.Fatalf("%s: %d matches (expected 3)\n", line, len(matches))
	}
	lo, err := strconv.ParseUint(matches[1], 16, 64)
	if err != nil {
		logger.Fatalf("%.5s...: %s", line, err)
	}
	hi := lo
	if len(matches[2]) > 2 { // ignore leading ..
		hi, err = strconv.ParseUint(matches[2][2:], 16, 64)
		if err != nil {
			logger.Fatalf("%.5s...: %s", line, err)
		}
	}
	name := matches[3]
	scripts[name] = append(scripts[name], Script{uint32(lo), uint32(hi), name})
}
Beispiel #25
0
func parseMetaValue(v string) (mv *metaValue, err error) {
	f := strings.Split(v, "/")
	if len(f) != 4 {
		return nil, errors.New("wrong number of fields")
	}
	mv = &metaValue{}
	plainSize, err := strconv.ParseUint(f[0], 10, 32)
	if err != nil {
		return nil, fmt.Errorf("bad plaintext size in meta %q", v)
	}
	mv.PlainSize = uint32(plainSize)
	mv.IV, err = hex.DecodeString(f[1])
	if err != nil {
		return nil, fmt.Errorf("bad iv in meta %q", v)
	}
	var ok bool
	mv.EncBlobRef, ok = blob.Parse(f[2])
	if !ok {
		return nil, fmt.Errorf("bad blobref in meta %q", v)
	}
	encSize, err := strconv.ParseUint(f[3], 10, 32)
	if err != nil {
		return nil, fmt.Errorf("bad encrypted size in meta %q", v)
	}
	mv.EncSize = uint32(encSize)
	return mv, nil
}
Beispiel #26
0
func (s *Store) AddVolume(volumeListString string, replicationType string) error {
	rt, e := NewReplicationTypeFromString(replicationType)
	if e != nil {
		return e
	}
	for _, range_string := range strings.Split(volumeListString, ",") {
		if strings.Index(range_string, "-") < 0 {
			id_string := range_string
			id, err := NewVolumeId(id_string)
			if err != nil {
				return errors.New("Volume Id " + id_string + " is not a valid unsigned integer!")
			}
			e = s.addVolume(VolumeId(id), rt)
		} else {
			pair := strings.Split(range_string, "-")
			start, start_err := strconv.ParseUint(pair[0], 10, 64)
			if start_err != nil {
				return errors.New("Volume Start Id" + pair[0] + " is not a valid unsigned integer!")
			}
			end, end_err := strconv.ParseUint(pair[1], 10, 64)
			if end_err != nil {
				return errors.New("Volume End Id" + pair[1] + " is not a valid unsigned integer!")
			}
			for id := start; id <= end; id++ {
				if err := s.addVolume(VolumeId(id), rt); err != nil {
					e = err
				}
			}
		}
	}
	return e
}
Beispiel #27
0
// parseQueryMeta is used to help parse query meta-data
func parseQueryMeta(resp *http.Response, q *QueryMeta) error {
	header := resp.Header

	// Parse the X-Consul-Index
	index, err := strconv.ParseUint(header.Get("X-Consul-Index"), 10, 64)
	if err != nil {
		return fmt.Errorf("Failed to parse X-Consul-Index: %v", err)
	}
	q.LastIndex = index

	// Parse the X-Consul-LastContact
	last, err := strconv.ParseUint(header.Get("X-Consul-LastContact"), 10, 64)
	if err != nil {
		return fmt.Errorf("Failed to parse X-Consul-LastContact: %v", err)
	}
	q.LastContact = time.Duration(last) * time.Millisecond

	// Parse the X-Consul-KnownLeader
	switch header.Get("X-Consul-KnownLeader") {
	case "true":
		q.KnownLeader = true
	default:
		q.KnownLeader = false
	}
	return nil
}
// Test if a key is present, but only for the current user (regardless of /broadcast)
func TestKeyCond_RLu(up *user, owner uint32, modifier string, descr string) bool {
	// The expected modifier is: "A,B", where A is the key id and B is the owner id
	args := strings.SplitN(modifier, ",", 2)
	if len(args) != 2 {
		if *verboseFlag > 0 {
			log.Println("Bad key condition", args)
		}
		return false
	}
	keyId, err1 := strconv.ParseUint(args[0], 10, 0)
	ownerId, err2 := strconv.ParseUint(args[1], 10, 0)
	if err2 == nil {
		owner = uint32(ownerId)
	}
	if err1 == nil {
		up.RLock()
		res := up.pl.Keys.Test(owner, uint(keyId))
		up.RUnlock()
		if !res {
			up.Printf_Bl("%s", descr)
		}
		if *verboseFlag > 0 {
			log.Println("Cond key", owner, keyId, res)
		}
		return res
	} else {
		log.Println("Bad modifier", modifier, err1, err2)
	}
	return false
}
func (t *Access) AddEntry(acc string) { //Adds an entry to the Access structure. It takes a line (from the input file), and sets all the structure's fields
	entry := strings.Split(acc, ",") //Splits the line into 3 parts (on comma), returns an array of strings: pid, r/w, address
	if len(entry) > 3 {              //If we get more than 3 fields on a line, then, ERROR
		fmt.Println("Entry had more than 3 fields")
		os.Exit(2)
	}
	var err error = nil                                  // err is a variable of type error , which is a primitive type
	t.process, err = strconv.ParseUint(entry[0], 10, 64) //Converts the pid, which is taken as decimal(second parameter), whose length is restricted to 64 bits(3rd parameter) to uint

	if err != nil { //If it is unable to convert, ERROR
		fmt.Println("Invalid Process ID", err)
		os.Exit(3)
	}

	if strings.Contains(entry[1], "W") || strings.Contains(entry[1], "w") { //contains searches for second param, in first param
		t.access = "w" // for simplicity, we're making all the chars to lowercase
	} else if strings.Contains(entry[1], "r") || strings.Contains(entry[1], "R") {
		t.access = "r"
	} else {
		fmt.Println("Invalid Access Specifier", entry[1])
		os.Exit(4)
	}

	t.virtualAddress, err = strconv.ParseUint(entry[2], 16, 16) //Takes the address, treats it as hexa, and restricts it to 16 bits. Returns uint
	if err != nil {
		fmt.Println("I cannot understand the address ", err)
		os.Exit(5)
	}
}
Beispiel #30
0
// Determine the heart-beat values in a CONNECT or STOMP frame.
//
// Returns 0,0 if the heart-beat header is missing. Otherwise
// returns the cx and cy values in the frame.
//
// Returns an error if the heart-beat header is malformed, or if
// the frame is not a CONNECT or STOMP frame. In this implementation,
// a heart-beat header is considered malformed if either cx or cy
// is greater than MaxHeartBeat.
func getHeartBeat(f *frame.Frame) (cx, cy int, err error) {
	if f.Command != frame.CONNECT &&
		f.Command != frame.STOMP &&
		f.Command != frame.CONNECTED {
		err = invalidOperationForFrame
		return
	}
	if heartBeat, ok := f.Header.Contains(frame.HeartBeat); ok {
		if !heartBeatRegexp.MatchString(heartBeat) {
			err = invalidHeartBeat
			return
		}

		// no error checking here because we are confident
		// that everything will work because the regexp matches.
		slice := strings.Split(heartBeat, ",")
		value1, _ := strconv.ParseUint(slice[0], 10, 32)
		value2, _ := strconv.ParseUint(slice[1], 10, 32)
		cx = int(value1)
		cy = int(value2)
	} else {
		// heart-beat header not present
		// this else clause is not necessary, but
		// included for clarity.
		cx = 0
		cy = 0
	}
	return
}