Esempio n. 1
0
// ParseToken is a helper function that extracts the username and password
// from an authorization token.  Callers should be able to pass in the header
// "Authorization" from an HTTP request, and retrieve the credentials.
//
// If the token is malformed, empty strings are returned for the
// username and password.
func (a *Basic) ParseToken(token string) (username, password string) {
	if token == "" {
		return "", ""
	}

	// Check that the token supplied corresponds to the basic authorization
	// protocol
	ndx := strings.IndexRune(token, ' ')
	if ndx < 1 || token[0:ndx] != "Basic" {
		return "", ""
	}

	// Drop prefix, and decode the base64
	buffer, err := base64.StdEncoding.DecodeString(token[ndx+1:])
	if err != nil {
		return "", ""
	}
	token = string(buffer)

	ndx = strings.IndexRune(token, ':')
	if ndx < 1 {
		return "", ""
	}

	return token[0:ndx], token[ndx+1:]
}
Esempio n. 2
0
func varLexNumber(l *varLexer) lexState {
	l.accept("+-")
	digits := "0123456789"
	if l.accept("0") {
		if l.accept("x") {
			digits = "0123456789abcdefABCDEF"
		} else {
			digits = "01234567"
		}
	}
	for strings.IndexRune(digits, l.next()) >= 0 {
	}
	l.backup()
	if l.accept(".") {
		for strings.IndexRune(digits, l.next()) >= 0 {
		}
		l.backup()
	}
	if l.accept("eE") {
		l.accept("+-")
		for strings.IndexRune("0123456789", l.next()) >= 0 {
		}
		l.backup()
	}
	if r := l.peek(); unicode.IsLetter(r) {
		l.next()
		return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
	}
	l.emit(tokNumber)
	return varLexNormal
}
Esempio n. 3
0
// Languages returns the user's preferred languages in BCP 47 format in
// priority order.
func Languages() (langs []string) {
	add := func(lang string) {
		for _, l := range strings.Split(lang, ":") {
			// Remove encoding (we only support UTF-8).
			if i := strings.IndexRune(l, '.'); i != -1 {
				l = l[:i]
			}
			// Skip empty locales or the "C" locale.
			if l == "" || l == "C" {
				continue
			}
			// Add the locale.
			langs = append(langs, strings.Replace(l, "_", "-", -1))
			// Add the base language if it is a dialect.
			if i := strings.IndexRune(l, '_'); i != -1 {
				langs = append(langs, l[:i])
			}
		}
	}
	add(os.Getenv("LANGUAGE"))
	add(os.Getenv("LC_MESSAGES"))
	add(os.Getenv("LC_ALL"))
	add(os.Getenv("LANG"))
	return
}
func init() {
	codel := `nug
rbc vjnmkf kd yxyqci na rbc zjkfoscdd ew rbc ujllmcp
tc rbkso rbyr ejp mysljylc kd kxveddknmc re jsicpdrysi
de kr kd eoya kw aej icfkici re zjkr`
	decol := `bjv
the public is amazed by the quickness of the juggler
we think that our language is impossible to understand
so it is okay if you decided to quit`

	m = map[rune]rune{' ': ' '}
	var misscod, missdec []rune
	for i := 'a'; i <= 'z'; i++ {
		ix := strings.IndexRune(codel, i)
		if ix != -1 {
			m[i] = rune(decol[ix])
		} else {
			misscod = append(misscod, i)
		}

		ix = strings.IndexRune(decol, i)
		if ix == -1 {
			missdec = append(missdec, i)
		}
	}
	for ix, i := range misscod {
		m[i] = missdec[ix]
	}
}
Esempio n. 5
0
//NewDependencyInfo creates a new DependencyInfo with the given line
func NewDependencyInfo(line string) (*DependencyInfo, error) {
	sep1 := strings.IndexRune(line, ' ')
	if sep1 != 1 {
		return nil, errors.New("Invalid separator")
	}
	sep2 := strings.IndexRune(line[sep1+1:], ' ')
	if sep2 < 0 {
		return nil, errors.New("Invalid separator")
	}
	sep2 += sep1 + 1

	depi := new(DependencyInfo)
	var err error
	depi.To, err = strconv.Atoi(line[sep1+1 : sep2-1])
	if err != nil {
		return nil, err
	}
	depi.DepType = rune(line[sep2-1])

	depi.Features = getFeatures(line[sep2+1:], '>', 1)
	if pasresult, ok := depi.Features["格解析結果"]; ok {
		depi.Pas, err = NewPas(pasresult, true)
	}

	return depi, err
}
func setState(in *RuneBuffer, out chan *Item) StateFn {
	if r, ok := in.Peek(); ok {
		switch {
		case strings.IndexRune(" \t\r\n", r) >= 0:
			for ok { //skip whitespace
				_, ok, _ = in.Accept(" \t\r\n")
			}
			return setState
		case strings.IndexRune("*/", r) >= 0:
			in.Next()
			out <- &Item{Type: string(r), Token: string(r)}
			return setState
		case strings.IndexRune("0123456789", r) >= 0:
			numberState(in, out)
			return setState
		case r == ';':
			in.Next()
			out <- &Item{Type: "EOL", Token: "EOL"}
			commentState(in, out)
			return setState
		case r == '>':
			in.Next()
			out <- &Item{Type: ">", Token: ">"}
			return switchState
		default:
			return phonemeState
		}
	} else {
		return nil
	}
}
Esempio n. 7
0
func lexStart(l *Lexer) (next_fn LexFn) {
	for {
		r := l.Peek()

		if r == EOF {
			return nil
		} else if r == ' ' {
			l.Skip()
		} else if strings.IndexRune(DIGITS, r) >= 0 {
			return lexNumber
		} else if strings.IndexRune(OPERATORS, r) >= 0 {
			l.Expand()
			l.Emit(OperatorLexeme)
		} else if r == '(' {
			l.Expand()
			l.Emit(LeftParenLexeme)
		} else if r == ')' {
			l.Expand()
			l.Emit(RightParenLexeme)
		} else {
			l.Expand()
			l.Emit(ErrLexeme)
		}
	}

	return nil
}
Esempio n. 8
0
// Colorize processes all colors in a given text block and returns a new string
// with all readable codes translated to ANSI codes.
func Colorize(text string) string {
	final := new(bytes.Buffer)
	toColor := new(bytes.Buffer)
	prevColorFunc := noopColorFunc
	for len(text) > 0 {
		startIndex := strings.IndexRune(text, ColorCodeOpen)
		switch {
		// if it's escaped, skip it.
		case startIndex > 0 && rune(text[startIndex-1]) == ColorCodeEscape:
			toColor.WriteString(text[:startIndex-1])
			toColor.WriteRune(ColorCodeOpen)
			text = text[startIndex+1:]
			continue
		case startIndex < 0:
			toColor.WriteString(text)
			final.WriteString(prevColorFunc(toColor.String()))
			text = ""
		default:
			toColor.WriteString(text[:startIndex])
			final.WriteString(prevColorFunc(toColor.String()))
			toColor = new(bytes.Buffer)
			text = text[startIndex+1:]
			endIndex := strings.IndexRune(text, ColorCodeClose)
			prevColorFunc = getColorFunction(text[:endIndex])
			text = text[endIndex+1:]
		}
	}

	return final.String()
}
Esempio n. 9
0
func getCharset() string {
	// Determine the character set.  This can help us later.
	// Per POSIX, we search for LC_ALL first, then LC_CTYPE, and
	// finally LANG.  First one set wins.
	locale := ""
	if locale = os.Getenv("LC_ALL"); locale == "" {
		if locale = os.Getenv("LC_CTYPE"); locale == "" {
			locale = os.Getenv("LANG")
		}
	}
	if locale == "POSIX" || locale == "C" {
		return "US-ASCII"
	}
	if i := strings.IndexRune(locale, '@'); i >= 0 {
		locale = locale[:i]
	}
	if i := strings.IndexRune(locale, '.'); i >= 0 {
		locale = locale[i+1:]
	} else {
		// Default assumption, and on Linux we can see LC_ALL
		// without a character set, which we assume implies UTF-8.
		return "UTF-8"
	}
	// XXX: add support for aliases
	return locale
}
Esempio n. 10
0
func Parse(str string) (*Selector, error) {
	// TODO proper parsing
	var reqAttr string
	var subAttr string
	var re *regexp.Regexp
	startPos := 0
	endPos := len(str)
	negate := false
	if str[0] == '!' {
		negate = true
		startPos = 1
	}
	if idx := strings.IndexRune(str, '='); idx != -1 {
		var err error
		re, err = regexp.Compile(str[idx+1:])
		if err != nil {
			return nil, errors.New("invalid regexp")
		}
		endPos = idx
	}

	if idx := strings.IndexRune(str, ':'); idx >= startPos {
		reqAttr = str[startPos:idx]
		subAttr = str[idx+1 : endPos]
	} else {
		reqAttr = str[startPos:endPos]
	}
	if reqAttr == "" {
		return nil, errors.New("missing request attribute")
	}
	return &Selector{reqAttr, subAttr, re, negate}, nil
}
Esempio n. 11
0
// Purge will remove color codes from the given string.
func Purge(text string) string {
	final := new(bytes.Buffer)
	for len(text) > 0 {
		startIndex := strings.IndexRune(text, ColorCodeOpen)
		switch {
		case startIndex >= 0:
			if startIndex > 0 && text[startIndex-1] == ColorCodeEscape {
				final.WriteString(text[:startIndex-1])
				final.WriteRune(ColorCodeOpen)
				text = text[startIndex+1:]
				continue
			} else if startIndex > 0 {
				final.WriteString(text[:startIndex])
			}

			endIndex := strings.IndexRune(text, ColorCodeClose)
			text = text[endIndex+1:]
		default:
			final.WriteString(text)
			text = ""
		}
	}

	return final.String()
}
Esempio n. 12
0
func (sc *SlackClient) unSlackify(str string) string {
	// Links e.g. <http://heise.de|heise.de>, <http://heise.de>
	if strings.HasPrefix(str, "<http") {
		endpos := strings.IndexRune(str, '|')
		if endpos != -1 {
			return str[1:endpos]
		}
		return str[1 : len(str)-1]
	}
	// Highlights e. g. <@U02A2A2A2>
	if strings.HasPrefix(str, "<@U") {
		userID := str[2 : len(str)-1]
		user, ok := sc.userIDMap[userID]
		if ok {
			return user.Name
		}
		// if we do not have a match, just return the ID.
		return str[1 : len(str)-1]
	}
	// Mail addresses e.g. <mailto:[email protected]|[email protected]>
	if strings.HasPrefix(str, "<mailto:") {
		return str[8:strings.IndexRune(str, '|')]
	}
	// Channels <#C02A2A2A2>
	if strings.HasPrefix(str, "<#C") {
		chanID := str[2 : len(str)-1]
		channel, ok := sc.chanIDMap[chanID]
		if ok {
			return fmt.Sprintf("#%v", channel.Name)
		}
		return str[1 : len(str)-1]
	}
	return str
}
Esempio n. 13
0
// ParseNamedDockerImageReference parses a Docker pull spec string into a
// NamedDockerImageReference.
func ParseNamedDockerImageReference(spec string) (NamedDockerImageReference, error) {
	var ref NamedDockerImageReference

	namedRef, err := reference.ParseNamed(spec)
	if err != nil {
		return ref, err
	}

	name := namedRef.Name()
	i := strings.IndexRune(name, '/')
	if i == -1 || (!strings.ContainsAny(name[:i], ":.") && name[:i] != "localhost") {
		ref.Name = name
	} else {
		ref.Registry, ref.Name = name[:i], name[i+1:]
	}

	if named, ok := namedRef.(reference.NamedTagged); ok {
		ref.Tag = named.Tag()
	}

	if named, ok := namedRef.(reference.Canonical); ok {
		ref.ID = named.Digest().String()
	}

	// It's not enough just to use the reference.ParseNamed(). We have to fill
	// ref.Namespace from ref.Name
	if i := strings.IndexRune(ref.Name, '/'); i != -1 {
		ref.Namespace, ref.Name = ref.Name[:i], ref.Name[i+1:]
	}

	return ref, nil
}
Esempio n. 14
0
func breadcrumbsFn(pdoc *doc.Package) string {
	if !strings.HasPrefix(pdoc.ImportPath, pdoc.ProjectRoot) {
		return ""
	}
	var buf bytes.Buffer
	i := 0
	j := len(pdoc.ProjectRoot)
	if j == 0 {
		buf.WriteString("<a href=\"/-/go\" title=\"Standard Packages\">☆</a> ")
		j = strings.IndexRune(pdoc.ImportPath, '/')
		if j < 0 {
			j = len(pdoc.ImportPath)
		}
	}
	for {
		buf.WriteString(`<a href="/`)
		buf.WriteString(urlFn(pdoc.ImportPath[:j]))
		buf.WriteString(`">`)
		buf.WriteString(template.HTMLEscapeString(pdoc.ImportPath[i:j]))
		buf.WriteString("</a>")
		i = j + 1
		if i >= len(pdoc.ImportPath) {
			break
		}
		buf.WriteByte('/')
		j = strings.IndexRune(pdoc.ImportPath[i:], '/')
		if j < 0 {
			j = len(pdoc.ImportPath)
		} else {
			j += i
		}
	}
	return buf.String()
}
Esempio n. 15
0
// ParseImageTag parses the docker image tag string and returns a validated Version or error
func ParseImageTag(s string) (CombinedVersion, error) {
	// try parse as a SEMVER
	prefix := ""
	version, err := semver.Parse(s)
	if err == nil {
		return CombinedVersion{Prefix: prefix, Version: version}, nil
	}
	// accept format such as `vSEMVER`
	if vIndex := strings.IndexRune(s, 'v'); vIndex == 0 {
		prefix = s[:vIndex+1]
		version, err = semver.Parse(s[vIndex+1:])
		if err == nil {
			return CombinedVersion{Prefix: prefix, Version: version}, nil
		}
	}
	// accept format such as `ANY-SEMVER`
	if firstHyphenIndex := strings.IndexRune(s, '-'); firstHyphenIndex != -1 {
		prefix = s[:firstHyphenIndex+1]
		version, err = semver.Parse(s[firstHyphenIndex+1:])
		if err == nil {
			return CombinedVersion{Prefix: prefix, Version: version}, nil
		}
	}
	return CombinedVersion{}, err
}
Esempio n. 16
0
func (t *tScreen) getCharset() string {
	// Let's also determine the character set.  This can help us later.
	// Per POSIX, we search for LC_ALL first, then LC_CTYPE, and
	// finally LANG.  First one set wins.
	locale := ""
	if locale = os.Getenv("LC_ALL"); locale == "" {
		if locale = os.Getenv("LC_CTYPE"); locale == "" {
			locale = os.Getenv("LANG")
		}
	}
	if locale == "POSIX" || locale == "C" {
		return "US-ASCII"
	}
	if i := strings.IndexRune(locale, '@'); i >= 0 {
		locale = locale[:i]
	}
	if i := strings.IndexRune(locale, '.'); i >= 0 {
		locale = locale[i+1:]
	}
	if locale == "" {
		return "UTF-8"
	}
	// XXX: add support for aliases
	return locale
}
func resourceHerokuAddonRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*heroku.Service)

	addon, err := resourceHerokuAddonRetrieve(
		d.Get("app").(string), d.Id(), client)
	if err != nil {
		return err
	}

	// Determine the plan. If we were configured without a specific plan,
	// then just avoid the plan altogether (accepting anything that
	// Heroku sends down).
	plan := addon.Plan.Name
	if v := d.Get("plan").(string); v != "" {
		if idx := strings.IndexRune(v, ':'); idx == -1 {
			idx = strings.IndexRune(plan, ':')
			if idx > -1 {
				plan = plan[:idx]
			}
		}
	}

	d.Set("name", addon.Name)
	d.Set("plan", plan)
	d.Set("provider_id", addon.ProviderID)
	if err := d.Set("config_vars", addon.ConfigVars); err != nil {
		return err
	}

	return nil
}
func explodeLocale(locale string) (mask uint, language string, territory string, codeset string, modifier string) {
	mask = uint(0)
	uscorePos := strings.IndexRune(locale, '_')
	dotPos := strings.IndexRune(locale, '.')
	atPos := strings.IndexRune(locale, '@')

	if atPos != -1 {
		mask |= _ComponentModifier
		modifier = locale[atPos:]
	} else {
		atPos = len(locale)
	}

	if dotPos != -1 {
		mask |= _ComponentCodeset
		codeset = locale[dotPos:atPos]
	} else {
		dotPos = atPos
	}

	if uscorePos != -1 {
		mask |= _ComponentTerritory
		territory = locale[uscorePos:dotPos]
	} else {
		uscorePos = dotPos
	}

	language = locale[:uscorePos]
	return
}
Esempio n. 19
0
// Authorize retrieves the credientials from the HTTP request, and
// returns the username only if the credientials could be validated.
// If the return value is blank, then the credentials are missing,
// invalid, or a system error prevented verification.
func (a *Basic) Authorize(r *http.Request) (username string) {
	token := r.Header.Get("Authorization")
	if token == "" {
		return ""
	}

	// Check that the token supplied corresponds to the basic authorization
	// protocol
	ndx := strings.IndexRune(token, ' ')
	if ndx < 1 || token[0:ndx] != "Basic" {
		return ""
	}

	// Drop prefix, and decode the base64
	buffer, err := base64.StdEncoding.DecodeString(token[ndx+1:])
	if err != nil {
		return ""
	}
	token = string(buffer)

	ndx = strings.IndexRune(token, ':')
	if ndx < 1 {
		return ""
	}

	if !a.Auth(token[0:ndx], token[ndx+1:], a.Realm) {
		return ""
	}

	return token[0:ndx]
}
Esempio n. 20
0
// Refresh reloads all the data associated with this process.
func (p *UnixProcess) Refresh() error {
	statPath := fmt.Sprintf("/proc/%d/stat", p.pid)
	dataBytes, err := ioutil.ReadFile(statPath)
	if err != nil {
		return err
	}

	// First, parse out the image name
	data := string(dataBytes)
	binStart := strings.IndexRune(data, '(') + 1
	binEnd := strings.IndexRune(data[binStart:], ')')
	p.binary = data[binStart : binStart+binEnd]

	// Move past the image name and start parsing the rest
	data = data[binStart+binEnd+2:]
	_, err = fmt.Sscanf(data,
		"%c %d %d %d",
		&p.state,
		&p.ppid,
		&p.pgrp,
		&p.sid)

	// Gather the number of files open
	fdPath := fmt.Sprintf("/proc/%d/fdinfo", p.pid)
	files, err := ioutil.ReadDir(fdPath)
	if err == nil {
		p.fds = len(files)
	} else {
		p.fds = -1
	}

	return err
}
Esempio n. 21
0
func init() {
	// OCTET      = <any 8-bit sequence of data>
	// CHAR       = <any US-ASCII character (octets 0 - 127)>
	// CTL        = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
	// CR         = <US-ASCII CR, carriage return (13)>
	// LF         = <US-ASCII LF, linefeed (10)>
	// SP         = <US-ASCII SP, space (32)>
	// HT         = <US-ASCII HT, horizontal-tab (9)>
	// <">        = <US-ASCII double-quote mark (34)>
	// CRLF       = CR LF
	// LWS        = [CRLF] 1*( SP | HT )
	// TEXT       = <any OCTET except CTLs, but including LWS>
	// separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <">
	//              | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT
	// token      = 1*<any CHAR except CTLs or separators>
	// qdtext     = <any TEXT except <">>

	for c := 0; c < 256; c++ {
		var t octetType
		isCtl := c <= 31 || c == 127
		isChar := 0 <= c && c <= 127
		isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0
		if strings.IndexRune(" \t\r\n", rune(c)) >= 0 {
			t |= isSpace
		}
		if isChar && !isCtl && !isSeparator {
			t |= isToken
		}
		octetTypes[c] = t
	}
}
Esempio n. 22
0
func parseDigestAuthHeader(r *http.Request) map[string]string {
	// Extract the authentication token.
	token := r.Header.Get("Authorization")
	if token == "" {
		return nil
	}

	// Check that the token supplied corresponds to the digest authorization
	// protocol.  If not, return nil to indicate failure.  No error
	// code is used as a malformed protocol is simply an authentication
	// failure.
	ndx := strings.IndexRune(token, ' ')
	if ndx < 1 || token[0:ndx] != "Digest" {
		return nil
	}
	token = token[ndx+1:]

	// Token is a comma separated list of name/value pairs.  Break-out pieces
	// and fill in a map.
	params := make(map[string]string)
	for _, str := range strings.Split(token, ",") {
		ndx := strings.IndexRune(str, '=')
		if ndx < 1 {
			// malformed name/value pair
			// ignore
			continue
		}
		name := strings.Trim(str[0:ndx], `" `)
		value := strings.Trim(str[ndx+1:], `" `)
		params[name] = value
	}

	return params
}
Esempio n. 23
0
// Refresh reloads all the data associated with this process.
func (p *UnixProcess) Refresh() error {
	statPath := fmt.Sprintf("/proc/%d/stat", p.pid)
	dataBytes, err := ioutil.ReadFile(statPath)
	if err != nil {
		return err
	}

	// First, parse out the image name
	data := string(dataBytes)
	binStart := strings.IndexRune(data, '(') + 1
	binEnd := strings.IndexRune(data[binStart:], ')')
	p.binary = data[binStart : binStart+binEnd]

	// Move past the image name and start parsing the rest
	// The name here might not be the full name
	data = data[binStart+binEnd+2:]
	_, err = fmt.Sscanf(data,
		"%c %d %d %d",
		&p.state,
		&p.ppid,
		&p.pgrp,
		&p.sid)

	return err
}
Esempio n. 24
0
func ExampleIndexRune() {
	fmt.Println(strings.IndexRune("chicken", 'k'))
	fmt.Println(strings.IndexRune("chicken", 'd'))
	// Output:
	// 4
	// -1
}
Esempio n. 25
0
func main() {
	cmd := os.Args[0]
	i := strings.IndexRune(cmd, os.PathSeparator)
	for i != -1 {
		cmd = cmd[i+1:]
		i = strings.IndexRune(cmd, os.PathSeparator)
	}

	f, ok := modes[cmd]
	if !ok {
		fmt.Fprintf(os.Stderr, "Unknown command %q.\nRename or link this binary as one of the following:\n", cmd)
		for k, _ := range modes {
			fmt.Println("\t", k)
		}
		os.Exit(1)
	}
	config := false
	for _, arg := range os.Args[1:] {
		if arg == "config" {
			config = true
		} else {
			fmt.Fprintln(os.Stderr, "unhandled argument", os.Args[1])
			os.Exit(1)
		}
	}

	f(config)
}
Esempio n. 26
0
func explodeLocale(locale string) (mask uint, language string, territory string, codeset string, modifier string) {
	mask = uint(0)
	uscore_pos := strings.IndexRune(locale, '_')
	dot_pos := strings.IndexRune(locale, '.')
	at_pos := strings.IndexRune(locale, '@')

	if at_pos != -1 {
		mask |= COMPONENT_MODIFIER
		modifier = locale[at_pos:]
		logger.Debug("modifier", modifier)
	} else {
		at_pos = len(locale)
	}

	if dot_pos != -1 {
		mask |= COMPONENT_CODESET
		codeset = locale[dot_pos:at_pos]
		logger.Debug("codeset", codeset)
	} else {
		dot_pos = at_pos
	}

	if uscore_pos != -1 {
		mask |= COMPONENT_TERRITORY
		territory = locale[uscore_pos:dot_pos]
		logger.Debug("territory", territory)
	} else {
		uscore_pos = dot_pos
	}

	language = locale[:uscore_pos]
	return
}
Esempio n. 27
0
func listPid(pid int) error {
	buf, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
	if err != nil {
		return err
	}
	str := string(buf)

	pi := Proc{Cmd: "?", Pid: pid}
	op := strings.IndexRune(str, '(')
	cp := strings.IndexRune(str, ')')
	if op >= 0 && cp >= 0 {
		pi.Cmd = str[op+1 : cp]
	}

	info, err := os.Stat(fmt.Sprintf("/proc/%d", pid))
	if err == nil {
		st, ok := info.Sys().(*syscall.Stat_t)
		if ok {
			user, err := user.LookupId(fmt.Sprint(st.Uid))
			if !numeric && err == nil {
				pi.User = user.Username
			} else {
				pi.User = fmt.Sprint(st.Uid)
			}
		}
	}

	visitSymlink(&pi, "cwd", "cwd")
	visitSymlink(&pi, "rtd", "root")
	visitSymlink(&pi, "txt", "exe")
	visitMaps(&pi)
	visitFds(&pi)
	return nil
}
Esempio n. 28
0
// Refresh reloads all the data associated with this process.
func (p *UnixProcess) Refresh() error {
	statPath := fmt.Sprintf("/proc/%d/stat", p.pid)
	dataBytes, err := ioutil.ReadFile(statPath)
	if err != nil {
		return err
	}

	// stat file have truncated names
	// First, parse out the image name
	data := string(dataBytes)
	binStart := strings.IndexRune(data, '(') + 1
	binEnd := strings.IndexRune(data[binStart:], ')')

	for _, str := range []string{"comm", "cmdline"} {
		dataBytes, err = ioutil.ReadFile(fmt.Sprintf("/proc/%d/%s", p.pid, str))
		if err != nil {
			continue
		}

		if p.binary = strings.TrimSpace(string(bytes.Trim(dataBytes, "\x00"))); p.binary != "" {
			break
		}
	}

	if p.binary == "" {
		return fmt.Errorf("failed to get process executable")
	}

	// Move past the image name and start parsing the rest
	data = data[binStart+binEnd+2:]
	_, err = fmt.Sscanf(data,
		"%c %d %d %d",
		&p.state,
		&p.ppid,
		&p.pgrp,
		&p.sid)

	f, err := os.Open(fmt.Sprintf("/proc/%d/task", p.pid))
	if err != nil {
		return err
	}
	defer f.Close()

	dirnames, err := f.Readdirnames(-1)
	if err != nil {
		return err
	}

	for _, name := range dirnames {
		pid, err := strconv.ParseInt(name, 10, 0)
		if err != nil {
			continue
		}
		p.cpids = append(p.cpids, int(pid))
	}

	return err
}
Esempio n. 29
0
func TestKubeVersion(t *testing.T) {
	Convey("Subject: Version Checking", t, func() {
		kversion, err := exec.Command("kubectl", "version").Output()
		Convey("kubectl version returns no error", func() {
			So(err, ShouldBeNil)
		})
		versions := bytes.Split(kversion, []byte("\n"))
		cver := string(versions[0])
		cver = cver[strings.IndexRune(cver, '{')+1:]
		cver = strings.TrimRight(cver, "}")
		sver := string(versions[1])
		sver = sver[strings.IndexRune(sver, '{')+1:]
		sver = strings.TrimRight(sver, "}")
		Convey("Subject: Client and Server version should be equal", func() {
			So(cver, ShouldEqual, sver)
		})
		kver := strings.Split(cver, ",")
		vmap := make(map[string]string)
		for _, item := range kver {
			entry := strings.Split(strings.TrimSpace(item), ":")
			vmap[entry[0]] = entry[1]
		}

		rversion, err := exec.Command("rpm", "-q", "kubernetes").Output()
		Convey("rpm -q kubernetes returns no error", func() {
			So(err, ShouldBeNil)
		})
		srver := string(rversion)
		rgit := strings.Split(srver, "-")[1]
		rver := strings.FieldsFunc(srver, func(r rune) bool {
			return r == '-' || r == '.'
		})
		rmajor := rver[1]
		rminor := rver[2]
		rcommit := rver[7][3:]
		vmajor, err := strconv.Unquote(vmap["Major"])
		Convey("unquote major return no error", func() {
			So(err, ShouldBeNil)
		})
		Convey("version major should match", func() {
			So(vmajor, ShouldEqual, rmajor)
		})
		vminor, err := strconv.Unquote(vmap["Minor"])
		Convey("unquote minor return no error", func() {
			So(err, ShouldBeNil)
		})
		Convey("version minor should match", func() {
			So(vminor, ShouldEqual, rminor)
		})
		Convey("rpm git version should be within kubectl git version", func() {
			So(vmap["GitVersion"], ShouldContainSubstring, rgit)
		})
		Convey("rpm git commit should be within kubectl git commit", func() {
			So(vmap["GitCommit"], ShouldContainSubstring, rcommit)
		})
	})
}
Esempio n. 30
0
func HexaToBytes(src string) []byte {
	res := make([]byte, len(src)/2)
	for i := range res {
		first := byte(strings.IndexRune(hex, rune(src[i*2])))
		second := byte(strings.IndexRune(hex, rune(src[i*2+1])))
		res[i] = first<<4 | second
	}
	return res
}