Repository navigation
Expand file tree
/
Copy pathsession.go
More file actions
370 lines (341 loc) · 14.9 KB
/
Copy pathsession.go
File metadata and controls
370 lines (341 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package meowcaller
import (
"sync"
"sync/atomic"
"github.com/rs/zerolog"
"github.com/polymorfa/hypermeow/types"
"github.com/purpshell/meowcaller/rtp"
"github.com/purpshell/meowcaller/srtp"
)
// Call state machine and the media-pipeline composition (Opus payload → RTP WARP
// header → E2E-SRTP protect, and the reverse). The byte-level crypto/framing lives
// in the rtp/srtp packages; this stitches it together.
// CallDirection is the originating direction of a call.
type CallDirection int
const (
CallDirectionOutgoing CallDirection = iota
CallDirectionIncoming
)
// CallPhase is the lifecycle phase of a call.
type CallPhase int
const (
CallPhaseIdle CallPhase = iota
CallPhaseCalling
CallPhaseRinging
CallPhaseConnecting
CallPhaseActive
CallPhaseEnded
CallPhaseWaitingRoom
)
// CallSession is the per-call signaling state with validated phase transitions.
type CallSession struct {
CallID string
PeerJID types.JID
CallCreator types.JID
Direction CallDirection
IsVideo bool
phase CallPhase
log zerolog.Logger
}
// NewOutgoingSession starts an outgoing call session in the Idle phase.
func NewOutgoingSession(callID string, peerJID, callCreator types.JID, opts ...Option) *CallSession {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L45-L54
s := &CallSession{
CallID: callID,
PeerJID: peerJID,
CallCreator: callCreator,
Direction: CallDirectionOutgoing,
phase: CallPhaseIdle,
log: resolveConfig(opts).log,
}
s.log.Debug().Str("call_id", callID).Str("peer_jid", peerJID.String()).Str("direction", "outgoing").Msg("call session created")
return s
}
// NewIncomingSession starts an incoming call session in the Ringing phase.
func NewIncomingSession(callID string, peerJID, callCreator types.JID, opts ...Option) *CallSession {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L56-L65
s := &CallSession{
CallID: callID,
PeerJID: peerJID,
CallCreator: callCreator,
Direction: CallDirectionIncoming,
phase: CallPhaseRinging,
log: resolveConfig(opts).log,
}
s.log.Debug().Str("call_id", callID).Str("peer_jid", peerJID.String()).Str("direction", "incoming").Msg("call session created")
return s
}
// Phase returns the current lifecycle phase.
func (s *CallSession) Phase() CallPhase {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L67-L69
return s.phase
}
// IsActive reports whether the call is in the Active phase.
func (s *CallSession) IsActive() bool {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L71-L73
return s.phase == CallPhaseActive
}
// IsEnded reports whether the call has ended.
func (s *CallSession) IsEnded() bool {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L75-L77
return s.phase == CallPhaseEnded
}
// TransitionTo attempts a phase transition, returning false (no-op) if illegal.
// Ended is reachable from anything except Ended.
func (s *CallSession) TransitionTo(next CallPhase) bool {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L81-L97
var ok bool
switch {
case s.phase == CallPhaseEnded:
ok = false
case next == CallPhaseEnded:
ok = true
case s.phase == CallPhaseIdle && next == CallPhaseCalling:
ok = s.Direction == CallDirectionOutgoing
case s.phase == CallPhaseCalling && next == CallPhaseRinging:
ok = true
case s.phase == CallPhaseRinging && next == CallPhaseConnecting:
ok = true
// Source of truth: https://github.com/purpshell/meowcaller/blob/f62ccfb2a431fc25008423954287fd3009fed161/datasheets/web-initial-group-call.md#L40-L120
case (s.phase == CallPhaseCalling || s.phase == CallPhaseConnecting) &&
next == CallPhaseWaitingRoom:
ok = true
case s.phase == CallPhaseWaitingRoom && next == CallPhaseConnecting:
ok = true
case s.phase == CallPhaseConnecting && next == CallPhaseActive:
ok = true
case s.phase == next:
ok = true
default:
ok = false
}
prev := s.phase
if ok {
s.phase = next
s.log.Debug().Str("call_id", s.CallID).Str("from", phaseName(prev)).Str("to", phaseName(next)).Msg("call phase transition")
} else {
s.log.Debug().Str("call_id", s.CallID).Str("from", phaseName(prev)).Str("to", phaseName(next)).Msg("call phase transition rejected")
}
return ok
}
// phaseName gives a stable, log-friendly label for a call phase.
func phaseName(p CallPhase) string {
switch p {
case CallPhaseIdle:
return "idle"
case CallPhaseCalling:
return "calling"
case CallPhaseRinging:
return "ringing"
case CallPhaseConnecting:
return "connecting"
case CallPhaseActive:
return "active"
case CallPhaseEnded:
return "ended"
case CallPhaseWaitingRoom:
return "waiting_room"
default:
return "unknown"
}
}
// MediaPipeline composes the outbound (protect) and inbound (unprotect) E2E 1:1
// media path. SFrame is omitted (plain Opus inside WAHKDF SRTP).
type MediaPipeline struct {
sendMu sync.Mutex
sendKeys srtp.E2eSrtpKeys
recvKeys srtp.E2eSrtpKeys
warpMITagLen int
stream *rtp.RtpStream
sendRoc srtp.RocTracker
recvMu sync.Mutex
recvRoc srtp.RecvRocTracker
packetsSent atomic.Uint32
octetsSent atomic.Uint32
rtpTimestamp atomic.Uint32
log zerolog.Logger
}
// RekeyRecv switches the receive keystream to the companion device that answered an
// outgoing call. The send path remains keyed to this client's own LID.
func (p *MediaPipeline) RekeyRecv(callKey []byte, peerJID string) error {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/aafac5cf46e770f59a1ef2f842d2404154038692/wacore/src/voip/session.rs#L171-L187
recvKeys, err := srtp.DeriveE2eKeys(callKey, rtp.FormatE2ESrtpParticipantID(peerJID))
if err != nil {
return err
}
p.installRecvKeys(recvKeys)
return nil
}
// RekeyRecvFromRaw switches the receive keystream to a participant's keygen-v2
// raw E2E key. The send path remains unchanged.
func (p *MediaPipeline) RekeyRecvFromRaw(rawE2E []byte, peerJID string) error {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/aafac5cf46e770f59a1ef2f842d2404154038692/wacore/src/voip/session.rs#L171-L187
recvKeys, err := srtp.DeriveE2eKeysFromRaw(rawE2E, rtp.FormatE2ESrtpParticipantID(peerJID))
if err != nil {
return err
}
p.installRecvKeys(recvKeys)
return nil
}
// RekeySendFromRaw switches the send keystream to a shared keygen-v2 raw epoch
// derived with this client's own participant ID.
func (p *MediaPipeline) RekeySendFromRaw(rawE2E []byte, selfJID string) error {
// Source of truth: https://github.com/purpshell/meowcaller/blob/cbe1446dabb5842362b1a4362d4100ec15d8254f/datasheets/group-media-key-epoch.md#L56-L64
sendKeys, err := srtp.DeriveE2eKeysFromRaw(rawE2E, rtp.FormatE2ESrtpParticipantID(selfJID))
if err != nil {
return err
}
p.installSendKeys(sendKeys)
return nil
}
// RekeyRecvFromRawPreservingROC switches the receive keystream to a shared
// keygen-v2 raw epoch while retaining the continuing RTP stream's ROC state.
func (p *MediaPipeline) RekeyRecvFromRawPreservingROC(rawE2E []byte, peerJID string) error {
// Source of truth: https://github.com/purpshell/meowcaller/blob/cbe1446dabb5842362b1a4362d4100ec15d8254f/datasheets/group-media-key-epoch.md#L56-L64
recvKeys, err := srtp.DeriveE2eKeysFromRaw(rawE2E, rtp.FormatE2ESrtpParticipantID(peerJID))
if err != nil {
return err
}
p.installRecvKeysPreservingROC(recvKeys)
return nil
}
func (p *MediaPipeline) installSendKeys(sendKeys srtp.E2eSrtpKeys) {
// Source of truth: https://github.com/purpshell/meowcaller/blob/cbe1446dabb5842362b1a4362d4100ec15d8254f/datasheets/group-media-key-epoch.md#L122-L136
p.sendMu.Lock()
p.sendKeys = sendKeys
p.sendMu.Unlock()
}
func (p *MediaPipeline) installRecvKeysPreservingROC(recvKeys srtp.E2eSrtpKeys) {
// Source of truth: https://github.com/purpshell/meowcaller/blob/cbe1446dabb5842362b1a4362d4100ec15d8254f/datasheets/group-media-key-epoch.md#L122-L136
p.recvMu.Lock()
p.recvKeys = recvKeys
p.recvMu.Unlock()
}
func (p *MediaPipeline) installRecvKeys(recvKeys srtp.E2eSrtpKeys) {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/aafac5cf46e770f59a1ef2f842d2404154038692/wacore/src/voip/session.rs#L171-L187
p.recvMu.Lock()
p.recvKeys = recvKeys
p.recvRoc = srtp.RecvRocTracker{}
p.recvMu.Unlock()
}
// NewMediaPipeline derives both directions from the 32-byte callKey: send keys from
// the self LID, recv keys from the peer LID (an interop-load-bearing convention).
func NewMediaPipeline(callKey []byte, selfJID, peerJID string, ssrc, samplesPerPacket uint32, opts ...Option) (*MediaPipeline, error) {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L118-L133
log := resolveConfig(opts).log
sendKeys, err := srtp.DeriveE2eKeys(callKey, rtp.FormatE2ESrtpParticipantID(selfJID))
if err != nil {
log.Debug().Err(err).Str("participant", "self").Msg("media pipeline: derive E2E keys failed")
return nil, err
}
recvKeys, err := srtp.DeriveE2eKeys(callKey, rtp.FormatE2ESrtpParticipantID(peerJID))
if err != nil {
log.Debug().Err(err).Str("participant", "peer").Msg("media pipeline: derive E2E keys failed")
return nil, err
}
log.Debug().Str("self_jid", selfJID).Str("peer_jid", peerJID).Uint32("ssrc", ssrc).
Uint32("samples_per_packet", samplesPerPacket).Int("warp_mi_tag_len", srtp.WarpMITagLen).
Msg("media pipeline initialized")
return &MediaPipeline{
sendKeys: sendKeys,
recvKeys: recvKeys,
warpMITagLen: srtp.WarpMITagLen,
stream: rtp.NewRtpStream(ssrc, samplesPerPacket, false),
log: log,
}, nil
}
// ProtectAudio wraps an Opus payload in an RTP WARP header, E2E-SRTP encrypts, and
// appends the WARP MI tag.
func (p *MediaPipeline) ProtectAudio(opusPayload []byte) ([]byte, error) {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L136-L150
// Source of truth: https://github.com/purpshell/meowcaller/blob/cbe1446dabb5842362b1a4362d4100ec15d8254f/datasheets/group-media-key-epoch.md#L122-L136
p.sendMu.Lock()
defer p.sendMu.Unlock()
header := p.stream.NextPacket(opusPayload, false)
roc := p.sendRoc.Advance(header.SequenceNumber)
packet := rtp.EncodeRtpHeader(&header)
encrypted, err := srtp.CryptPayload(&p.sendKeys, header.Ssrc, header.SequenceNumber, roc, opusPayload)
if err != nil {
p.log.Debug().Err(err).Uint32("ssrc", header.Ssrc).Uint16("seq", header.SequenceNumber).Uint32("roc", roc).Msg("protect: SRTP encrypt failed")
return nil, err
}
packet = append(packet, encrypted...)
out := srtp.AppendWarpMITag(p.sendKeys.AuthKey[:], packet, roc, p.warpMITagLen)
p.packetsSent.Add(1)
p.octetsSent.Add(uint32(len(opusPayload)))
p.rtpTimestamp.Store(header.Timestamp)
p.log.Trace().Uint32("ssrc", header.Ssrc).Uint16("seq", header.SequenceNumber).Uint32("roc", roc).
Int("opus_bytes", len(opusPayload)).Int("packet_bytes", len(out)).Msg("protected audio frame")
return out, nil
}
// ProtectRTP E2E-SRTP encrypts payload under the send keys for a caller-built RTP header
// and appends the WARP MI tag. It is the generic form of ProtectAudio used by the video
// send path, which manages its own PT-97 sequencer (header) per WaCalls.
//
// NOT VALIDATED: the video send media path is unproven.
func (p *MediaPipeline) ProtectRTP(header *rtp.RtpHeader, payload []byte) ([]byte, error) {
// Source of truth: https://github.com/purpshell/meowcaller/blob/cbe1446dabb5842362b1a4362d4100ec15d8254f/datasheets/group-media-key-epoch.md#L122-L136
p.sendMu.Lock()
defer p.sendMu.Unlock()
roc := p.sendRoc.Advance(header.SequenceNumber)
packet := rtp.EncodeRtpHeader(header)
encrypted, err := srtp.CryptPayload(&p.sendKeys, header.Ssrc, header.SequenceNumber, roc, payload)
if err != nil {
p.log.Debug().Err(err).Uint32("ssrc", header.Ssrc).Uint16("seq", header.SequenceNumber).Uint32("roc", roc).Msg("protect rtp: SRTP encrypt failed")
return nil, err
}
packet = append(packet, encrypted...)
out := srtp.AppendWarpMITag(p.sendKeys.AuthKey[:], packet, roc, p.warpMITagLen)
p.packetsSent.Add(1)
p.octetsSent.Add(uint32(len(payload)))
p.rtpTimestamp.Store(header.Timestamp)
return out, nil
}
// SenderStats snapshots the counters used by an RTCP Sender Report.
func (p *MediaPipeline) SenderStats() rtp.RtcpSenderStats {
return rtp.RtcpSenderStats{
PacketsSent: p.packetsSent.Load(),
OctetsSent: p.octetsSent.Load(),
RtpTimestamp: p.rtpTimestamp.Load(),
}
}
// UnprotectAudio authenticates and strips the WARP MI tag, parses the header, and
// decrypts the payload, guessing the ROC from the recv tracker. ok=false on a
// malformed or unauthenticated packet.
func (p *MediaPipeline) UnprotectAudio(packet []byte) (rtp.RtpHeader, []byte, bool) {
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/41095d4e6ba4610e054e9ede3af1d5e88a83faee/src/voip/session.rs#L155-L175
if len(packet) < 12+p.warpMITagLen {
p.log.Debug().Int("packet_bytes", len(packet)).Int("min_bytes", 12+p.warpMITagLen).Msg("unprotect: packet too short")
return rtp.RtpHeader{}, nil, false
}
withoutTag := packet[:len(packet)-p.warpMITagLen]
header, ok := rtp.ParseRtpHeader(withoutTag)
if !ok {
p.log.Debug().Int("packet_bytes", len(packet)).Msg("unprotect: malformed RTP header")
return rtp.RtpHeader{}, nil, false
}
headerLen, ok := rtp.RtpHeaderByteLength(withoutTag)
if !ok || len(withoutTag) <= headerLen {
p.log.Debug().Uint32("ssrc", header.Ssrc).Int("header_bytes", headerLen).Msg("unprotect: header length invalid or no payload")
return rtp.RtpHeader{}, nil, false
}
p.recvMu.Lock()
// Source of truth: https://github.com/oxidezap/whatsapp-rust/blob/2f001b5a3d6374cc5cf7177792c2a81f87a54080/wacore/src/voip/session.rs#L239-L250
roc := p.recvRoc.EstimateRoc(header.SequenceNumber)
tag := packet[len(withoutTag):]
if !srtp.VerifyWarpMITag(p.recvKeys.AuthKey[:], withoutTag, roc, p.warpMITagLen, tag, p.log) {
p.recvMu.Unlock()
p.log.Debug().Uint32("ssrc", header.Ssrc).Uint16("seq", header.SequenceNumber).Uint32("roc", roc).Msg("unprotect: WARP MI authentication failed")
return rtp.RtpHeader{}, nil, false
}
p.recvRoc.CommitRoc(roc, header.SequenceNumber)
plain, err := srtp.CryptPayload(&p.recvKeys, header.Ssrc, header.SequenceNumber, roc, withoutTag[headerLen:])
p.recvMu.Unlock()
if err != nil {
p.log.Debug().Err(err).Uint32("ssrc", header.Ssrc).Uint16("seq", header.SequenceNumber).Uint32("roc", roc).Msg("unprotect: SRTP decrypt failed")
return rtp.RtpHeader{}, nil, false
}
p.log.Trace().Uint32("ssrc", header.Ssrc).Uint16("seq", header.SequenceNumber).Uint32("roc", roc).
Int("plain_bytes", len(plain)).Msg("unprotected audio frame")
return header, plain, true
}