Exemple #1
0
func (v *Vault0) serveLocal(fpath, query string) (*http.Response, os.Error) {
	fpath = path.Clean(fpath)
	if len(fpath) > 0 && fpath[0] == '/' {
		fpath = fpath[1:]
	}
	if fpath == "" {
		fpath = "index.html"
	}
	full := path.Join(v.hdir, fpath)
	if !isFile(full) {
		if fpath == "index.html" {
			return newRespNoIndexHTML(), nil
		} else {
			return newRespNotFound(), os.ErrorString("not found")
		}
	}

	// Serve file if we can allocate a file descriptor in time
	if v.fdlim.LockOrTimeout(10e9) == nil {
		body, bodylen, err := http.FileToBody(full)
		if err != nil {
			if body != nil {
				body.Close()
			}
			v.fdlim.Unlock()
			return newRespServiceUnavailable(), os.ErrorString("service unavailable")
		}
		body = http.NewRunOnClose(body, func() { v.fdlim.Unlock() })
		return buildRespFromBody(body, bodylen), nil
	} else {
		return newRespServiceUnavailable(), os.ErrorString("service unavailable")
	}
	panic("unreach")
}
Exemple #2
0
// ParseURL parses rawurl into a URL structure.
// The string rawurl is assumed not to have a #fragment suffix.
// (Web browsers strip #fragment before sending the URL to a web server.)
func ParseURL(rawurl string) (url *URL, err os.Error) {
	if rawurl == "" {
		err = os.ErrorString("empty url")
		goto Error
	}
	url = new(URL)
	url.Raw = rawurl

	// split off possible leading "http:", "mailto:", etc.
	var path string
	if url.Scheme, path, err = getscheme(rawurl); err != nil {
		goto Error
	}
	url.RawPath = path

	// RFC 2396: a relative URI (no scheme) has a ?query,
	// but absolute URIs only have query if path begins with /
	if url.Scheme == "" || len(path) > 0 && path[0] == '/' {
		path, url.RawQuery = split(path, '?', true)
	}

	// Maybe path is //authority/path
	if len(path) > 2 && path[0:2] == "//" {
		url.Authority, path = split(path[2:], '/', false)
	}

	// If there's no @, split's default is wrong.  Check explicitly.
	if strings.Index(url.Authority, "@") < 0 {
		url.Host = url.Authority
	} else {
		url.Userinfo, url.Host = split(url.Authority, '@', true)
	}

	if url.Path, err = urlUnescape(path, false); err != nil {
		goto Error
	}

	// Remove escapes from the Authority and Userinfo fields, and verify
	// that Scheme and Host contain no escapes (that would be illegal).
	if url.Authority, err = urlUnescape(url.Authority, false); err != nil {
		goto Error
	}
	if url.Userinfo, err = urlUnescape(url.Userinfo, false); err != nil {
		goto Error
	}
	if strings.Index(url.Scheme, "%") >= 0 {
		err = os.ErrorString("hexadecimal escape in scheme")
		goto Error
	}
	if strings.Index(url.Host, "%") >= 0 {
		err = os.ErrorString("hexadecimal escape in host")
		goto Error
	}

	return url, nil

Error:
	return nil, &URLError{"parse", rawurl, err}

}
Exemple #3
0
// Much like http.Get. If s is nil, uses DefaultSender.
func Get(s Sender, url string) (rs []*http.Response, err os.Error) {
	for redirect := 0; ; redirect++ {
		if redirect >= 10 {
			err = os.ErrorString("stopped after 10 redirects")
			break
		}

		var req http.Request
		req.RawURL = url
		req.Header = map[string]string{}
		r, err := Send(s, &req)
		if err != nil {
			break
		}
		rs = prepend(r, rs)
		if shouldRedirect(r.StatusCode) {
			r.Body.Close()
			if url = r.GetHeader("Location"); url == "" {
				err = os.ErrorString(fmt.Sprintf("%d response missing Location header", r.StatusCode))
				break
			}
			continue
		}

		return
	}

	err = &http.URLError{"Get", url, err}
	return
}
func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg) ([]byte, os.Error) {
	preMasterSecret := make([]byte, 48)
	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
	if err != nil {
		return nil, err
	}

	if len(ckx.ciphertext) < 2 {
		return nil, os.ErrorString("bad ClientKeyExchange")
	}
	ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
	if ciphertextLen != len(ckx.ciphertext)-2 {
		return nil, os.ErrorString("bad ClientKeyExchange")
	}
	ciphertext := ckx.ciphertext[2:]

	err = rsa.DecryptPKCS1v15SessionKey(config.rand(), config.Certificates[0].PrivateKey, ciphertext, preMasterSecret)
	if err != nil {
		return nil, err
	}
	// We don't check the version number in the premaster secret.  For one,
	// by checking it, we would leak information about the validity of the
	// encrypted pre-master secret. Secondly, it provides only a small
	// benefit against a downgrade attack and some implementations send the
	// wrong version anyway. See the discussion at the end of section
	// 7.4.7.1 of RFC 4346.
	return preMasterSecret, nil
}
Exemple #5
0
func (server *Server) readRequest(codec ServerCodec) (req *Request, service *service, mtype *methodType, err os.Error) {
	// Grab the request header.
	req = server.getRequest()
	err = codec.ReadRequestHeader(req)
	if err != nil {
		req = nil
		if err == os.EOF || err == io.ErrUnexpectedEOF {
			return
		}
		err = os.ErrorString("rpc: server cannot decode request: " + err.String())
		return
	}

	serviceMethod := strings.Split(req.ServiceMethod, ".", -1)
	if len(serviceMethod) != 2 {
		err = os.ErrorString("rpc: service/method request ill-formed: " + req.ServiceMethod)
		return
	}
	// Look up the request.
	server.Lock()
	service = server.serviceMap[serviceMethod[0]]
	server.Unlock()
	if service == nil {
		err = os.ErrorString("rpc: can't find service " + req.ServiceMethod)
		return
	}
	mtype = service.method[serviceMethod[1]]
	if mtype == nil {
		err = os.ErrorString("rpc: can't find method " + req.ServiceMethod)
	}
	return
}
Exemple #6
0
// ImportNValues imports a channel of the given type and specified direction
// and then receives or transmits up to n values on that channel.  A value of
// n==0 implies an unbounded number of values.  The channel to be bound to
// the remote site's channel is provided in the call and may be of arbitrary
// channel type.
// Despite the literal signature, the effective signature is
//	ImportNValues(name string, chT chan T, dir Dir, pT T)
// where T must be a struct, pointer to struct, etc.  pT may be more indirect
// than the value type of the channel (e.g.  chan T, pT *T) but it must be a
// pointer.
// Example usage:
//	imp, err := NewImporter("tcp", "netchanserver.mydomain.com:1234")
//	if err != nil { log.Exit(err) }
//	ch := make(chan myType)
//	err := imp.ImportNValues("name", ch, Recv, new(myType), 1)
//	if err != nil { log.Exit(err) }
//	fmt.Printf("%+v\n", <-ch)
// (TODO: Can we eliminate the need for pT?)
func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, pT interface{}, n int) os.Error {
	ch, err := checkChan(chT, dir)
	if err != nil {
		return err
	}
	// Make sure pT is a pointer (to a pointer...) to a struct.
	rt := reflect.Typeof(pT)
	if _, ok := rt.(*reflect.PtrType); !ok {
		return os.ErrorString("not a pointer:" + rt.String())
	}
	if _, ok := reflect.Indirect(reflect.NewValue(pT)).(*reflect.StructValue); !ok {
		return os.ErrorString("not a pointer to a struct:" + rt.String())
	}
	imp.chanLock.Lock()
	defer imp.chanLock.Unlock()
	_, present := imp.chans[name]
	if present {
		return os.ErrorString("channel name already being imported:" + name)
	}
	ptr := reflect.MakeZero(reflect.Typeof(pT)).(*reflect.PtrValue)
	imp.chans[name] = &importChan{ch, dir, ptr, n}
	// Tell the other side about this channel.
	req := new(request)
	req.name = name
	req.dir = dir
	req.count = n
	if err := imp.encode(req, nil); err != nil {
		log.Stderr("importer request encode:", err)
		return err
	}
	return nil
}
Exemple #7
0
func (y *Conn) Auth(af connAuthFunc) (remote sys.Id, err os.Error) {
	y.lk.Lock()
	if y.err != nil {
		y.lk.Unlock()
		return 0, os.ErrorString("d,conn: closed meantime")
	}
	if y.regime != regimeUnAuth || y.tube == nil {
		panic("d,conn: regime logic")
	}
	y.regime = regimeAuth
	tube := y.tube
	y.lk.Unlock()

	remote, tubex, err := af(tube)

	y.lk.Lock()
	if y.err != nil {
		y.lk.Unlock()
		return 0, os.ErrorString("d,conn: closed meantime")
	}
	if err != nil {
		y.lk.Unlock()
		return 0, y.kill(os.ErrorString("d,conn: auth failed"))
	}
	y.id = &remote
	y.tube = tubex
	y.regime = regimeReady
	y.lk.Unlock()
	return remote, nil
}
Exemple #8
0
func (y *Conn) Greet() (string, string, os.Error) {
	y.lk.Lock()
	if y.err != nil {
		y.lk.Unlock()
		return "", "", os.ErrorString("d,conn: closed meantime")
	}
	if y.regime != regimeUnAuth || y.tube == nil {
		panic("d,conn: regime logic")
	}
	y.regime = regimeAuth
	tube := y.tube
	y.lk.Unlock()

	g := &U_Greet{sys.Build, Version}
	err := tube.Encode(g)
	if err == nil {
		err = tube.Decode(g)
	}

	y.lk.Lock()
	if y.err != nil {
		y.lk.Unlock()
		return "", "", os.ErrorString("d,conn: closed meantime")
	}
	if err != nil {
		y.lk.Unlock()
		return "", "", y.kill(os.ErrorString("d,conn: greet failed"))
	}
	y.regime = regimeUnAuth
	y.lk.Unlock()
	return g.Build, g.Version, nil
}
Exemple #9
0
// consumeQuotedString parses the quoted string at the start of p.
func (p *addrParser) consumeQuotedString() (qs string, err os.Error) {
	// Assume first byte is '"'.
	i := 1
	qsb := make([]byte, 0, 10)
Loop:
	for {
		if i >= p.len() {
			return "", os.ErrorString("mail: unclosed quoted-string")
		}
		switch c := (*p)[i]; {
		case c == '"':
			break Loop
		case c == '\\':
			if i+1 == p.len() {
				return "", os.ErrorString("mail: unclosed quoted-string")
			}
			qsb = append(qsb, (*p)[i+1])
			i += 2
		case isQtext(c), c == ' ' || c == '\t':
			// qtext (printable US-ASCII excluding " and \), or
			// FWS (almost; we're ignoring CRLF)
			qsb = append(qsb, c)
			i++
		default:
			return "", fmt.Errorf("mail: bad character in quoted-string: %q", c)
		}
	}
	*p = (*p)[i+1:]
	return string(qsb), nil
}
Exemple #10
0
// Get issues a GET to the specified URL.  If the response is one of the following
// redirect codes, it follows the redirect, up to a maximum of 10 redirects:
//
//    301 (Moved Permanently)
//    302 (Found)
//    303 (See Other)
//    307 (Temporary Redirect)
//
// finalUrl is the URL from which the response was fetched -- identical to the input
// URL unless redirects were followed.
//
// Caller should close r.Body when done reading it.
func Get(url string) (r *Response, finalURL string, err os.Error) {
	// TODO: if/when we add cookie support, the redirected request shouldn't
	// necessarily supply the same cookies as the original.
	// TODO: set referrer header on redirects.
	for redirect := 0; ; redirect++ {
		if redirect >= 10 {
			err = os.ErrorString("stopped after 10 redirects")
			break
		}

		var req Request
		if req.Url, err = ParseURL(url); err != nil {
			break
		}
		if r, err = send(&req); err != nil {
			break
		}
		if shouldRedirect(r.StatusCode) {
			r.Body.Close()
			if url = r.GetHeader("Location"); url == "" {
				err = os.ErrorString(fmt.Sprintf("%d response missing Location header", r.StatusCode))
				break
			}
			continue
		}
		finalURL = url
		return
	}

	err = &URLError{"Get", url, err}
	return
}
func pkcs1v15HashInfo(hash PKCS1v15Hash, inLen int) (hashLen int, prefix []byte, err os.Error) {
	switch hash {
	case HashMD5:
		hashLen = 16
	case HashSHA1:
		hashLen = 20
	case HashSHA256:
		hashLen = 32
	case HashSHA384:
		hashLen = 48
	case HashSHA512:
		hashLen = 64
	case HashMD5SHA1:
		hashLen = 36
	default:
		return 0, nil, os.ErrorString("unknown hash function")
	}

	if inLen != hashLen {
		return 0, nil, os.ErrorString("input must be hashed message")
	}

	prefix = hashPrefixes[int(hash)]
	return
}
func (dec *Decoder) ignoreMap(state *decodeState, keyOp, elemOp decOp) {
	n := int(state.decodeUint())
	keyInstr := &decInstr{keyOp, 0, 0, 0, os.ErrorString("no error")}
	elemInstr := &decInstr{elemOp, 0, 0, 0, os.ErrorString("no error")}
	for i := 0; i < n; i++ {
		keyOp(keyInstr, state, nil)
		elemOp(elemInstr, state, nil)
	}
}
Exemple #13
0
func (s *routerImpl) AttachRecvChan(id Id, v interface{}, args ...interface{}) (routCh *RoutedChan, err os.Error) {
	if err = s.validateId(id); err != nil {
		s.LogError(err)
		s.Raise(err)
		return
	}
	var ok bool
	ch, internalChan := v.(Channel)
	if !internalChan {
		ch, ok = reflect.NewValue(v).(*reflect.ChanValue)
		if !ok {
			err = os.ErrorString(errInvalidChan)
			s.LogError(err)
			s.Raise(err)
			return
		}
	}
	var bindChan chan *BindEvent
	for i := 0; i < len(args); i++ {
		switch cv := args[0].(type) {
		case chan *BindEvent:
			bindChan = cv
			if cap(bindChan) == 0 {
				err = os.ErrorString(errInvalidBindChan + ": binding bindChan is not buffered")
				s.LogError(err)
				s.Raise(err)
				return
			}
		case int:
			//set recv chan buffer size
			s.bufSizeLock.Lock()
			old, ok := s.recvBufSizes[id.Key()]
			if !ok || old < cv {
				s.recvBufSizes[id.Key()] = cv
			}
			s.bufSizeLock.Unlock()
		default:
			err = os.ErrorString("invalid arguments to attach recv chan")
			s.LogError(err)
			s.Raise(err)
			return
		}
	}
	if s.async && ch.Cap() != UnlimitedBuffer && !internalChan {
		//for async router, external recv chans must have unlimited buffering,
		//ie. Cap()==-1, all undelivered msgs will be buffered right before ext recv chans
		ch = &asyncChan{Channel: ch}
	}
	routCh = newRoutedChan(id, recverType, ch, s, bindChan)
	routCh.internalChan = internalChan
	err = s.attach(routCh)
	if err != nil {
		s.LogError(err)
		s.Raise(err)
	}
	return
}
Exemple #14
0
func (jm *jsonDemarshaler) Demarshal() (id Id, ctrlMsg interface{}, appMsg reflect.Value, err os.Error) {
	seedId := jm.proxy.router.seedId
	id, _ = seedId.Clone()
	if err = jm.Decode(id); err != nil {
		return
	}
	if id.Scope() == NumScope && id.Member() == NumMembership {
		return
	}
	switch id.SysIdIndex() {
	case ConnId, DisconnId, ErrorId:
		idc, _ := seedId.Clone()
		ctrlMsg = &ConnInfoMsg{Id: idc}
		err = jm.demarshalCtrlMsg(ctrlMsg)
	case ReadyId:
		idc, _ := seedId.Clone()
		ctrlMsg = &ConnReadyMsg{[]*ChanReadyInfo{&ChanReadyInfo{Id: idc}}}
		err = jm.demarshalCtrlMsg(ctrlMsg)
	case PubId, UnPubId, SubId, UnSubId:
		idc, _ := seedId.Clone()
		ctrlMsg = &IdChanInfoMsg{[]*IdChanInfo{&IdChanInfo{idc, nil, nil}}}
		err = jm.demarshalCtrlMsg(ctrlMsg)
	default: //appMsg
		chanType := jm.proxy.getExportRecvChanType(id)
		if chanType == nil {
			err = os.ErrorString(fmt.Sprintf("failed to find chanType for id %v", id))
			return
		}
		et := chanType.Elem()
		appMsg = reflect.MakeZero(et)
		var ptrT *reflect.PtrValue
		switch et := et.(type) {
		case *reflect.BoolType:
			ptrT = jm.ptrBool
			ptrT.PointTo(appMsg)
		case *reflect.IntType:
			ptrT = jm.ptrInt
			ptrT.PointTo(appMsg)
		case *reflect.FloatType:
			ptrT = jm.ptrFloat
			ptrT.PointTo(appMsg)
		case *reflect.StringType:
			ptrT = jm.ptrString
			ptrT.PointTo(appMsg)
		case *reflect.PtrType:
			sto := reflect.MakeZero(et.Elem())
			ptrT = appMsg.(*reflect.PtrValue)
			ptrT.PointTo(sto)
		default:
			err = os.ErrorString(fmt.Sprintf("invalid chanType for id %v", id))
			return
		}
		err = jm.Decode(ptrT.Interface())
	}
	return
}
// VerifyHostname checks that the peer certificate chain is valid for
// connecting to host.  If so, it returns nil; if not, it returns an os.Error
// describing the problem.
func (c *Conn) VerifyHostname(host string) os.Error {
	c.handshakeMutex.Lock()
	defer c.handshakeMutex.Unlock()
	if !c.isClient {
		return os.ErrorString("VerifyHostname called on TLS server connection")
	}
	if !c.handshakeComplete {
		return os.ErrorString("TLS handshake has not yet been performed")
	}
	return c.peerCertificates[0].VerifyHostname(host)
}
Exemple #16
0
func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err os.Error) {
	hashLen = hash.Size()
	if inLen != hashLen {
		return 0, nil, os.ErrorString("input must be hashed message")
	}
	prefix, ok := hashPrefixes[hash]
	if !ok {
		return 0, nil, os.ErrorString("unsupported hash function")
	}
	return
}
Exemple #17
0
// Compile compiles and links sourcefile and atomically renames the
// resulting binary to runfile.
func Compile(sourcefile, runfile string, useGd bool) (err os.Error) {

	pid := strconv.Itoa(os.Getpid())

	content, err := ioutil.ReadFile(sourcefile)
	if len(content) > 2 && content[0] == '#' && content[1] == '!' {
		content[0] = '/'
		content[1] = '/'
		sourcefile = runfile + "." + pid + ".go"
		ioutil.WriteFile(sourcefile, content, 0600)
		defer os.Remove(sourcefile)
	}

	bindir := filepath.Join(runtime.GOROOT(), "bin")
	if useGd {
		gd := filepath.Join(bindir, "mgd")
		if _, err := os.Stat(gd); err != nil {
			if gd, err = exec.LookPath("mgd"); err != nil {
				return os.ErrorString("can't find mgd")
			}
		}
		err = Exec([]string{gd, "-L", "_obj", ".", "-q", "-o", runfile})
		return err
	} else {
		n := TheChar()
		gc := filepath.Join(bindir, n+"g")
		ld := filepath.Join(bindir, n+"l")
		if _, err := os.Stat(gc); err != nil {
			if gc, err = exec.LookPath(n + "g"); err != nil {
				return os.ErrorString("can't find " + n + "g")
			}
		}
		if _, err := os.Stat(ld); err != nil {
			if ld, err = exec.LookPath(n + "l"); err != nil {
				return os.ErrorString("can't find " + n + "l")
			}
		}
		gcout := runfile + "." + pid + "." + n
		ldout := runfile + "." + pid
		err = Exec([]string{gc, "-o", gcout, sourcefile})
		if err != nil {
			return err
		}
		defer os.Remove(gcout)
		err = Exec([]string{ld, "-o", ldout, gcout})
		if err != nil {
			return err
		}
		return os.Rename(ldout, runfile)
	}
	panic("Unreachable code")
}
Exemple #18
0
// checkSimilarDistribution returns success if the mean and stddev of the
// two statsResults are similar.
func (this *statsResults) checkSimilarDistribution(expected *statsResults) os.Error {
	if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) {
		s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
		fmt.Println(s)
		return os.ErrorString(s)
	}
	if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) {
		s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
		fmt.Println(s)
		return os.ErrorString(s)
	}
	return nil
}
func (dec *Decoder) compileSingle(remoteId typeId, rt reflect.Type) (engine *decEngine, err os.Error) {
	engine = new(decEngine)
	engine.instr = make([]decInstr, 1) // one item
	name := rt.String()                // best we can do
	if !dec.compatibleType(rt, remoteId) {
		return nil, os.ErrorString("gob: wrong type received for local value " + name + ": " + dec.typeString(remoteId))
	}
	op, indir := dec.decOpFor(remoteId, rt, name)
	ovfl := os.ErrorString(`value for "` + name + `" out of range`)
	engine.instr[singletonField] = decInstr{op, singletonField, indir, 0, ovfl}
	engine.numInstr = 1
	return
}
Exemple #20
0
// parseAddress parses a single RFC 5322 address at the start of p.
func (p *addrParser) parseAddress() (addr *Address, err os.Error) {
	debug.Printf("parseAddress: %q", *p)
	p.skipSpace()
	if p.empty() {
		return nil, os.ErrorString("mail: no address")
	}

	// address = name-addr / addr-spec
	// TODO(dsymonds): Support parsing group address.

	// addr-spec has a more restricted grammar than name-addr,
	// so try parsing it first, and fallback to name-addr.
	// TODO(dsymonds): Is this really correct?
	spec, err := p.consumeAddrSpec()
	if err == nil {
		return &Address{
			Address: spec,
		}, err
	}
	debug.Printf("parseAddress: not an addr-spec: %v", err)
	debug.Printf("parseAddress: state is now %q", *p)

	// display-name
	var displayName string
	if p.peek() != '<' {
		displayName, err = p.consumePhrase()
		if err != nil {
			return nil, err
		}
	}
	debug.Printf("parseAddress: displayName=%q", displayName)

	// angle-addr = "<" addr-spec ">"
	p.skipSpace()
	if !p.consume('<') {
		return nil, os.ErrorString("mail: no angle-addr")
	}
	spec, err = p.consumeAddrSpec()
	if err != nil {
		return nil, err
	}
	if !p.consume('>') {
		return nil, os.ErrorString("mail: unclosed angle-addr")
	}
	debug.Printf("parseAddress: spec=%q", spec)

	return &Address{
		Name:    displayName,
		Address: spec,
	}, nil
}
Exemple #21
0
func getParams(req *jsonRequest, argTypes []reflect.Type) ([]reflect.Value, os.Error) {
	params := make([]*json.RawMessage, 0)
	err := json.Unmarshal(*req.Params, &params)

	if err != nil {
		return nil, err
	}

	if len(params) != len(argTypes) {
		return nil, os.ErrorString("Incorrect number of parameters.")
	}

	args := make([]reflect.Value, 0, len(argTypes))

	for i, argType := range argTypes {
		argPointerType := argType

		if argPointerType.Kind() == reflect.Ptr {
			argPointer := reflect.New(argType)
			err := json.Unmarshal(*params[i], argPointer.Interface())
			if err != nil {
				return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
			}
			args = append(args, reflect.Indirect(argPointer))
		} else {
			var arg reflect.Value
			var v interface{}
			err := json.Unmarshal(*params[i], &v)
			if err != nil {
				return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
			}
			value := reflect.ValueOf(v)
			if value.Type() == argType {
				arg = reflect.ValueOf(v)
			} else if value.Type().Kind() == reflect.Float32 || value.Type().Kind() == reflect.Float64 {
				if argType.Kind() == reflect.Int || argType.Kind() == reflect.Int8 ||
					argType.Kind() == reflect.Int16 || argType.Kind() == reflect.Int32 ||
					argType.Kind() == reflect.Int64 {
					arg = reflect.ValueOf(int(v.(float64)))
				} else {
					return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
				}
			} else {
				return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
			}
			args = append(args, reflect.Value(arg))
		}
	}
	return args, nil
}
Exemple #22
0
// Unmarshal deserializes data from in into the out value.  The out value
// must be a map or a pointer to a struct (or a pointer to a struct pointer).
// In the case of struct values, field names are mapped to the struct using
// the field tag as the key.  If the field has no tag, its lowercased name
// will be used as the default key.  Nil values are properly initialized
// when necessary.
//
// The target field types of out may not necessarily match the BSON values
// of the provided data.  If there is a sensible way to unmarshal the values
// into the Go types, they will be converted.  Otherwise, the incompatible
// values will be silently skipped.
func Unmarshal(in []byte, out interface{}) (err os.Error) {
	defer handleErr(&err)
	v := reflect.ValueOf(out)
	switch v.Kind() {
	case reflect.Map, reflect.Ptr:
		d := &decoder{in: in}
		d.readDocTo(v)
	case reflect.Struct:
		return os.ErrorString("Unmarshal can't deal with struct values. Use a pointer.")
	default:
		return os.ErrorString("Unmarshal needs a map or a pointer to a struct.")
	}
	return nil
}
Exemple #23
0
func (db *buttress) Attach(slot int, u *friend) os.Error {
	if _, present := db.recs[slot]; present {
		return os.ErrorString("db, slot busy")
	}
	if u.GetId() != nil {
		for _, f := range db.recs {
			if f.GetId() != nil && *f.GetId() == *u.GetId() {
				return os.ErrorString("db, Duplicate Id present")
			}
		}
	}
	u.Slot = slot
	db.recs[slot] = u
	return nil
}
Exemple #24
0
// Exec runs args[0] with args[1:] arguments and passes through
// stdout and stderr.
func Exec(args []string) os.Error {

	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	base := filepath.Base(args[0])
	if w, ok := err.(*os.Waitmsg); ok && w.ExitStatus() != 0 {
		return os.ErrorString(base + " exited with status " + strconv.Itoa(w.ExitStatus()))
	}
	if err != nil {
		return os.ErrorString("failed to run " + base + ": " + err.String())
	}
	return nil
}
func (ka *ecdheRSAKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg) ([]byte, os.Error) {
	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
		return nil, os.ErrorString("bad ClientKeyExchange")
	}
	x, y := ka.curve.Unmarshal(ckx.ciphertext[1:])
	if x == nil {
		return nil, os.ErrorString("bad ClientKeyExchange")
	}
	x, _ = ka.curve.ScalarMult(x, y, ka.privateKey)
	preMasterSecret := make([]byte, (ka.curve.BitSize+7)>>3)
	xBytes := x.Bytes()
	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)

	return preMasterSecret, nil
}
Exemple #26
0
// consumeAddrSpec parses a single RFC 5322 addr-spec at the start of p.
func (p *addrParser) consumeAddrSpec() (spec string, err os.Error) {
	debug.Printf("consumeAddrSpec: %q", *p)

	orig := *p
	defer func() {
		if err != nil {
			*p = orig
		}
	}()

	// local-part = dot-atom / quoted-string
	var localPart string
	p.skipSpace()
	if p.empty() {
		return "", os.ErrorString("mail: no addr-spec")
	}
	if p.peek() == '"' {
		// quoted-string
		debug.Printf("consumeAddrSpec: parsing quoted-string")
		localPart, err = p.consumeQuotedString()
	} else {
		// dot-atom
		debug.Printf("consumeAddrSpec: parsing dot-atom")
		localPart, err = p.consumeAtom(true)
	}
	if err != nil {
		debug.Printf("consumeAddrSpec: failed: %v", err)
		return "", err
	}

	if !p.consume('@') {
		return "", os.ErrorString("mail: missing @ in addr-spec")
	}

	// domain = dot-atom / domain-literal
	var domain string
	p.skipSpace()
	if p.empty() {
		return "", os.ErrorString("mail: no domain in addr-spec")
	}
	// TODO(dsymonds): Handle domain-literal
	domain, err = p.consumeAtom(true)
	if err != nil {
		return "", err
	}

	return localPart + "@" + domain, nil
}
// EncodeValue transmits the data item represented by the reflection value,
// guaranteeing that all necessary type information has been transmitted first.
func (enc *Encoder) EncodeValue(value reflect.Value) os.Error {
	// Make sure we're single-threaded through here, so multiple
	// goroutines can share an encoder.
	enc.mutex.Lock()
	defer enc.mutex.Unlock()

	enc.err = nil
	rt, _ := indirect(value.Type())

	// Sanity check only: encoder should never come in with data present.
	if enc.state.b.Len() > 0 || enc.countState.b.Len() > 0 {
		enc.err = os.ErrorString("encoder: buffer not empty")
		return enc.err
	}

	enc.sendTypeDescriptor(rt)
	if enc.err != nil {
		return enc.err
	}

	// Encode the object.
	err := enc.encode(enc.state.b, value)
	if err != nil {
		enc.setError(err)
	} else {
		enc.send()
	}

	return enc.err
}
Exemple #28
0
// applyRelocations applies relocations to dst. rels is a relocations section
// in RELA format.
func (f *File) applyRelocations(dst []byte, rels []byte) os.Error {
	if f.Class == ELFCLASS64 && f.Machine == EM_X86_64 {
		return f.applyRelocationsAMD64(dst, rels)
	}

	return os.ErrorString("not implemented")
}
Exemple #29
0
// decodeTypeSequence parses:
// TypeSequence
//	(TypeDefinition DelimitedTypeDefinition*)?
// and returns the type id of the next value.  It returns -1 at
// EOF.  Upon return, the remainder of dec.buf is the value to be
// decoded.  If this is an interface value, it can be ignored by
// simply resetting that buffer.
func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId {
	for dec.err == nil {
		if dec.buf.Len() == 0 {
			if !dec.recvMessage() {
				break
			}
		}
		// Receive a type id.
		id := typeId(dec.nextInt())
		if id >= 0 {
			// Value follows.
			return id
		}
		// Type definition for (-id) follows.
		dec.recvType(-id)
		// When decoding an interface, after a type there may be a
		// DelimitedValue still in the buffer.  Skip its count.
		// (Alternatively, the buffer is empty and the byte count
		// will be absorbed by recvMessage.)
		if dec.buf.Len() > 0 {
			if !isInterface {
				dec.err = os.ErrorString("extra data in buffer")
				break
			}
			dec.nextUint()
		}
	}
	return -1
}
// If src != nil, readSource converts src to a []byte if possible;
// otherwise it returns an error. If src == nil, readSource returns
// the result of reading the file specified by filename.
//
func readSource(filename string, src interface{}) ([]byte, os.Error) {
	if src != nil {
		switch s := src.(type) {
		case string:
			return strings.Bytes(s), nil
		case []byte:
			return s, nil
		case *bytes.Buffer:
			// is io.Reader, but src is already available in []byte form
			if s != nil {
				return s.Bytes(), nil
			}
		case io.Reader:
			var buf bytes.Buffer
			_, err := io.Copy(&buf, s)
			if err != nil {
				return nil, err
			}
			return buf.Bytes(), nil
		default:
			return nil, os.ErrorString("invalid source")
		}
	}

	return io.ReadFile(filename)
}