context.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package proxy
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. type key int
  7. const (
  8. sourceKey key = iota
  9. targetKey
  10. originalTargetKey
  11. inboundEntryPointKey
  12. inboundTagKey
  13. resolvedIPsKey
  14. )
  15. // ContextWithSource creates a new context with given source.
  16. func ContextWithSource(ctx context.Context, src net.Destination) context.Context {
  17. return context.WithValue(ctx, sourceKey, src)
  18. }
  19. // SourceFromContext retreives source from the given context.
  20. func SourceFromContext(ctx context.Context) (net.Destination, bool) {
  21. v, ok := ctx.Value(sourceKey).(net.Destination)
  22. return v, ok
  23. }
  24. func ContextWithOriginalTarget(ctx context.Context, dest net.Destination) context.Context {
  25. return context.WithValue(ctx, originalTargetKey, dest)
  26. }
  27. func OriginalTargetFromContext(ctx context.Context) (net.Destination, bool) {
  28. v, ok := ctx.Value(originalTargetKey).(net.Destination)
  29. return v, ok
  30. }
  31. func ContextWithTarget(ctx context.Context, dest net.Destination) context.Context {
  32. return context.WithValue(ctx, targetKey, dest)
  33. }
  34. func TargetFromContext(ctx context.Context) (net.Destination, bool) {
  35. v, ok := ctx.Value(targetKey).(net.Destination)
  36. return v, ok
  37. }
  38. func ContextWithInboundEntryPoint(ctx context.Context, dest net.Destination) context.Context {
  39. return context.WithValue(ctx, inboundEntryPointKey, dest)
  40. }
  41. func InboundEntryPointFromContext(ctx context.Context) (net.Destination, bool) {
  42. v, ok := ctx.Value(inboundEntryPointKey).(net.Destination)
  43. return v, ok
  44. }
  45. func ContextWithInboundTag(ctx context.Context, tag string) context.Context {
  46. return context.WithValue(ctx, inboundTagKey, tag)
  47. }
  48. func InboundTagFromContext(ctx context.Context) (string, bool) {
  49. v, ok := ctx.Value(inboundTagKey).(string)
  50. return v, ok
  51. }
  52. type IPResolver interface {
  53. Resolve() []net.Address
  54. }
  55. func ContextWithResolveIPs(ctx context.Context, f IPResolver) context.Context {
  56. return context.WithValue(ctx, resolvedIPsKey, f)
  57. }
  58. func ResolvedIPsFromContext(ctx context.Context) (IPResolver, bool) {
  59. ips, ok := ctx.Value(resolvedIPsKey).(IPResolver)
  60. return ips, ok
  61. }