Cotton code
565 lines · 17.1 KB · GoRaw
package mainimport (	"context"	"encoding/json"	"errors"	"fmt"	"os"	"path/filepath"	"sync"	"sync/atomic"	"time"	"go.mau.fi/whatsmeow"	"go.mau.fi/whatsmeow/store"	"go.mau.fi/whatsmeow/store/sqlstore"	"go.mau.fi/whatsmeow/types"	"go.mau.fi/whatsmeow/types/events"	waLog "go.mau.fi/whatsmeow/util/log")// Hub holds one whatsmeow client per paired account (WhatsApp allows four linked devices per// number, and one Mac may hold several numbers), the pairings in progress, and the live channel// to whichever client is connected to the socket.type Hub struct {	container *sqlstore.Container	outbox    *Outbox	log       waLog.Logger	starting atomic.Bool	requests chan struct{}	mu       sync.Mutex	sessions map[string]*session	pairings map[string]*pairing	finished map[string]PairState // pairings that ended, kept for the poll that comes after	groups   map[string]bool      // group chats whose name was already sent this run	live chan *Event // transient events; dropped when no client is listening	calls *Calls // live calls followed until they end (calls.go)	retries retries // downloads waiting for the owner's phone to upload a file again (reupload.go)	// Numbers whose connection the person paused: linked, never connected, so nothing is read.	// WhatsApp keeps what arrives for a linked device and delivers it on the next connect.	held     map[string]bool	heldPath string	// The last number WhatsApp removed, kept on disk until a number links again (unlinked.go).	unlinked     *Unlinked	unlinkedPath string}type session struct {	cli       *whatsmeow.Client	state     string	lastEvent int64 // unix seconds of the newest message taken this run}func NewHub(c *sqlstore.Container, o *Outbox, log waLog.Logger) *Hub {	return &Hub{requests: make(chan struct{}, 32), container: c, outbox: o, log: log, sessions: map[string]*session{}, pairings: map[string]*pairing{}, finished: map[string]PairState{}, groups: map[string]bool{}, held: map[string]bool{}, live: make(chan *Event, 64), calls: NewCalls()}}func (h *Hub) StartAll(ctx context.Context) error {	devices, err := h.container.GetAllDevices(ctx)	if err != nil {		return err	}	for _, d := range devices {		if d.ID == nil {			continue		}		cli := h.newClient(d)		account := d.ID.ToNonAD().String()		h.mu.Lock()		held := h.held[account]		state := "connecting"		if held {			state = "held"		}		h.sessions[account] = &session{cli: cli, state: state}		h.mu.Unlock()		if held {			continue		}		if err := cli.ConnectContext(ctx); err != nil {			h.setState(account, "disconnected", err.Error())		}	}	return nil}func (h *Hub) StopAll() {	h.mu.Lock()	var clients []interface{ Disconnect() }	for _, s := range h.sessions {		clients = append(clients, s.cli)	}	for _, p := range h.pairings {		p.cancel()		clients = append(clients, p.cli)	}	h.mu.Unlock()	// Disconnect waits for event handlers, which take mu in setState. Never	// hold the session lock while waiting for the session to stop.	for _, cli := range clients {		cli.Disconnect()	}}func (h *Hub) newClient(d *store.Device) *whatsmeow.Client {	cli := whatsmeow.NewClient(d, h.log.Sub("client"))	cli.EnableAutoReconnect = true	cli.AddEventHandler(func(evt any) { h.handle(cli, evt) })	return cli}func accountOf(cli *whatsmeow.Client) string {	if cli.Store.ID == nil {		return ""	}	return cli.Store.ID.ToNonAD().String()}func (h *Hub) resolver(cli *whatsmeow.Client) PNResolver {	return func(lid types.JID) (types.JID, bool) {		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)		defer cancel()		pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)		if err != nil || pn.IsEmpty() {			return types.EmptyJID, false		}		return pn, true	}}// durable writes an event to the outbox; a failure here would lose a message, so it is logged loudly.// A chat event's name is remembered and every message is stamped with its chat's name.func (h *Hub) durable(ev *Event) {	if ev.Event == "chat" {		_ = h.outbox.SetChatName(ev.Account, ev.Chat, ev.Name)	}	if ev.Message != nil && ev.Message.ChatName == "" {		ev.Message.ChatName = h.outbox.ChatName(ev.Account, ev.Message.Chat)	}	if _, err := h.outbox.Append(ev); err != nil {		h.log.Errorf("outbox append failed, event lost: %v (%s %s)", err, ev.Event, ev.Account)	}}func (h *Hub) transient(ev *Event) {	select {	case h.live <- ev:	default:	}}func (h *Hub) setState(account, state, detail string) {	h.mu.Lock()	if s, ok := h.sessions[account]; ok {		if state == "disconnected" && h.held[account] {			state = "held"		}		s.state = state	}	h.mu.Unlock()	h.transient(&Event{Event: "state", Account: account, State: state, Detail: detail})}func (h *Hub) handle(cli *whatsmeow.Client, evt any) {	account := accountOf(cli)	switch e := evt.(type) {	case *events.Message:		chat, _ := normalize(e.Info.Chat, h.resolver(cli))		h.census("live", e, chat)		if ev := liveVote(context.Background(), cli, e, h.resolver(cli)); ev != nil {			ev.Account = account			h.durable(ev)			h.touch(account, e.Info.Timestamp.Unix())			return		}		if ev := Convert(e, "live", h.resolver(cli)); ev != nil {			ev.Account = account			switch {			case e.Info.Chat.Server == types.BroadcastServer:				// A broadcast list is no group: nothing to ask WhatsApp about. (A				// status, status@broadcast, never gets here: Convert drops it.)			case e.Info.IsGroup:				h.announceGroup(cli, account, e.Info.Chat)			case !e.Info.IsFromMe && e.Info.PushName != "" && h.outbox.ChatName(account, ev.Message.Chat) == "":				_ = h.outbox.SetChatName(account, ev.Message.Chat, e.Info.PushName)			}			h.durable(ev)			h.touch(account, e.Info.Timestamp.Unix())		}	case *events.CallOffer, *events.CallOfferNotice, *events.CallAccept, *events.CallReject, *events.CallTerminate:		// A call, followed until it ends; then one line in its chat. Nothing here answers or rejects it.		own := ""		if cli.Store.ID != nil {			own = cli.Store.ID.User		}		if ev := h.calls.Event(account, own, e, h.resolver(cli)); ev != nil {			h.outbox.Count("live", "call")			h.durable(ev)			h.touch(account, ev.Message.Timestamp)		}	case *events.Picture:		// A contact's or a group's picture changed: ask about it next (still one question every few seconds).		chat, _ := normalize(e.JID, h.resolver(cli))		_ = h.outbox.PictureChanged(chat.String())	case *events.MediaRetry:		h.retries.answered(e)	case *events.HistorySync:		h.history(cli, account, e)	case *events.Connected:		h.setState(account, "connected", "")	case *events.Disconnected:		h.setState(account, "disconnected", "")	case *events.StreamReplaced:		h.setState(account, "replaced", "another copy of this session connected")	case *events.TemporaryBan:		h.setState(account, "banned", e.String())	case *events.ClientOutdated:		h.setState(account, "outdated", "WhatsApp refuses this helper's version")	case *events.LoggedOut:		h.mu.Lock()		_, linked := h.sessions[account]		delete(h.sessions, account)		h.mu.Unlock()		if linked {			h.recordUnlinked(account, e.Reason.String(), time.Now())		}		// Durable: Cotton must learn the number was unlinked even if it was not listening.		h.durable(&Event{Event: "state", Account: account, State: "logged_out", Detail: e.Reason.String()})	}}func (h *Hub) announceGroup(cli *whatsmeow.Client, account string, chat types.JID) {	key := account + "|" + chat.String()	h.mu.Lock()	seen := h.groups[key]	h.groups[key] = true	h.mu.Unlock()	if seen {		return	}	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)	defer cancel()	info, err := cli.GetGroupInfo(ctx, chat)	if err != nil {		h.mu.Lock()		delete(h.groups, key)		h.mu.Unlock()		return	}	h.durable(&Event{Event: "chat", Account: account, Chat: chat.String(), Name: info.Name, IsGroup: true})}func (h *Hub) history(cli *whatsmeow.Client, account string, e *events.HistorySync) {	resolve := h.resolver(cli)	for _, conv := range e.Data.GetConversations() {		chatJID, err := types.ParseJID(conv.GetID())		if err != nil || IsStatus(chatJID) {			// The status feed's history is passed over whole: messages only.			continue		}		isGroup := chatJID.Server == types.GroupServer		name := conv.GetName()		if name == "" {			name = conv.GetDisplayName()		}		normChat, _ := normalize(chatJID, resolve)		if name != "" || isGroup {			h.durable(&Event{Event: "chat", Account: account, Chat: normChat.String(), Name: name, IsGroup: isGroup})		}		for _, hm := range conv.GetMessages() {			web := hm.GetMessage()			if web == nil {				continue			}			if web.GetMessage() == nil {				h.censusStub(web)				// A message deleted for everyone before the link saw the delete: its place in the history.				if ev := historyRevoke(web, chatJID, resolve); ev != nil {					ev.Account = account					h.durable(ev)				}				// A missed call WhatsApp kept in the history: its line in the chat.				if ev := historyMissedCall(web, chatJID, resolve); ev != nil {					ev.Account = account					h.durable(ev)				}			}			parsed, err := cli.ParseWebMessage(chatJID, web)			if err != nil {				h.outbox.Count("history", "unreadable")				continue			}			if parsed.Message != nil {				h.census("history", parsed, normChat)			}			if ev := Convert(parsed, "history", resolve); ev != nil {				ev.Account = account				h.durable(ev)			}			for _, vote := range historyVotes(web, chatJID, resolve) {				vote.Account = account				h.outbox.Count("history", "poll vote")				h.durable(vote)			}		}	}	h.transient(&Event{Event: "history_chunk", Account: account, Detail: fmt.Sprintf("%s %d%%", e.Data.GetSyncType().String(), e.Data.GetProgress())})}func (h *Hub) client(account string) (*whatsmeow.Client, error) {	if !h.mu.TryLock() {		return nil, errors.New("busy")	}	defer h.mu.Unlock()	s, ok := h.sessions[account]	if !ok {		return nil, errors.New("not_linked")	}	if s.state != "connected" {		return nil, errors.New("busy")	}	return s.cli, nil}type AccountState struct {	Account   string `json:"account"`	Name      string `json:"name,omitempty"`	State     string `json:"state"`	LastEvent int64  `json:"last_event,omitempty"`}func (h *Hub) Accounts() ([]AccountState, error) {	if !h.mu.TryLock() {		return nil, errors.New("busy")	}	defer h.mu.Unlock()	out := make([]AccountState, 0, len(h.sessions))	for a, s := range h.sessions {		out = append(out, AccountState{Account: a, Name: s.cli.Store.PushName, State: s.state, LastEvent: s.lastEvent})	}	return out, nil}// RequestHistory asks the phone for older messages in one chat, before the oldest one Cotton holds.// The phone must be online; the answer arrives later as history events (sync type ON_DEMAND). The// request is a message to the account's own phone, never to a chat.func (h *Hub) RequestHistory(ctx context.Context, account, chat string, before *MessageRef, count int) error {	cli, err := h.client(account)	if err != nil {		return err	}	if before == nil || before.ID == "" {		return errors.New("history needs the oldest message held in the chat")	}	chatJID, err := types.ParseJID(chat)	if err != nil {		return err	}	if count <= 0 || count > 500 {		count = 50	}	info := &types.MessageInfo{		MessageSource: types.MessageSource{Chat: chatJID, IsFromMe: before.FromMe, IsGroup: chatJID.Server == types.GroupServer},		ID:            before.ID,		Timestamp:     time.Unix(before.Timestamp, 0),	}	if before.Sender != "" {		if s, err := types.ParseJID(before.Sender); err == nil {			info.Sender = s		}	}	_, err = cli.SendPeerMessage(ctx, cli.BuildHistorySyncRequest(info, count))	return err}var mediaTypes = map[string]whatsmeow.MediaType{	"image": whatsmeow.MediaImage, "sticker": whatsmeow.MediaImage,	"video": whatsmeow.MediaVideo, "audio": whatsmeow.MediaAudio, "document": whatsmeow.MediaDocument,}var mmsTypes = map[string]string{"image": "image", "sticker": "image", "video": "video", "audio": "audio", "document": "document"}// ErrGone marks media WhatsApp's servers no longer hold; the backup and export doors stay for those.var ErrGone = errors.New("gone")// Unfetchable is media no request can fetch: a pointer WhatsApp sent without what a download needs,// or bytes that are not the file the pointer names. Asking again fetches nothing more, so the reader// lands the message saying what it was; the reply's error starts "unfetchable: " and says why.type Unfetchable struct{ Why string }func (u Unfetchable) Error() string { return "unfetchable: " + u.Why }// fetchable says why a pointer cannot fetch its file, or nil when it can: a download needs the path// on WhatsApp's media hosts, the key that decrypts it, and the SHA-256 of the ciphertext and of the// file, which whatsmeow checks the bytes against.func (m *MediaPointer) fetchable() error {	switch {	case m == nil:		return Unfetchable{"no media pointer"}	case m.DirectPath == "" || m.DirectPath[0] != '/':		return Unfetchable{"media pointer incomplete: no direct path"}	case len(m.MediaKey) == 0:		return Unfetchable{"media pointer incomplete: no media key"}	case len(m.FileEncSHA256) != 32:		return Unfetchable{"media pointer incomplete: no ciphertext SHA-256"}	case len(m.FileSHA256) != 32:		return Unfetchable{"media pointer incomplete: no file SHA-256"}	}	if _, ok := mediaTypes[m.Type]; !ok {		return Unfetchable{fmt.Sprintf("unknown media type %q", m.Type)}	}	return nil}// corrupt are the download failures that say the bytes on WhatsApp's hosts are not the file the// pointer names: fetched again, they are the same bytes.var corrupt = []error{	whatsmeow.ErrTooShortFile, whatsmeow.ErrInvalidMediaHMAC, whatsmeow.ErrInvalidMediaEncSHA256,	whatsmeow.ErrInvalidMediaSHA256, whatsmeow.ErrInvalidUnencryptedMediaSHA256, whatsmeow.ErrFileLengthMismatch,}func (h *Hub) DownloadMedia(ctx context.Context, account string, m *MediaPointer, dest string) (int, error) {	if err := m.fetchable(); err != nil {		return 0, err	}	cli, err := h.client(account)	if err != nil {		return 0, err	}	data, err := cli.DownloadMediaWithPath(ctx, m.DirectPath, m.FileEncSHA256, m.FileSHA256, m.MediaKey, mediaTypes[m.Type], mmsTypes[m.Type], false)	if expired(err) {		// WhatsApp's servers no longer hold it: the owner's phone is asked to upload it again, as WhatsApp's own		// linked devices do, and the file is fetched from where it now is.		path, again := h.reupload(ctx, cli, m)		if again != nil {			return 0, again		}		data, err = cli.DownloadMediaWithPath(ctx, path, m.FileEncSHA256, m.FileSHA256, m.MediaKey, mediaTypes[m.Type], mmsTypes[m.Type], false)	}	if err != nil {		if expired(err) {			return 0, ErrGone		}		for _, bad := range corrupt {			if errors.Is(err, bad) {				return 0, Unfetchable{err.Error()}			}		}		return 0, err	}	if err := os.MkdirAll(filepath.Dir(dest), 0o700); err != nil {		return 0, err	}	tmp := dest + ".part"	if err := os.WriteFile(tmp, data, 0o600); err != nil {		return 0, err	}	return len(data), os.Rename(tmp, dest)}// Unlink removes this Mac from the number's linked devices and forgets the session.func (h *Hub) Unlink(ctx context.Context, account string) error {	cli, err := h.client(account)	if err != nil {		return err	}	if err := cli.Logout(ctx); err != nil {		return err	}	h.mu.Lock()	delete(h.sessions, account)	h.mu.Unlock()	return nil}// touch records the newest live message an account took, for Connections' "last read".func (h *Hub) touch(account string, ts int64) {	h.mu.Lock()	defer h.mu.Unlock()	if s, ok := h.sessions[account]; ok && ts > s.lastEvent {		s.lastEvent = ts	}}// LoadHeld reads the held numbers kept from the last run, before any session connects.func (h *Hub) LoadHeld(path string) error {	h.heldPath = path	b, err := os.ReadFile(path)	if errors.Is(err, os.ErrNotExist) {		return nil	}	if err != nil {		return err	}	var accounts []string	if err := json.Unmarshal(b, &accounts); err != nil {		return err	}	h.mu.Lock()	defer h.mu.Unlock()	for _, a := range accounts {		h.held[a] = true	}	return nil}// Hold makes exactly these numbers held: each is disconnected (it stays linked) and every other// linked number connects again. The list is kept on disk so a restart never reads a held number.func (h *Hub) Hold(accounts []string) error {	if !h.mu.TryLock() {		return errors.New("busy")	}	// Persist and publish the same hold list under one lock; network work is below it.	locked := true	defer func() {		if locked {			h.mu.Unlock()		}	}()	next := map[string]bool{}	for _, a := range accounts {		next[a] = true	}	if h.heldPath != "" {		b, err := json.Marshal(accounts)		if err != nil {			return err		}		tmp := h.heldPath + ".part"		if err := os.WriteFile(tmp, b, 0o600); err != nil {			return err		}		if err := os.Rename(tmp, h.heldPath); err != nil {			return err		}	}	h.held = next	var release, hold []*whatsmeow.Client	for a, s := range h.sessions {		if next[a] && s.state != "held" {			s.state = "held"			hold = append(hold, s.cli)		} else if !next[a] && s.state == "held" {			s.state = "connecting"			release = append(release, s.cli)		}	}	h.mu.Unlock()	locked = false	for _, cli := range hold {		cli.Disconnect()	}	for _, cli := range release {		if err := cli.Connect(); err != nil {			h.setState(accountOf(cli), "disconnected", err.Error())		}	}	return nil}