Cotton code
263 lines · 6.4 KB · GoRaw
package mainimport (	"bufio"	"context"	"encoding/json"	"errors"	"net"	"os"	"sync"	"time")// Serve listens on the socket until ctx ends. Any number of connections may send requests (the server's// pairing route and the ingest source both do); events go to the one connection that sent `subscribe`,// and a later subscriber replaces it. A subscriber first receives the whole outbox again (the client// dedupes by seq and by WhatsApp's message id, so a replay is harmless).func Serve(ctx context.Context, path string, h *Hub) error {	_ = os.Remove(path)	ln, err := net.Listen("unix", path)	if err != nil {		return err	}	if err := os.Chmod(path, 0o600); err != nil {		ln.Close()		return err	}	go func() { <-ctx.Done(); ln.Close() }()	subs := &subscriber{}	for {		conn, err := ln.Accept()		if err != nil {			if ctx.Err() != nil {				return nil			}			return err		}		go serveConn(ctx, conn, h, subs)	}}// subscriber is the one connection events flow to.type subscriber struct {	mu     sync.Mutex	cancel context.CancelFunc}func (s *subscriber) take(ctx context.Context) context.Context {	s.mu.Lock()	defer s.mu.Unlock()	if s.cancel != nil {		s.cancel()	}	sctx, cancel := context.WithCancel(ctx)	s.cancel = cancel	return sctx}type connWriter struct {	mu   sync.Mutex	conn net.Conn}func (w *connWriter) write(v any) error {	line, err := encodeLine(v)	if err != nil {		return err	}	w.mu.Lock()	defer w.mu.Unlock()	_ = w.conn.SetWriteDeadline(time.Now().Add(30 * time.Second))	_, err = w.conn.Write(line)	return err}func (w *connWriter) writeRaw(line string) error {	w.mu.Lock()	defer w.mu.Unlock()	_ = w.conn.SetWriteDeadline(time.Now().Add(30 * time.Second))	_, err := w.conn.Write([]byte(line + "\n"))	return err}func serveConn(parent context.Context, conn net.Conn, h *Hub, subs *subscriber) {	ctx, cancel := context.WithCancel(parent)	defer cancel()	defer conn.Close()	go func() { <-ctx.Done(); conn.Close() }()	w := &connWriter{conn: conn}	subscribed := false	sc := bufio.NewScanner(conn)	sc.Buffer(make([]byte, 64*1024), 4*1024*1024)	for sc.Scan() {		var req Request		if err := json.Unmarshal(sc.Bytes(), &req); err != nil {			_ = w.write(Reply{Reply: 0, OK: false, Error: "bad request: " + err.Error()})			continue		}		if req.Op == "subscribe" {			if !subscribed {				subscribed = true				sctx := subs.take(ctx)				go pumpOutbox(sctx, w, h.outbox)				go pumpLive(sctx, w, h.live)			}			_ = w.write(Reply{Reply: req.ID, OK: true})			continue		}		// Bound outstanding operations even when a session/library call stalls.		select {		case h.requests <- struct{}{}:		default:			_ = w.write(Reply{Reply: req.ID, OK: false, Error: "busy"})			continue		}		go func(req Request) {			defer func() { <-h.requests }()			result, err := dispatch(ctx, h, &req)			rep := Reply{Reply: req.ID, OK: err == nil, Result: result}			if err != nil {				rep.Error = err.Error()			}			_ = w.write(rep)		}(req)	}}func pumpLive(ctx context.Context, w *connWriter, live <-chan *Event) {	for {		select {		case <-ctx.Done():			return		case ev := <-live:			if w.write(ev) != nil {				return			}		}	}}func pumpOutbox(ctx context.Context, w *connWriter, o *Outbox) {	var cursor int64	tick := time.NewTicker(time.Second)	defer tick.Stop()	for {		seqs, bodies, err := o.After(cursor, 200)		if err == nil {			for i, body := range bodies {				if w.writeRaw(body) != nil {					return				}				cursor = seqs[i]			}			if len(bodies) == 200 {				continue			}		}		select {		case <-ctx.Done():			return		case <-o.notify:		case <-tick.C:		}	}}func dispatch(ctx context.Context, h *Hub, req *Request) (any, error) {	if h.starting.Load() || !h.mu.TryLock() {		return nil, errors.New("busy")	}	h.mu.Unlock()	switch req.Op {	case "hello":		accounts, err := h.Accounts()		if err != nil {			return nil, err		}		pending, _ := h.outbox.Pending()		wanted, _ := h.outbox.WantedPictures()		hello := map[string]any{"version": ProtocolVersion, "accounts": accounts, "pending": pending, "pictures": picturesDigest(wanted)}		if u := h.Unlinked(); u != nil {			hello["unlinked"] = u		}		return hello, nil	case "accounts":		return h.Accounts()	case "events":		limit := req.Limit		if limit <= 0 || limit > 2000 {			limit = 500		}		_, bodies, err := h.outbox.After(req.After, limit)		if err != nil {			return nil, err		}		raw := make([]json.RawMessage, len(bodies))		for i, b := range bodies {			raw[i] = json.RawMessage(b)		}		return map[string]any{"events": raw}, nil	case "ack":		return nil, h.outbox.Ack(req.Seq)	case "pair":		id, err := h.Pair(req.Phone)		if err != nil {			return nil, err		}		return map[string]string{"pairing": id}, nil	case "pair_status":		return h.PairStatus(req.Pairing)	case "pair_cancel":		return nil, h.CancelPairing(req.Pairing)	case "passkey_response":		return nil, h.PasskeyResponse(req.Pairing, req.Response)	case "passkey_confirm":		return nil, h.PasskeyConfirm(req.Pairing)	case "history":		cctx, cancel := context.WithTimeout(ctx, 30*time.Second)		defer cancel()		return nil, h.RequestHistory(cctx, req.Account, req.Chat, req.Before, req.Count)	case "media":		cctx, cancel := context.WithTimeout(ctx, 5*time.Minute)		defer cancel()		n, err := h.DownloadMedia(cctx, req.Account, req.Media, req.Dest)		if err != nil {			return nil, err		}		return map[string]any{"path": req.Dest, "bytes": n}, nil	case "pictures":		return nil, h.outbox.SetWantedPictures(req.Chats)	case "picture":		cctx, cancel := context.WithTimeout(ctx, 2*time.Minute)		defer cancel()		n, err := h.DownloadPicture(cctx, req.Account, req.Chat, req.Dest)		if err != nil {			return nil, err		}		return map[string]any{"path": req.Dest, "bytes": n}, nil	case "send":		// A file goes up to WhatsApp's media hosts first: a video can take minutes.		cctx, cancel := context.WithTimeout(ctx, sendTimeout(req.Kind))		defer cancel()		if sourceActs[req.Kind] {			return h.SourceAct(cctx, req)		}		if req.Kind != "" && req.Kind != "text" {			return h.SendKind(cctx, req)		}		return h.Send(cctx, req.Account, req.Chat, req.Text, req.MessageID, quoteOf(req))	case "census":		return h.outbox.Census()	case "hold":		return nil, h.Hold(req.Accounts)	case "unlink":		cctx, cancel := context.WithTimeout(ctx, 30*time.Second)		defer cancel()		return nil, h.Unlink(cctx, req.Account)	default:		return nil, errors.New("unknown op " + req.Op)	}}