2022-01-30 15:27:37 -08:00
|
|
|
// Copyright (c) 2021 Tulir Asokan
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
|
|
|
|
package whatsmeow
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"compress/zlib"
|
2022-06-11 14:07:42 -07:00
|
|
|
"encoding/hex"
|
2022-01-30 15:27:37 -08:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-03-31 15:23:19 -07:00
|
|
|
"runtime/debug"
|
2022-01-30 15:27:37 -08:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"go.mau.fi/libsignal/groups"
|
|
|
|
"go.mau.fi/libsignal/protocol"
|
|
|
|
"go.mau.fi/libsignal/session"
|
2024-05-23 14:44:31 -07:00
|
|
|
"go.mau.fi/libsignal/signalerror"
|
|
|
|
"go.mau.fi/util/random"
|
|
|
|
"google.golang.org/protobuf/proto"
|
2022-01-30 15:27:37 -08:00
|
|
|
|
|
|
|
"go.mau.fi/whatsmeow/appstate"
|
|
|
|
waBinary "go.mau.fi/whatsmeow/binary"
|
|
|
|
waProto "go.mau.fi/whatsmeow/binary/proto"
|
|
|
|
"go.mau.fi/whatsmeow/store"
|
|
|
|
"go.mau.fi/whatsmeow/types"
|
|
|
|
"go.mau.fi/whatsmeow/types/events"
|
|
|
|
)
|
|
|
|
|
|
|
|
var pbSerializer = store.SignalProtobufSerializer
|
|
|
|
|
|
|
|
func (cli *Client) handleEncryptedMessage(node *waBinary.Node) {
|
|
|
|
info, err := cli.parseMessageInfo(node)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Failed to parse message: %v", err)
|
|
|
|
} else {
|
2022-06-24 15:36:16 -07:00
|
|
|
if info.VerifiedName != nil && len(info.VerifiedName.Details.GetVerifiedName()) > 0 {
|
|
|
|
go cli.updateBusinessName(info.Sender, info, info.VerifiedName.Details.GetVerifiedName())
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
if len(info.PushName) > 0 && info.PushName != "-" {
|
|
|
|
go cli.updatePushName(info.Sender, info, info.PushName)
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
go cli.sendAck(node)
|
|
|
|
if info.Sender.Server == types.NewsletterServer {
|
|
|
|
cli.handlePlaintextMessage(info, node)
|
|
|
|
} else {
|
|
|
|
cli.decryptMessages(info, node)
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-24 15:36:16 -07:00
|
|
|
func (cli *Client) parseMessageSource(node *waBinary.Node, requireParticipant bool) (source types.MessageSource, err error) {
|
2023-01-28 13:57:53 -08:00
|
|
|
clientID := cli.getOwnID()
|
|
|
|
if clientID.IsEmpty() {
|
2022-08-13 07:14:26 -07:00
|
|
|
err = ErrNotLoggedIn
|
|
|
|
return
|
|
|
|
}
|
2022-06-11 14:07:42 -07:00
|
|
|
ag := node.AttrGetter()
|
|
|
|
from := ag.JID("from")
|
|
|
|
if from.Server == types.GroupServer || from.Server == types.BroadcastServer {
|
2022-01-30 15:27:37 -08:00
|
|
|
source.IsGroup = true
|
|
|
|
source.Chat = from
|
2022-06-24 15:36:16 -07:00
|
|
|
if requireParticipant {
|
|
|
|
source.Sender = ag.JID("participant")
|
|
|
|
} else {
|
|
|
|
source.Sender = ag.OptionalJIDOrEmpty("participant")
|
|
|
|
}
|
2022-08-13 07:14:26 -07:00
|
|
|
if source.Sender.User == clientID.User {
|
2022-06-11 14:07:42 -07:00
|
|
|
source.IsFromMe = true
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
if from.Server == types.BroadcastServer {
|
2022-06-11 14:07:42 -07:00
|
|
|
source.BroadcastListOwner = ag.OptionalJIDOrEmpty("recipient")
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
} else if from.Server == types.NewsletterServer {
|
|
|
|
source.Chat = from
|
|
|
|
source.Sender = from
|
|
|
|
// TODO IsFromMe?
|
2022-08-13 07:14:26 -07:00
|
|
|
} else if from.User == clientID.User {
|
2022-01-30 15:27:37 -08:00
|
|
|
source.IsFromMe = true
|
|
|
|
source.Sender = from
|
2022-06-11 14:07:42 -07:00
|
|
|
recipient := ag.OptionalJID("recipient")
|
|
|
|
if recipient != nil {
|
|
|
|
source.Chat = *recipient
|
2022-01-30 15:27:37 -08:00
|
|
|
} else {
|
2022-06-11 14:07:42 -07:00
|
|
|
source.Chat = from.ToNonAD()
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
source.Chat = from.ToNonAD()
|
|
|
|
source.Sender = from
|
|
|
|
}
|
2022-06-11 14:07:42 -07:00
|
|
|
err = ag.Error()
|
2022-01-30 15:27:37 -08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *Client) parseMessageInfo(node *waBinary.Node) (*types.MessageInfo, error) {
|
|
|
|
var info types.MessageInfo
|
|
|
|
var err error
|
2022-06-24 15:36:16 -07:00
|
|
|
info.MessageSource, err = cli.parseMessageSource(node, true)
|
2022-01-30 15:27:37 -08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-06-11 14:07:42 -07:00
|
|
|
ag := node.AttrGetter()
|
|
|
|
info.ID = types.MessageID(ag.String("id"))
|
2024-05-23 14:44:31 -07:00
|
|
|
info.ServerID = types.MessageServerID(ag.OptionalInt("server_id"))
|
2022-06-11 14:07:42 -07:00
|
|
|
info.Timestamp = ag.UnixTime("t")
|
|
|
|
info.PushName = ag.OptionalString("notify")
|
|
|
|
info.Category = ag.OptionalString("category")
|
2023-08-05 11:43:19 -07:00
|
|
|
info.Type = ag.OptionalString("type")
|
2024-05-23 14:44:31 -07:00
|
|
|
info.Edit = types.EditAttribute(ag.OptionalString("edit"))
|
2022-06-11 14:07:42 -07:00
|
|
|
if !ag.OK() {
|
|
|
|
return nil, ag.Error()
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
|
2022-04-25 14:50:10 -07:00
|
|
|
for _, child := range node.GetChildren() {
|
2024-05-23 14:44:31 -07:00
|
|
|
switch child.Tag {
|
|
|
|
case "multicast":
|
2022-04-25 14:50:10 -07:00
|
|
|
info.Multicast = true
|
2024-05-23 14:44:31 -07:00
|
|
|
case "verified_name":
|
2022-06-24 15:36:16 -07:00
|
|
|
info.VerifiedName, err = parseVerifiedNameContent(child)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Failed to parse verified_name node in %s: %v", info.ID, err)
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
case "franking":
|
|
|
|
// TODO
|
|
|
|
case "trace":
|
|
|
|
// TODO
|
|
|
|
default:
|
|
|
|
if mediaType, ok := child.AttrGetter().GetString("mediatype", false); ok {
|
|
|
|
info.MediaType = mediaType
|
|
|
|
}
|
2022-04-25 14:50:10 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
return &info, nil
|
|
|
|
}
|
|
|
|
|
2024-05-23 14:44:31 -07:00
|
|
|
func (cli *Client) handlePlaintextMessage(info *types.MessageInfo, node *waBinary.Node) {
|
|
|
|
// TODO edits have an additional <meta msg_edit_t="1696321271735" original_msg_t="1696321248"/> node
|
|
|
|
plaintext, ok := node.GetOptionalChildByTag("plaintext")
|
|
|
|
if !ok {
|
|
|
|
// 3:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
plaintextBody, ok := plaintext.Content.([]byte)
|
|
|
|
if !ok {
|
|
|
|
cli.Log.Warnf("Plaintext message from %s doesn't have byte content", info.SourceString())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var msg waProto.Message
|
|
|
|
err := proto.Unmarshal(plaintextBody, &msg)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Error unmarshaling plaintext message from %s: %v", info.SourceString(), err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cli.storeMessageSecret(info, &msg)
|
|
|
|
evt := &events.Message{
|
|
|
|
Info: *info,
|
|
|
|
RawMessage: &msg,
|
|
|
|
}
|
|
|
|
meta, ok := node.GetOptionalChildByTag("meta")
|
|
|
|
if ok {
|
|
|
|
evt.NewsletterMeta = &events.NewsletterMessageMeta{
|
|
|
|
EditTS: meta.AttrGetter().UnixMilli("msg_edit_t"),
|
|
|
|
OriginalTS: meta.AttrGetter().UnixTime("original_msg_t"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cli.dispatchEvent(evt.UnwrapRaw())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
func (cli *Client) decryptMessages(info *types.MessageInfo, node *waBinary.Node) {
|
2022-04-25 14:50:10 -07:00
|
|
|
if len(node.GetChildrenByTag("unavailable")) > 0 && len(node.GetChildrenByTag("enc")) == 0 {
|
2022-01-30 15:27:37 -08:00
|
|
|
cli.Log.Warnf("Unavailable message %s from %s", info.ID, info.SourceString())
|
2023-08-05 11:43:19 -07:00
|
|
|
go cli.sendRetryReceipt(node, info, true)
|
2022-01-30 15:27:37 -08:00
|
|
|
cli.dispatchEvent(&events.UndecryptableMessage{Info: *info, IsUnavailable: true})
|
|
|
|
return
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
children := node.GetChildren()
|
2024-05-23 14:44:31 -07:00
|
|
|
cli.Log.Debugf("Decrypting message from %s", info.SourceString())
|
2022-01-30 15:27:37 -08:00
|
|
|
handled := false
|
2022-06-11 14:07:42 -07:00
|
|
|
containsDirectMsg := false
|
2022-01-30 15:27:37 -08:00
|
|
|
for _, child := range children {
|
|
|
|
if child.Tag != "enc" {
|
|
|
|
continue
|
|
|
|
}
|
2023-08-05 11:43:19 -07:00
|
|
|
ag := child.AttrGetter()
|
|
|
|
encType, ok := ag.GetString("type", false)
|
2022-01-30 15:27:37 -08:00
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
var decrypted []byte
|
|
|
|
var err error
|
|
|
|
if encType == "pkmsg" || encType == "msg" {
|
|
|
|
decrypted, err = cli.decryptDM(&child, info.Sender, encType == "pkmsg")
|
2022-06-11 14:07:42 -07:00
|
|
|
containsDirectMsg = true
|
2022-01-30 15:27:37 -08:00
|
|
|
} else if info.IsGroup && encType == "skmsg" {
|
|
|
|
decrypted, err = cli.decryptGroupMsg(&child, info.Sender, info.Chat)
|
|
|
|
} else {
|
|
|
|
cli.Log.Warnf("Unhandled encrypted message (type %s) from %s", encType, info.SourceString())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Error decrypting message from %s: %v", info.SourceString(), err)
|
2022-06-11 14:07:42 -07:00
|
|
|
isUnavailable := encType == "skmsg" && !containsDirectMsg && errors.Is(err, signalerror.ErrNoSenderKeyForUser)
|
2023-08-05 11:43:19 -07:00
|
|
|
go cli.sendRetryReceipt(node, info, isUnavailable)
|
|
|
|
cli.dispatchEvent(&events.UndecryptableMessage{
|
|
|
|
Info: *info,
|
|
|
|
IsUnavailable: isUnavailable,
|
2024-05-23 14:44:31 -07:00
|
|
|
DecryptFailMode: events.DecryptFailMode(ag.OptionalString("decrypt-fail")),
|
2023-08-05 11:43:19 -07:00
|
|
|
})
|
2022-01-30 15:27:37 -08:00
|
|
|
return
|
|
|
|
}
|
2023-08-05 11:43:19 -07:00
|
|
|
retryCount := ag.OptionalInt("count")
|
|
|
|
if retryCount > 0 {
|
|
|
|
cli.cancelDelayedRequestFromPhone(info.ID)
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
|
2024-05-23 14:44:31 -07:00
|
|
|
var msg waProto.Message
|
|
|
|
switch ag.Int("v") {
|
|
|
|
case 2:
|
|
|
|
err = proto.Unmarshal(decrypted, &msg)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Error unmarshaling decrypted message from %s: %v", info.SourceString(), err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
cli.handleDecryptedMessage(info, &msg, retryCount)
|
|
|
|
handled = true
|
|
|
|
case 3:
|
|
|
|
handled = cli.handleDecryptedArmadillo(info, decrypted, retryCount)
|
|
|
|
default:
|
|
|
|
cli.Log.Warnf("Unknown version %d in decrypted message from %s", ag.Int("v"), info.SourceString())
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
if handled {
|
|
|
|
go cli.sendMessageReceipt(info)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-31 15:23:19 -07:00
|
|
|
func (cli *Client) clearUntrustedIdentity(target types.JID) {
|
|
|
|
err := cli.Store.Identities.DeleteIdentity(target.SignalAddress().String())
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Failed to delete untrusted identity of %s from store: %v", target, err)
|
|
|
|
}
|
|
|
|
err = cli.Store.Sessions.DeleteSession(target.SignalAddress().String())
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Failed to delete session with %s (untrusted identity) from store: %v", target, err)
|
|
|
|
}
|
|
|
|
cli.dispatchEvent(&events.IdentityChange{JID: target, Timestamp: time.Now(), Implicit: true})
|
|
|
|
}
|
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
func (cli *Client) decryptDM(child *waBinary.Node, from types.JID, isPreKey bool) ([]byte, error) {
|
|
|
|
content, _ := child.Content.([]byte)
|
|
|
|
|
|
|
|
builder := session.NewBuilderFromSignal(cli.Store, from.SignalAddress(), pbSerializer)
|
|
|
|
cipher := session.NewCipher(builder, from.SignalAddress())
|
|
|
|
var plaintext []byte
|
|
|
|
if isPreKey {
|
|
|
|
preKeyMsg, err := protocol.NewPreKeySignalMessageFromBytes(content, pbSerializer.PreKeySignalMessage, pbSerializer.SignalMessage)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse prekey message: %w", err)
|
|
|
|
}
|
|
|
|
plaintext, _, err = cipher.DecryptMessageReturnKey(preKeyMsg)
|
2022-03-31 15:23:19 -07:00
|
|
|
if cli.AutoTrustIdentity && errors.Is(err, signalerror.ErrUntrustedIdentity) {
|
2022-01-30 15:27:37 -08:00
|
|
|
cli.Log.Warnf("Got %v error while trying to decrypt prekey message from %s, clearing stored identity and retrying", err, from)
|
2022-03-31 15:23:19 -07:00
|
|
|
cli.clearUntrustedIdentity(from)
|
2022-01-30 15:27:37 -08:00
|
|
|
plaintext, _, err = cipher.DecryptMessageReturnKey(preKeyMsg)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to decrypt prekey message: %w", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
msg, err := protocol.NewSignalMessageFromBytes(content, pbSerializer.SignalMessage)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse normal message: %w", err)
|
|
|
|
}
|
|
|
|
plaintext, err = cipher.Decrypt(msg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to decrypt normal message: %w", err)
|
|
|
|
}
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
if child.AttrGetter().Int("v") == 3 {
|
|
|
|
return plaintext, nil
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
return unpadMessage(plaintext)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *Client) decryptGroupMsg(child *waBinary.Node, from types.JID, chat types.JID) ([]byte, error) {
|
|
|
|
content, _ := child.Content.([]byte)
|
|
|
|
|
|
|
|
senderKeyName := protocol.NewSenderKeyName(chat.String(), from.SignalAddress())
|
|
|
|
builder := groups.NewGroupSessionBuilder(cli.Store, pbSerializer)
|
|
|
|
cipher := groups.NewGroupCipher(builder, senderKeyName, cli.Store)
|
|
|
|
msg, err := protocol.NewSenderKeyMessageFromBytes(content, pbSerializer.SenderKeyMessage)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse group message: %w", err)
|
|
|
|
}
|
|
|
|
plaintext, err := cipher.Decrypt(msg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to decrypt group message: %w", err)
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
if child.AttrGetter().Int("v") == 3 {
|
|
|
|
return plaintext, nil
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
return unpadMessage(plaintext)
|
|
|
|
}
|
|
|
|
|
|
|
|
const checkPadding = true
|
|
|
|
|
|
|
|
func isValidPadding(plaintext []byte) bool {
|
|
|
|
lastByte := plaintext[len(plaintext)-1]
|
|
|
|
expectedPadding := bytes.Repeat([]byte{lastByte}, int(lastByte))
|
|
|
|
return bytes.HasSuffix(plaintext, expectedPadding)
|
|
|
|
}
|
|
|
|
|
|
|
|
func unpadMessage(plaintext []byte) ([]byte, error) {
|
2023-08-05 11:43:19 -07:00
|
|
|
if len(plaintext) == 0 {
|
|
|
|
return nil, fmt.Errorf("plaintext is empty")
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
if checkPadding && !isValidPadding(plaintext) {
|
|
|
|
return nil, fmt.Errorf("plaintext doesn't have expected padding")
|
|
|
|
}
|
|
|
|
return plaintext[:len(plaintext)-int(plaintext[len(plaintext)-1])], nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func padMessage(plaintext []byte) []byte {
|
2024-05-23 14:44:31 -07:00
|
|
|
pad := random.Bytes(1)
|
2022-01-30 15:27:37 -08:00
|
|
|
pad[0] &= 0xf
|
|
|
|
if pad[0] == 0 {
|
|
|
|
pad[0] = 0xf
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
plaintext = append(plaintext, bytes.Repeat(pad, int(pad[0]))...)
|
2022-01-30 15:27:37 -08:00
|
|
|
return plaintext
|
|
|
|
}
|
|
|
|
|
2024-05-23 14:44:31 -07:00
|
|
|
func (cli *Client) handleSenderKeyDistributionMessage(chat, from types.JID, axolotlSKDM []byte) {
|
2022-01-30 15:27:37 -08:00
|
|
|
builder := groups.NewGroupSessionBuilder(cli.Store, pbSerializer)
|
|
|
|
senderKeyName := protocol.NewSenderKeyName(chat.String(), from.SignalAddress())
|
2024-05-23 14:44:31 -07:00
|
|
|
sdkMsg, err := protocol.NewSenderKeyDistributionMessageFromBytes(axolotlSKDM, pbSerializer.SenderKeyDistributionMessage)
|
2022-01-30 15:27:37 -08:00
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("Failed to parse sender key distribution message from %s for %s: %v", from, chat, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
builder.Process(senderKeyName, sdkMsg)
|
|
|
|
cli.Log.Debugf("Processed sender key distribution message from %s in %s", senderKeyName.Sender().String(), senderKeyName.GroupID())
|
|
|
|
}
|
|
|
|
|
2022-03-31 15:23:19 -07:00
|
|
|
func (cli *Client) handleHistorySyncNotificationLoop() {
|
|
|
|
defer func() {
|
2024-05-23 14:44:31 -07:00
|
|
|
cli.historySyncHandlerStarted.Store(false)
|
2022-03-31 15:23:19 -07:00
|
|
|
err := recover()
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("History sync handler panicked: %v\n%s", err, debug.Stack())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check in case something new appeared in the channel between the loop stopping
|
|
|
|
// and the atomic variable being updated. If yes, restart the loop.
|
2024-05-23 14:44:31 -07:00
|
|
|
if len(cli.historySyncNotifications) > 0 && cli.historySyncHandlerStarted.CompareAndSwap(false, true) {
|
2022-03-31 15:23:19 -07:00
|
|
|
cli.Log.Warnf("New history sync notifications appeared after loop stopped, restarting loop...")
|
|
|
|
go cli.handleHistorySyncNotificationLoop()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
for notif := range cli.historySyncNotifications {
|
|
|
|
cli.handleHistorySyncNotification(notif)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
func (cli *Client) handleHistorySyncNotification(notif *waProto.HistorySyncNotification) {
|
|
|
|
var historySync waProto.HistorySync
|
|
|
|
if data, err := cli.Download(notif); err != nil {
|
|
|
|
cli.Log.Errorf("Failed to download history sync data: %v", err)
|
|
|
|
} else if reader, err := zlib.NewReader(bytes.NewReader(data)); err != nil {
|
|
|
|
cli.Log.Errorf("Failed to create zlib reader for history sync data: %v", err)
|
|
|
|
} else if rawData, err := io.ReadAll(reader); err != nil {
|
|
|
|
cli.Log.Errorf("Failed to decompress history sync data: %v", err)
|
|
|
|
} else if err = proto.Unmarshal(rawData, &historySync); err != nil {
|
|
|
|
cli.Log.Errorf("Failed to unmarshal history sync data: %v", err)
|
|
|
|
} else {
|
2022-03-31 15:23:19 -07:00
|
|
|
cli.Log.Debugf("Received history sync (type %s, chunk %d)", historySync.GetSyncType(), historySync.GetChunkOrder())
|
2022-01-30 15:27:37 -08:00
|
|
|
if historySync.GetSyncType() == waProto.HistorySync_PUSH_NAME {
|
|
|
|
go cli.handleHistoricalPushNames(historySync.GetPushnames())
|
2022-11-26 15:42:16 -08:00
|
|
|
} else if len(historySync.GetConversations()) > 0 {
|
|
|
|
go cli.storeHistoricalMessageSecrets(historySync.GetConversations())
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
cli.dispatchEvent(&events.HistorySync{
|
|
|
|
Data: &historySync,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *Client) handleAppStateSyncKeyShare(keys *waProto.AppStateSyncKeyShare) {
|
2022-06-11 14:07:42 -07:00
|
|
|
onlyResyncIfNotSynced := true
|
|
|
|
|
2022-03-12 14:02:04 -08:00
|
|
|
cli.Log.Debugf("Got %d new app state keys", len(keys.GetKeys()))
|
2022-06-11 14:07:42 -07:00
|
|
|
cli.appStateKeyRequestsLock.RLock()
|
2022-01-30 15:27:37 -08:00
|
|
|
for _, key := range keys.GetKeys() {
|
|
|
|
marshaledFingerprint, err := proto.Marshal(key.GetKeyData().GetFingerprint())
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("Failed to marshal fingerprint of app state sync key %X", key.GetKeyId().GetKeyId())
|
|
|
|
continue
|
|
|
|
}
|
2022-06-11 14:07:42 -07:00
|
|
|
_, isReRequest := cli.appStateKeyRequests[hex.EncodeToString(key.GetKeyId().GetKeyId())]
|
|
|
|
if isReRequest {
|
|
|
|
onlyResyncIfNotSynced = false
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
err = cli.Store.AppStateKeys.PutAppStateSyncKey(key.GetKeyId().GetKeyId(), store.AppStateSyncKey{
|
|
|
|
Data: key.GetKeyData().GetKeyData(),
|
|
|
|
Fingerprint: marshaledFingerprint,
|
|
|
|
Timestamp: key.GetKeyData().GetTimestamp(),
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-06-11 14:07:42 -07:00
|
|
|
cli.Log.Errorf("Failed to store app state sync key %X: %v", key.GetKeyId().GetKeyId(), err)
|
2022-01-30 15:27:37 -08:00
|
|
|
continue
|
|
|
|
}
|
2023-03-09 13:48:00 -08:00
|
|
|
cli.Log.Debugf("Received app state sync key %X (ts: %d)", key.GetKeyId().GetKeyId(), key.GetKeyData().GetTimestamp())
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
2022-06-11 14:07:42 -07:00
|
|
|
cli.appStateKeyRequestsLock.RUnlock()
|
2022-01-30 15:27:37 -08:00
|
|
|
|
|
|
|
for _, name := range appstate.AllPatchNames {
|
2022-06-11 14:07:42 -07:00
|
|
|
err := cli.FetchAppState(name, false, onlyResyncIfNotSynced)
|
2022-01-30 15:27:37 -08:00
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("Failed to do initial fetch of app state %s: %v", name, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-05 11:43:19 -07:00
|
|
|
func (cli *Client) handlePlaceholderResendResponse(msg *waProto.PeerDataOperationRequestResponseMessage) {
|
|
|
|
reqID := msg.GetStanzaId()
|
|
|
|
parts := msg.GetPeerDataOperationResult()
|
|
|
|
cli.Log.Debugf("Handling response to placeholder resend request %s with %d items", reqID, len(parts))
|
|
|
|
for i, part := range parts {
|
|
|
|
var webMsg waProto.WebMessageInfo
|
|
|
|
if resp := part.GetPlaceholderMessageResendResponse(); resp == nil {
|
|
|
|
cli.Log.Warnf("Missing response in item #%d of response to %s", i+1, reqID)
|
|
|
|
} else if err := proto.Unmarshal(resp.GetWebMessageInfoBytes(), &webMsg); err != nil {
|
|
|
|
cli.Log.Warnf("Failed to unmarshal protobuf web message in item #%d of response to %s: %v", i+1, reqID, err)
|
|
|
|
} else if msgEvt, err := cli.ParseWebMessage(types.EmptyJID, &webMsg); err != nil {
|
|
|
|
cli.Log.Warnf("Failed to parse web message info in item #%d of response to %s: %v", i+1, reqID, err)
|
|
|
|
} else {
|
|
|
|
msgEvt.UnavailableRequestID = reqID
|
|
|
|
cli.dispatchEvent(msgEvt)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
func (cli *Client) handleProtocolMessage(info *types.MessageInfo, msg *waProto.Message) {
|
|
|
|
protoMsg := msg.GetProtocolMessage()
|
|
|
|
|
|
|
|
if protoMsg.GetHistorySyncNotification() != nil && info.IsFromMe {
|
2022-03-31 15:23:19 -07:00
|
|
|
cli.historySyncNotifications <- protoMsg.HistorySyncNotification
|
2024-05-23 14:44:31 -07:00
|
|
|
if cli.historySyncHandlerStarted.CompareAndSwap(false, true) {
|
2022-03-31 15:23:19 -07:00
|
|
|
go cli.handleHistorySyncNotificationLoop()
|
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
go cli.sendProtocolMessageReceipt(info.ID, types.ReceiptTypeHistorySync)
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
|
2023-08-05 11:43:19 -07:00
|
|
|
if protoMsg.GetPeerDataOperationRequestResponseMessage().GetPeerDataOperationRequestType() == waProto.PeerDataOperationRequestType_PLACEHOLDER_MESSAGE_RESEND {
|
|
|
|
go cli.handlePlaceholderResendResponse(protoMsg.GetPeerDataOperationRequestResponseMessage())
|
|
|
|
}
|
|
|
|
|
2022-01-30 15:27:37 -08:00
|
|
|
if protoMsg.GetAppStateSyncKeyShare() != nil && info.IsFromMe {
|
2022-03-31 15:23:19 -07:00
|
|
|
go cli.handleAppStateSyncKeyShare(protoMsg.AppStateSyncKeyShare)
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
if info.Category == "peer" {
|
2024-05-23 14:44:31 -07:00
|
|
|
go cli.sendProtocolMessageReceipt(info.ID, types.ReceiptTypePeerMsg)
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-11 14:07:42 -07:00
|
|
|
func (cli *Client) processProtocolParts(info *types.MessageInfo, msg *waProto.Message) {
|
|
|
|
// Hopefully sender key distribution messages and protocol messages can't be inside ephemeral messages
|
2022-01-30 15:27:37 -08:00
|
|
|
if msg.GetDeviceSentMessage().GetMessage() != nil {
|
|
|
|
msg = msg.GetDeviceSentMessage().GetMessage()
|
|
|
|
}
|
|
|
|
if msg.GetSenderKeyDistributionMessage() != nil {
|
|
|
|
if !info.IsGroup {
|
2024-05-23 14:44:31 -07:00
|
|
|
cli.Log.Warnf("Got sender key distribution message in non-group chat from %s", info.Sender)
|
2022-01-30 15:27:37 -08:00
|
|
|
} else {
|
2024-05-23 14:44:31 -07:00
|
|
|
cli.handleSenderKeyDistributionMessage(info.Chat, info.Sender, msg.SenderKeyDistributionMessage.AxolotlSenderKeyDistributionMessage)
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
}
|
2022-11-26 15:42:16 -08:00
|
|
|
// N.B. Edits are protocol messages, but they're also wrapped inside EditedMessage,
|
|
|
|
// which is only unwrapped after processProtocolParts, so this won't trigger for edits.
|
2022-01-30 15:27:37 -08:00
|
|
|
if msg.GetProtocolMessage() != nil {
|
2022-03-31 15:23:19 -07:00
|
|
|
cli.handleProtocolMessage(info, msg)
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
2024-05-23 14:44:31 -07:00
|
|
|
cli.storeMessageSecret(info, msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *Client) storeMessageSecret(info *types.MessageInfo, msg *waProto.Message) {
|
2022-11-26 15:42:16 -08:00
|
|
|
if msgSecret := msg.GetMessageContextInfo().GetMessageSecret(); len(msgSecret) > 0 {
|
|
|
|
err := cli.Store.MsgSecrets.PutMessageSecret(info.Chat, info.Sender, info.ID, msgSecret)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("Failed to store message secret key for %s: %v", info.ID, err)
|
|
|
|
} else {
|
|
|
|
cli.Log.Debugf("Stored message secret key for %s", info.ID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
|
2022-11-26 15:42:16 -08:00
|
|
|
func (cli *Client) storeHistoricalMessageSecrets(conversations []*waProto.Conversation) {
|
|
|
|
var secrets []store.MessageSecretInsert
|
2023-01-28 13:57:53 -08:00
|
|
|
var privacyTokens []store.PrivacyToken
|
|
|
|
ownID := cli.getOwnID().ToNonAD()
|
|
|
|
if ownID.IsEmpty() {
|
|
|
|
return
|
|
|
|
}
|
2022-11-26 15:42:16 -08:00
|
|
|
for _, conv := range conversations {
|
|
|
|
chatJID, _ := types.ParseJID(conv.GetId())
|
|
|
|
if chatJID.IsEmpty() {
|
|
|
|
continue
|
|
|
|
}
|
2023-01-28 13:57:53 -08:00
|
|
|
if chatJID.Server == types.DefaultUserServer && conv.GetTcToken() != nil {
|
|
|
|
ts := conv.GetTcTokenSenderTimestamp()
|
|
|
|
if ts == 0 {
|
|
|
|
ts = conv.GetTcTokenTimestamp()
|
|
|
|
}
|
|
|
|
privacyTokens = append(privacyTokens, store.PrivacyToken{
|
|
|
|
User: chatJID,
|
|
|
|
Token: conv.GetTcToken(),
|
|
|
|
Timestamp: time.Unix(int64(ts), 0),
|
|
|
|
})
|
|
|
|
}
|
2022-11-26 15:42:16 -08:00
|
|
|
for _, msg := range conv.GetMessages() {
|
|
|
|
if secret := msg.GetMessage().GetMessageSecret(); secret != nil {
|
|
|
|
var senderJID types.JID
|
|
|
|
msgKey := msg.GetMessage().GetKey()
|
|
|
|
if msgKey.GetFromMe() {
|
2023-01-28 13:57:53 -08:00
|
|
|
senderJID = ownID
|
2022-11-26 15:42:16 -08:00
|
|
|
} else if chatJID.Server == types.DefaultUserServer {
|
|
|
|
senderJID = chatJID
|
|
|
|
} else if msgKey.GetParticipant() != "" {
|
|
|
|
senderJID, _ = types.ParseJID(msgKey.GetParticipant())
|
|
|
|
} else if msg.GetMessage().GetParticipant() != "" {
|
|
|
|
senderJID, _ = types.ParseJID(msg.GetMessage().GetParticipant())
|
|
|
|
}
|
|
|
|
if senderJID.IsEmpty() || msgKey.GetId() == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
secrets = append(secrets, store.MessageSecretInsert{
|
|
|
|
Chat: chatJID,
|
|
|
|
Sender: senderJID,
|
|
|
|
ID: msgKey.GetId(),
|
|
|
|
Secret: secret,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(secrets) > 0 {
|
|
|
|
cli.Log.Debugf("Storing %d message secret keys in history sync", len(secrets))
|
|
|
|
err := cli.Store.MsgSecrets.PutMessageSecrets(secrets)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("Failed to store message secret keys in history sync: %v", err)
|
|
|
|
} else {
|
|
|
|
cli.Log.Infof("Stored %d message secret keys from history sync", len(secrets))
|
|
|
|
}
|
|
|
|
}
|
2023-01-28 13:57:53 -08:00
|
|
|
if len(privacyTokens) > 0 {
|
|
|
|
cli.Log.Debugf("Storing %d privacy tokens in history sync", len(privacyTokens))
|
|
|
|
err := cli.Store.PrivacyTokens.PutPrivacyTokens(privacyTokens...)
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Errorf("Failed to store privacy tokens in history sync: %v", err)
|
|
|
|
} else {
|
|
|
|
cli.Log.Infof("Stored %d privacy tokens from history sync", len(privacyTokens))
|
|
|
|
}
|
|
|
|
}
|
2022-06-11 14:07:42 -07:00
|
|
|
}
|
2022-01-30 15:27:37 -08:00
|
|
|
|
2023-08-05 11:43:19 -07:00
|
|
|
func (cli *Client) handleDecryptedMessage(info *types.MessageInfo, msg *waProto.Message, retryCount int) {
|
2022-06-11 14:07:42 -07:00
|
|
|
cli.processProtocolParts(info, msg)
|
2023-08-05 11:43:19 -07:00
|
|
|
evt := &events.Message{Info: *info, RawMessage: msg, RetryCount: retryCount}
|
2022-06-11 14:07:42 -07:00
|
|
|
cli.dispatchEvent(evt.UnwrapRaw())
|
2022-01-30 15:27:37 -08:00
|
|
|
}
|
|
|
|
|
2024-05-23 14:44:31 -07:00
|
|
|
func (cli *Client) sendProtocolMessageReceipt(id types.MessageID, msgType types.ReceiptType) {
|
2022-08-13 07:14:26 -07:00
|
|
|
clientID := cli.Store.ID
|
|
|
|
if len(id) == 0 || clientID == nil {
|
2022-01-30 15:27:37 -08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
err := cli.sendNode(waBinary.Node{
|
|
|
|
Tag: "receipt",
|
|
|
|
Attrs: waBinary.Attrs{
|
2024-05-23 14:44:31 -07:00
|
|
|
"id": string(id),
|
|
|
|
"type": string(msgType),
|
2022-08-13 07:14:26 -07:00
|
|
|
"to": types.NewJID(clientID.User, types.LegacyUserServer),
|
2022-01-30 15:27:37 -08:00
|
|
|
},
|
|
|
|
Content: nil,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
cli.Log.Warnf("Failed to send acknowledgement for protocol message %s: %v", id, err)
|
|
|
|
}
|
|
|
|
}
|