// socks5ReadCommand reads a SOCKS5 client command and parses out the relevant
// fields into a SocksRequest.  Only CMD_CONNECT is supported.
438663
func socks5ReadCommand(rw *bufio.ReadWriter, req *SocksRequest) (err error) {
	sendErrResp := func(reason byte) {
		// Swallow errors that occur when writing/flushing the response,
		// connection will be closed anyway.
		sendSocks5ResponseRejected(rw, reason)
		socksFlushBuffers(rw)
	}

	// Validate the fixed parts of the command message.
	if err = socksReadByteVerify(rw.Reader, "version", socks5Version); err != nil {
		sendErrResp(SocksRepGeneralFailure)
		err = newTemporaryNetError("socks5ReadCommand: %s", err)
		return
	}
	if err = socksReadByteVerify(rw.Reader, "command", socksCmdConnect); err != nil {
		sendErrResp(SocksRepCommandNotSupported)
		err = newTemporaryNetError("socks5ReadCommand: %s", err)
		return
	}
	if err = socksReadByteVerify(rw.Reader, "reserved", socksReserved); err != nil {
		sendErrResp(SocksRepGeneralFailure)
		err = newTemporaryNetError("socks5ReadCommand: %s", err)
		return
	}

	// Read the destination address/port.
	// XXX: This should probably eventually send socks 5 error messages instead
	// of rudely closing connections on invalid addresses.
	var atype byte
	if atype, err = socksReadByte(rw.Reader); err != nil {
		err = newTemporaryNetError("socks5ReadCommand: Failed to read address type: %s", err)
		return
	}
	var host string
	switch atype {
	case socksAtypeV4:
		var addr []byte
		if addr, err = socksReadBytes(rw.Reader, net.IPv4len); err != nil {
			err = newTemporaryNetError("socks5ReadCommand: Failed to read IPv4 address: %s", err)
			return
		}
		host = net.IPv4(addr[0], addr[1], addr[2], addr[3]).String()

	case socksAtypeDomainName:
		var alen byte
		if alen, err = socksReadByte(rw.Reader); err != nil {
			err = newTemporaryNetError("socks5ReadCommand: Failed to read domain name length: %s", err)
			return
		}
		if alen == 0 {
			err = newTemporaryNetError("socks5ReadCommand: SOCKS request had domain name with 0 length")
			return
		}
		var addr []byte
		if addr, err = socksReadBytes(rw.Reader, int(alen)); err != nil {
			err = newTemporaryNetError("socks5ReadCommand: Failed to read domain name: %s", err)
			return
		}
		host = string(addr)

	case socksAtypeV6:
		var rawAddr []byte
		if rawAddr, err = socksReadBytes(rw.Reader, net.IPv6len); err != nil {
			err = newTemporaryNetError("socks5ReadCommand: Failed to read IPv6 address: %s", err)
			return
		}
		addr := make(net.IP, net.IPv6len)
		copy(addr[:], rawAddr[:])
		host = fmt.Sprintf("[%s]", addr.String())

	default:
		sendErrResp(SocksRepAddressNotSupported)
		err = newTemporaryNetError("socks5ReadCommand: SOCKS request had unsupported address type 0x%02x", atype)
		return
	}
	var rawPort []byte
	if rawPort, err = socksReadBytes(rw.Reader, 2); err != nil {
		err = newTemporaryNetError("socks5ReadCommand: Failed to read port number: %s", err)
		return
	}
	port := int(rawPort[0])<<8 | int(rawPort[1])<<0

	if err = socksFlushBuffers(rw); err != nil {
		err = newTemporaryNetError("socks5ReadCommand: Failed to flush buffers: %s", err)
		return
	}

	req.Target = fmt.Sprintf("%s:%d", host, port)
	return
}
568836
func batchReadHeaders(
	client *as.Client,
	keyPrefix string,
	size int,
) {
	// Batch gets into one call.
	keys := make([]*as.Key, size)
	for i := 0; i < size; i++ {
		keys[i], _ = as.NewKey(*shared.Namespace, *shared.Set, keyPrefix+strconv.Itoa(i+1))
	}

	records, err := client.BatchGetHeader(nil, keys)
	shared.PanicOnError(err)

	for i := 0; i < len(records); i++ {
		key := keys[i]
		record := records[i]
		level := asl.ERR
		generation := uint32(0)
		expiration := uint32(0)

		if record != nil && (record.Generation > 0 || record.Expiration > 0) {
			level = asl.INFO
			generation = record.Generation
			expiration = record.Expiration
		}
		asl.Logger.LogAtLevel(level, "Record: ns=%s set=%s key=%s generation=%d expiration=%d",
			key.Namespace(), key.SetName(), key.Value(), generation, expiration)
	}

	if len(records) != size {
		log.Fatalf("Record size mismatch. Expected %d. Received %d.", size, len(records))
	}
}
1156597
func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) {
	s := &socks5{
		network: network,
		addr:    addr,
		forward: forward,
	}
	if auth != nil {
		s.user = auth.User
		s.password = auth.Password
	}

	return s, nil
}
1010032
func (smb SMBus) Read_byte_data(cmd byte) (byte, error) {
	smb.Set_addr(smb.addr)
	ret, err := C.i2c_smbus_read_byte_data(C.int(smb.bus.Fd()), C.__u8(cmd))
	if err != nil {
		ret = 0
	}
	return byte(ret & 0x0FF), err
}
302610
func (c *Conn) SetReadBuffer(bytes int) error {
	conn, ok := c.sock.(bufferSetter)
	if !ok {
		return notSupported("set-read-buffer")
	}

	return newOpError("set-read-buffer", conn.SetReadBuffer(bytes))
}
1335754
func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) {
	switch network {
	case "tcp", "tcp6", "tcp4":
	default:
		return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network)
	}

	conn, err := s.forward.Dial(s.network, s.addr)
	if err != nil {
		return nil, err
	}
	if err := s.connect(conn, addr); err != nil {
		conn.Close()
		return nil, err
	}
	return conn, nil
}
1171241
func (c *Command) readConfig() *Config {
	var cmdConfig Config
	var configFiles []string
	var tags []string
	var retryInterval string
	var broadcastTimeout string
	var disableCompression bool

	cmdFlags := flag.NewFlagSet("agent", flag.ContinueOnError)
	cmdFlags.Usage = func() { c.Ui.Output(c.Help()) }
	cmdFlags.StringVar(&cmdConfig.BindAddr, "bind", "", "address to bind listeners to")
	cmdFlags.StringVar(&cmdConfig.AdvertiseAddr, "advertise", "", "address to advertise to cluster")
	cmdFlags.Var((*AppendSliceValue)(&configFiles), "config-file",
		"json file to read config from")
	cmdFlags.Var((*AppendSliceValue)(&configFiles), "config-dir",
		"directory of json files to read")
	cmdFlags.StringVar(&cmdConfig.EncryptKey, "encrypt", "", "encryption key")
	cmdFlags.StringVar(&cmdConfig.KeyringFile, "keyring-file", "", "path to the keyring file")
	cmdFlags.Var((*AppendSliceValue)(&cmdConfig.EventHandlers), "event-handler",
		"command to execute when events occur")
	cmdFlags.Var((*AppendSliceValue)(&cmdConfig.StartJoin), "join",
		"address of agent to join on startup")
	cmdFlags.BoolVar(&cmdConfig.ReplayOnJoin, "replay", false,
		"replay events for startup join")
	cmdFlags.StringVar(&cmdConfig.LogLevel, "log-level", "", "log level")
	cmdFlags.StringVar(&cmdConfig.NodeName, "node", "", "node name")
	cmdFlags.IntVar(&cmdConfig.Protocol, "protocol", -1, "protocol version")
	cmdFlags.StringVar(&cmdConfig.Role, "role", "", "role name")
	cmdFlags.StringVar(&cmdConfig.RPCAddr, "rpc-addr", "",
		"address to bind RPC listener to")
	cmdFlags.StringVar(&cmdConfig.Profile, "profile", "", "timing profile to use (lan, wan, local)")
	cmdFlags.StringVar(&cmdConfig.SnapshotPath, "snapshot", "", "path to the snapshot file")
	cmdFlags.Var((*AppendSliceValue)(&tags), "tag",
		"tag pair, specified as key=value")
	cmdFlags.StringVar(&cmdConfig.Discover, "discover", "", "mDNS discovery name")
	cmdFlags.StringVar(&cmdConfig.Interface, "iface", "", "interface to bind to")
	cmdFlags.StringVar(&cmdConfig.TagsFile, "tags-file", "", "tag persistence file")
	cmdFlags.BoolVar(&cmdConfig.EnableSyslog, "syslog", false,
		"enable logging to syslog facility")
	cmdFlags.Var((*AppendSliceValue)(&cmdConfig.RetryJoin), "retry-join",
		"address of agent to join on startup with retry")
	cmdFlags.IntVar(&cmdConfig.RetryMaxAttempts, "retry-max", 0, "maximum retry join attempts")
	cmdFlags.StringVar(&retryInterval, "retry-interval", "", "retry join interval")
	cmdFlags.BoolVar(&cmdConfig.RejoinAfterLeave, "rejoin", false,
		"enable re-joining after a previous leave")

	cmdFlags.BoolVar(
		&disableCompression,
		"disable-compression",
		false,
		"disable message compression for broadcasting events",
	)

	cmdFlags.StringVar(&broadcastTimeout, "broadcast-timeout", "", "timeout for broadcast messages")
	if err := cmdFlags.Parse(c.args); err != nil {
		return nil
	}

	cmdConfig.EnableCompression = !disableCompression

	// Parse any command line tag values
	tagValues, err := UnmarshalTags(tags)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error: %s", err))
		return nil
	}
	cmdConfig.Tags = tagValues

	// Decode the retry interval if given
	if retryInterval != "" {
		dur, err := time.ParseDuration(retryInterval)
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error: %s", err))
			return nil
		}
		cmdConfig.RetryInterval = dur
	}

	// Decode the broadcast timeout if given
	if broadcastTimeout != "" {
		dur, err := time.ParseDuration(broadcastTimeout)
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error: %s", err))
			return nil
		}
		cmdConfig.BroadcastTimeout = dur
	}

	config := DefaultConfig()
	if len(configFiles) > 0 {
		fileConfig, err := ReadConfigPaths(configFiles)
		if err != nil {
			c.Ui.Error(err.Error())
			return nil
		}

		config = MergeConfig(config, fileConfig)
	}

	config = MergeConfig(config, &cmdConfig)

	if config.NodeName == "" {
		hostname, err := os.Hostname()
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error determining hostname: %s", err))
			return nil
		}
		config.NodeName = hostname
	}

	eventScripts := config.EventScripts()
	for _, script := range eventScripts {
		if !script.Valid() {
			c.Ui.Error(fmt.Sprintf("Invalid event script: %s", script.String()))
			return nil
		}
	}

	// Check for a valid interface
	if _, err := config.NetworkInterface(); err != nil {
		c.Ui.Error(fmt.Sprintf("Invalid network interface: %s", err))
		return nil
	}

	// Backward compatibility hack for 'Role'
	if config.Role != "" {
		c.Ui.Output("Deprecation warning: 'Role' has been replaced with 'Tags'")
		config.Tags["role"] = config.Role
	}

	// Check for sane retry interval
	if config.RetryInterval < minRetryInterval {
		config.RetryInterval = minRetryInterval
		c.Ui.Output(fmt.Sprintf("Warning: 'RetryInterval' is too low. Setting to %v", config.RetryInterval))
	}

	// Check for sane broadcast timeout
	if config.BroadcastTimeout < minBroadcastTimeout {
		config.BroadcastTimeout = minBroadcastTimeout
		c.Ui.Output(fmt.Sprintf("Warning: 'BroadcastTimeout' is too low. Setting to %v",
			config.BroadcastTimeout))
	}

	// Check snapshot file is provided if we have RejoinAfterLeave
	if config.RejoinAfterLeave && config.SnapshotPath == "" {
		c.Ui.Output("Warning: 'RejoinAfterLeave' enabled without snapshot file")
	}

	return config
}
1201049
func (c *SocketConnection) ReadMessage() (*Message, error) {
	Debug("Waiting for connection message to be received ...")

	select {
	case err := <-c.err:
		return nil, err
	case msg := <-c.m:
		return msg, nil
	}
}
1064646
func (sp *ServerPeer) OnRead(_ *peer.Peer, bytesRead int, msg wire.Message,
	err error) {

	sp.server.AddBytesReceived(uint64(bytesRead))

	// Send a message to each subscriber. Each message gets its own
	// goroutine to prevent blocking on the mutex lock.
	// TODO: Flood control.
	sp.mtxSubscribers.RLock()
	defer sp.mtxSubscribers.RUnlock()
	for subscription := range sp.recvSubscribers {
		go func(subscription spMsgSubscription) {
			select {
			case <-subscription.quitChan:
			case subscription.msgChan <- spMsg{
				msg: msg,
				sp:  sp,
			}:
			}
		}(subscription)
	}
}
35629
func socksDialerFunction(u *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
	var auth *proxy.Auth
	if u.User != nil {
		auth = new(proxy.Auth)
		auth.User = u.User.Username()
		if p, ok := u.User.Password(); ok {
			auth.Password = p
		}
	}

	return proxy.SOCKS5("tcp", u.Host, auth, forward)
}
34685
func (m *Md5Reader) Md5() string {
	return hex.EncodeToString(m.hash.Sum(nil))
}
992174
func newConnectCmd() *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "connect -dir <path> -server <server> -user <name>",
		ShortDesc: "connects to a swarming server",
		LongDesc:  "Connects to a Swarming server.",
		CommandRun: func() subcommands.CommandRun {
			cmd := &connectCmd{}
			cmd.Initialize()
			cmd.Flags.StringVar(&cmd.dir, "dir", "", "Path to use as the Swarming bot directory.")
			cmd.Flags.StringVar(&cmd.provider, "provider", "", "Provider server URL to retrieve Swarming server URL from.")
			cmd.Flags.StringVar(&cmd.server, "server", "", "Deprecated. Use -provider.")
			cmd.Flags.StringVar(&cmd.user, "user", "", "Name of the local user to start the Swarming bot process as.")
			return cmd
		},
	}
}
1053438
func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) {
	s := &proxy_socks5{
		network: network,
		addr:    addr,
		forward: forward,
	}
	if auth != nil {
		s.user = auth.User
		s.password = auth.Password
	}

	return s, nil
}
844920
func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {
	cmd.Stdin = input
	pipeR, pipeW := io.Pipe()
	cmd.Stdout = pipeW
	var errBuf bytes.Buffer
	cmd.Stderr = &errBuf

	// Run the command and return the pipe
	if err := cmd.Start(); err != nil {
		return nil, err
	}

	// Copy stdout to the returned pipe
	go func() {
		if err := cmd.Wait(); err != nil {
			pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String()))
		} else {
			pipeW.Close()
		}
	}()

	return pipeR, nil
}
1073142
func socks5Handshake(rw *bufio.ReadWriter) (req SocksRequest, err error) {
	// Negotiate the authentication method.
	var method byte
	if method, err = socks5NegotiateAuth(rw); err != nil {
		return
	}

	// Authenticate the client.
	if err = socks5Authenticate(rw, method, &req); err != nil {
		return
	}

	// Read the command.
	err = socks5ReadCommand(rw, &req)
	return
}
1025941
func (s *Socket) ReadBINC(v interface{}) (err error) {
	_, r, err := s.NextReader()
	if err != nil {
		return err
	}
	return codec.NewDecoder(r, &bh).Decode(v)
}
1218257
func (s *stream) readCommand() (dota.EDemoCommands, error) {
	c, err := s.readVarUint32()
	return dota.EDemoCommands(c), err
}