Example #1
0
func (v *IPv4Matcher) Apply(ctx context.Context) bool {
	ips := make([]net.IP, 0, 4)
	if resolveIPs, ok := proxy.ResolvedIPsFromContext(ctx); ok {
		for _, rip := range resolveIPs {
			if !rip.Family().IsIPv4() {
				continue
			}
			ips = append(ips, rip.IP())
		}
	}

	var dest v2net.Destination
	if v.onSource {
		dest = proxy.SourceFromContext(ctx)
	} else {
		dest = proxy.DestinationFromContext(ctx)
	}

	if dest.IsValid() && dest.Address.Family().IsIPv4() {
		ips = append(ips, dest.Address.IP())
	}

	for _, ip := range ips {
		if v.ipv4net.Contains(ip) {
			return true
		}
	}
	return false
}
Example #2
0
func (v *PlainDomainMatcher) Apply(ctx context.Context) bool {
	dest := proxy.DestinationFromContext(ctx)
	if !dest.Address.Family().IsDomain() {
		return false
	}
	domain := dest.Address.Domain()
	return strings.Contains(domain, v.pattern)
}
Example #3
0
func (v *RegexpDomainMatcher) Apply(ctx context.Context) bool {
	dest := proxy.DestinationFromContext(ctx)
	if !dest.Address.Family().IsDomain() {
		return false
	}
	domain := dest.Address.Domain()
	return v.pattern.MatchString(strings.ToLower(domain))
}
Example #4
0
func (v *Router) TakeDetour(ctx context.Context) (string, error) {
	for _, rule := range v.rules {
		if rule.Apply(ctx) {
			return rule.Tag, nil
		}
	}

	dest := proxy.DestinationFromContext(ctx)
	if v.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() {
		log.Info("Router: Looking up IP for ", dest)
		ipDests := v.resolveIP(dest)
		if ipDests != nil {
			ctx = proxy.ContextWithResolveIPs(ctx, ipDests)
			for _, rule := range v.rules {
				if rule.Apply(ctx) {
					return rule.Tag, nil
				}
			}
		}
	}

	return "", ErrNoRuleApplicable
}
Example #5
0
func (v *DefaultDispatcher) DispatchToOutbound(ctx context.Context) ray.InboundRay {
	dispatcher := v.ohm.GetDefaultHandler()
	destination := proxy.DestinationFromContext(ctx)
	if !destination.IsValid() {
		panic("Dispatcher: Invalid destination.")
	}

	if v.router != nil {
		if tag, err := v.router.TakeDetour(ctx); err == nil {
			if handler := v.ohm.GetHandler(tag); handler != nil {
				log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].")
				dispatcher = handler
			} else {
				log.Warning("DefaultDispatcher: Nonexisting tag: ", tag)
			}
		} else {
			log.Info("DefaultDispatcher: Default route for ", destination)
		}
	}

	direct := ray.NewRay(ctx)
	var waitFunc func() error
	if allowPassiveConnection, ok := proxy.AllowPassiveConnectionFromContext(ctx); ok && allowPassiveConnection {
		waitFunc = noOpWait()
	} else {
		wdi := &waitDataInspector{
			hasData: make(chan bool, 1),
		}
		direct.AddInspector(wdi)
		waitFunc = waitForData(wdi)
	}

	go v.waitAndDispatch(ctx, waitFunc, direct, dispatcher)

	return direct
}
Example #6
0
func (v *NetworkMatcher) Apply(ctx context.Context) bool {
	dest := proxy.DestinationFromContext(ctx)
	return v.network.HasNetwork(dest.Network)
}
Example #7
0
func (v *PortMatcher) Apply(ctx context.Context) bool {
	dest := proxy.DestinationFromContext(ctx)
	return v.port.Contains(dest.Port)
}
Example #8
0
// Process implements OutboundHandler.Process().
func (v *Client) Process(ctx context.Context, outboundRay ray.OutboundRay) error {
	destination := proxy.DestinationFromContext(ctx)
	network := destination.Network

	var server *protocol.ServerSpec
	var conn internet.Connection

	dialer := proxy.DialerFromContext(ctx)
	err := retry.ExponentialBackoff(5, 100).On(func() error {
		server = v.serverPicker.PickServer()
		dest := server.Destination()
		dest.Network = network
		rawConn, err := dialer.Dial(ctx, dest)
		if err != nil {
			return err
		}
		conn = rawConn

		return nil
	})
	if err != nil {
		log.Warning("Shadowsocks|Client: Failed to find an available destination:", err)
		return err
	}
	log.Info("Shadowsocks|Client: Tunneling request to ", destination, " via ", server.Destination())

	conn.SetReusable(false)

	request := &protocol.RequestHeader{
		Version: Version,
		Address: destination.Address,
		Port:    destination.Port,
	}
	if destination.Network == net.Network_TCP {
		request.Command = protocol.RequestCommandTCP
	} else {
		request.Command = protocol.RequestCommandUDP
	}

	user := server.PickUser()
	rawAccount, err := user.GetTypedAccount()
	if err != nil {
		log.Warning("Shadowsocks|Client: Failed to get a valid user account: ", err)
		return err
	}
	account := rawAccount.(*ShadowsocksAccount)
	request.User = user

	if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
		request.Option |= RequestOptionOneTimeAuth
	}

	if request.Command == protocol.RequestCommandTCP {
		bufferedWriter := bufio.NewWriter(conn)
		bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
		if err != nil {
			log.Info("Shadowsocks|Client: Failed to write request: ", err)
			return err
		}

		bufferedWriter.SetBuffered(false)

		requestDone := signal.ExecuteAsync(func() error {
			if err := buf.PipeUntilEOF(outboundRay.OutboundInput(), bodyWriter); err != nil {
				return err
			}
			return nil
		})

		responseDone := signal.ExecuteAsync(func() error {
			defer outboundRay.OutboundOutput().Close()

			responseReader, err := ReadTCPResponse(user, conn)
			if err != nil {
				return err
			}

			if err := buf.PipeUntilEOF(responseReader, outboundRay.OutboundOutput()); err != nil {
				return err
			}

			return nil
		})

		if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
			log.Info("Shadowsocks|Client: Connection ends with ", err)
			outboundRay.OutboundInput().CloseError()
			outboundRay.OutboundOutput().CloseError()
			return err
		}

		return nil
	}

	if request.Command == protocol.RequestCommandUDP {

		writer := &UDPWriter{
			Writer:  conn,
			Request: request,
		}

		requestDone := signal.ExecuteAsync(func() error {
			if err := buf.PipeUntilEOF(outboundRay.OutboundInput(), writer); err != nil {
				log.Info("Shadowsocks|Client: Failed to transport all UDP request: ", err)
				return err
			}
			return nil
		})

		timedReader := net.NewTimeOutReader(16, conn)

		responseDone := signal.ExecuteAsync(func() error {
			defer outboundRay.OutboundOutput().Close()

			reader := &UDPReader{
				Reader: timedReader,
				User:   user,
			}

			if err := buf.PipeUntilEOF(reader, outboundRay.OutboundOutput()); err != nil {
				log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err)
				return err
			}
			return nil
		})

		if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
			log.Info("Shadowsocks|Client: Connection ends with ", err)
			outboundRay.OutboundInput().CloseError()
			outboundRay.OutboundOutput().CloseError()
			return err
		}

		return nil
	}

	return nil
}
Example #9
0
func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay) error {
	destination := proxy.DestinationFromContext(ctx)
	if v.destOverride != nil {
		server := v.destOverride.Server
		destination = net.Destination{
			Network: destination.Network,
			Address: server.Address.AsAddress(),
			Port:    net.Port(server.Port),
		}
	}
	log.Info("Freedom: Opening connection to ", destination)

	input := outboundRay.OutboundInput()
	output := outboundRay.OutboundOutput()

	var conn internet.Connection
	if v.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
		destination = v.ResolveIP(destination)
	}

	dialer := proxy.DialerFromContext(ctx)
	err := retry.ExponentialBackoff(5, 100).On(func() error {
		rawConn, err := dialer.Dial(ctx, destination)
		if err != nil {
			return err
		}
		conn = rawConn
		return nil
	})
	if err != nil {
		log.Warning("Freedom: Failed to open connection to ", destination, ": ", err)
		return err
	}
	defer conn.Close()

	conn.SetReusable(false)

	requestDone := signal.ExecuteAsync(func() error {
		v2writer := buf.NewWriter(conn)
		if err := buf.PipeUntilEOF(input, v2writer); err != nil {
			return err
		}
		return nil
	})

	var reader io.Reader = conn

	timeout := v.timeout
	if destination.Network == net.Network_UDP {
		timeout = 16
	}
	if timeout > 0 {
		reader = net.NewTimeOutReader(timeout /* seconds */, conn)
	}

	responseDone := signal.ExecuteAsync(func() error {
		defer output.Close()

		v2reader := buf.NewReader(reader)
		if err := buf.PipeUntilEOF(v2reader, output); err != nil {
			return err
		}
		return nil
	})

	if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
		log.Info("Freedom: Connection ending with ", err)
		input.CloseError()
		output.CloseError()
		return err
	}

	return nil
}
Example #10
0
// Dispatch implements OutboundHandler.Dispatch().
func (v *VMessOutboundHandler) Process(ctx context.Context, outboundRay ray.OutboundRay) error {
	var rec *protocol.ServerSpec
	var conn internet.Connection

	dialer := proxy.DialerFromContext(ctx)
	err := retry.ExponentialBackoff(5, 100).On(func() error {
		rec = v.serverPicker.PickServer()
		rawConn, err := dialer.Dial(ctx, rec.Destination())
		if err != nil {
			return err
		}
		conn = rawConn

		return nil
	})
	if err != nil {
		log.Warning("VMess|Outbound: Failed to find an available destination:", err)
		return err
	}
	defer conn.Close()

	target := proxy.DestinationFromContext(ctx)
	log.Info("VMess|Outbound: Tunneling request to ", target, " via ", rec.Destination())

	command := protocol.RequestCommandTCP
	if target.Network == net.Network_UDP {
		command = protocol.RequestCommandUDP
	}
	request := &protocol.RequestHeader{
		Version: encoding.Version,
		User:    rec.PickUser(),
		Command: command,
		Address: target.Address,
		Port:    target.Port,
		Option:  protocol.RequestOptionChunkStream,
	}

	rawAccount, err := request.User.GetTypedAccount()
	if err != nil {
		log.Warning("VMess|Outbound: Failed to get user account: ", err)
		return err
	}
	account := rawAccount.(*vmess.InternalAccount)
	request.Security = account.Security

	conn.SetReusable(true)
	if conn.Reusable() { // Conn reuse may be disabled on transportation layer
		request.Option.Set(protocol.RequestOptionConnectionReuse)
	}

	input := outboundRay.OutboundInput()
	output := outboundRay.OutboundOutput()

	session := encoding.NewClientSession(protocol.DefaultIDHash)

	requestDone := signal.ExecuteAsync(func() error {
		writer := bufio.NewWriter(conn)
		session.EncodeRequestHeader(request, writer)

		bodyWriter := session.EncodeRequestBody(request, writer)
		firstPayload, err := input.ReadTimeout(time.Millisecond * 500)
		if err != nil && err != ray.ErrReadTimeout {
			return errors.Base(err).Message("VMess|Outbound: Failed to get first payload.")
		}
		if !firstPayload.IsEmpty() {
			if err := bodyWriter.Write(firstPayload); err != nil {
				return errors.Base(err).Message("VMess|Outbound: Failed to write first payload.")
			}
			firstPayload.Release()
		}

		writer.SetBuffered(false)

		if err := buf.PipeUntilEOF(input, bodyWriter); err != nil {
			return err
		}

		if request.Option.Has(protocol.RequestOptionChunkStream) {
			if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
				return err
			}
		}
		return nil
	})

	responseDone := signal.ExecuteAsync(func() error {
		defer output.Close()

		reader := bufio.NewReader(conn)
		header, err := session.DecodeResponseHeader(reader)
		if err != nil {
			return err
		}
		v.handleCommand(rec.Destination(), header.Command)

		conn.SetReusable(header.Option.Has(protocol.ResponseOptionConnectionReuse))

		reader.SetBuffered(false)
		bodyReader := session.DecodeResponseBody(request, reader)
		if err := buf.PipeUntilEOF(bodyReader, output); err != nil {
			return err
		}

		return nil
	})

	if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
		log.Info("VMess|Outbound: Connection ending with ", err)
		conn.SetReusable(false)
		input.CloseError()
		output.CloseError()
		return err
	}

	return nil
}
Example #11
0
func (c *Client) Process(ctx context.Context, ray ray.OutboundRay) error {
	destination := proxy.DestinationFromContext(ctx)

	var server *protocol.ServerSpec
	var conn internet.Connection

	dialer := proxy.DialerFromContext(ctx)
	err := retry.ExponentialBackoff(5, 100).On(func() error {
		server = c.serverPicker.PickServer()
		dest := server.Destination()
		rawConn, err := dialer.Dial(ctx, dest)
		if err != nil {
			return err
		}
		conn = rawConn

		return nil
	})

	if err != nil {
		log.Warning("Socks|Client: Failed to find an available destination.")
		return err
	}

	defer conn.Close()
	conn.SetReusable(false)

	request := &protocol.RequestHeader{
		Version: socks5Version,
		Command: protocol.RequestCommandTCP,
		Address: destination.Address,
		Port:    destination.Port,
	}
	if destination.Network == net.Network_UDP {
		request.Command = protocol.RequestCommandUDP
	}

	user := server.PickUser()
	if user != nil {
		request.User = user
	}

	udpRequest, err := ClientHandshake(request, conn, conn)
	if err != nil {
		log.Warning("Socks|Client: Failed to establish connection to server: ", err)
		return err
	}

	var requestFunc func() error
	var responseFunc func() error
	if request.Command == protocol.RequestCommandTCP {
		requestFunc = func() error {
			return buf.PipeUntilEOF(ray.OutboundInput(), buf.NewWriter(conn))
		}
		responseFunc = func() error {
			defer ray.OutboundOutput().Close()
			return buf.PipeUntilEOF(buf.NewReader(conn), ray.OutboundOutput())
		}
	} else if request.Command == protocol.RequestCommandUDP {
		udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
		if err != nil {
			log.Info("Socks|Client: Failed to create UDP connection: ", err)
			return err
		}
		defer udpConn.Close()
		requestFunc = func() error {
			return buf.PipeUntilEOF(ray.OutboundInput(), &UDPWriter{request: request, writer: udpConn})
		}
		responseFunc = func() error {
			defer ray.OutboundOutput().Close()
			reader := &UDPReader{reader: net.NewTimeOutReader(16, udpConn)}
			return buf.PipeUntilEOF(reader, ray.OutboundOutput())
		}
	}

	requestDone := signal.ExecuteAsync(requestFunc)
	responseDone := signal.ExecuteAsync(responseFunc)
	if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
		log.Info("Socks|Client: Connection ends with ", err)
		ray.OutboundInput().CloseError()
		ray.OutboundOutput().CloseError()
		return err
	}

	return nil
}