11package mtproto
22
33import (
4+ "context"
45 "crypto/rand"
56 "crypto/sha256"
67 "io"
@@ -13,6 +14,35 @@ const (
1314 HeaderSize = 64
1415)
1516
17+ type SessionContext struct {
18+ ConnectionType [4 ]byte
19+ DataCenterID uint16
20+ }
21+
22+ func DefaultSessionContext () SessionContext {
23+ return SessionContext {
24+ ConnectionType : [4 ]byte {0xef , 0xef , 0xef , 0xef },
25+ DataCenterID : 0 ,
26+ }
27+ }
28+
29+ type contextKey int32
30+
31+ const (
32+ sessionContextKey contextKey = iota
33+ )
34+
35+ func ContextWithSessionContext (ctx context.Context , c SessionContext ) context.Context {
36+ return context .WithValue (ctx , sessionContextKey , c )
37+ }
38+
39+ func SessionContextFromContext (ctx context.Context ) SessionContext {
40+ if c := ctx .Value (sessionContextKey ); c != nil {
41+ return c .(SessionContext )
42+ }
43+ return DefaultSessionContext ()
44+ }
45+
1646type Authentication struct {
1747 Header [HeaderSize ]byte
1848 DecodingKey [32 ]byte
@@ -29,12 +59,18 @@ func (a *Authentication) DataCenterID() uint16 {
2959 return uint16 (x ) - 1
3060}
3161
62+ func (a * Authentication ) ConnectionType () [4 ]byte {
63+ var x [4 ]byte
64+ copy (x [:], a .Header [56 :60 ])
65+ return x
66+ }
67+
3268func (a * Authentication ) ApplySecret (b []byte ) {
3369 a .DecodingKey = sha256 .Sum256 (append (a .DecodingKey [:], b ... ))
3470 a .EncodingKey = sha256 .Sum256 (append (a .EncodingKey [:], b ... ))
3571}
3672
37- func generateRandomBytes (random []byte ) {
73+ func generateRandomBytes (random []byte , connType [ 4 ] byte ) {
3874 for {
3975 common .Must2 (rand .Read (random ))
4076
@@ -51,19 +87,16 @@ func generateRandomBytes(random []byte) {
5187 continue
5288 }
5389
54- random [56 ] = 0xef
55- random [57 ] = 0xef
56- random [58 ] = 0xef
57- random [59 ] = 0xef
90+ copy (random [56 :60 ], connType [:])
5891
5992 return
6093 }
6194}
6295
63- func NewAuthentication () * Authentication {
96+ func NewAuthentication (sc SessionContext ) * Authentication {
6497 auth := getAuthenticationObject ()
6598 random := auth .Header [:]
66- generateRandomBytes (random )
99+ generateRandomBytes (random , sc . ConnectionType )
67100 copy (auth .EncodingKey [:], random [8 :])
68101 copy (auth .EncodingNonce [:], random [8 + 32 :])
69102 keyivInverse := Inverse (random [8 : 8 + 32 + 16 ])
0 commit comments