Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

direct.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package proxy
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "sync"
  7. "github.com/juju/errors"
  8. "github.com/9seconds/mtg/client"
  9. "github.com/9seconds/mtg/config"
  10. "github.com/9seconds/mtg/mtproto"
  11. "github.com/9seconds/mtg/telegram"
  12. "github.com/9seconds/mtg/wrappers"
  13. )
  14. func NewProxyDirect(conf *config.Config) *Proxy {
  15. tg := telegram.NewDirectTelegram(conf)
  16. return &Proxy{
  17. conf: conf,
  18. acceptCallback: func(ctx context.Context, cancel context.CancelFunc, clientSocket net.Conn,
  19. connID string, wait *sync.WaitGroup, conf *config.Config) error {
  20. client, opts, err := client.DirectInit(ctx, cancel, clientSocket, connID, conf)
  21. if err != nil {
  22. return errors.Annotate(err, "Cannot initialize client connection")
  23. }
  24. defer client.Close()
  25. server, err := directTelegramStream(ctx, cancel, opts, connID, tg)
  26. if err != nil {
  27. return errors.Annotate(err, "Cannot initialize telegram connection")
  28. }
  29. defer server.Close()
  30. wait.Add(2)
  31. go directPipe(client, server, wait)
  32. go directPipe(server, client, wait)
  33. return nil
  34. },
  35. }
  36. }
  37. func directTelegramStream(ctx context.Context, cancel context.CancelFunc, opts *mtproto.ConnectionOpts,
  38. connID string, tg *telegram.DirectTelegram) (wrappers.WrapStreamReadWriteCloser, error) {
  39. streamConn, err := tg.Dial(connID, opts)
  40. if err != nil {
  41. return nil, errors.Annotate(err, "Cannot dial to Telegram")
  42. }
  43. streamConn = wrappers.NewCtx(ctx, cancel, streamConn)
  44. packetConn, err := tg.Init(opts, streamConn)
  45. if err != nil {
  46. return nil, errors.Annotate(err, "Cannot handshake telegram")
  47. }
  48. return packetConn, nil
  49. }
  50. func directPipe(src io.Reader, dst io.Writer, wait *sync.WaitGroup) {
  51. defer wait.Done()
  52. io.Copy(dst, src)
  53. }