~samwhited/xmpp

ref: 3ca280202eb041adb381e0177c480615ebd2c97d xmpp/examples/msgrepl/main.go -rw-r--r-- 3.9 KiB
3ca28020Sam Whited xmpp, sasl2: use Session ConnectionState for SASL 1 year, 1 month ago
                                                                                
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
// Copyright 2019 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

// The msgrepl command listens on the given JID and prints and sends messages.
//
// For more information try running the command and typing "help" at the prompt.
package main

import (
	"bufio"
	"context"
	"crypto/tls"
	"encoding/xml"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	"time"

	"mellium.im/sasl"
	"mellium.im/xmlstream"
	"mellium.im/xmpp"
	"mellium.im/xmpp/jid"
	"mellium.im/xmpp/stanza"
)

const (
	prompt  = "> "
	envAddr = "XMPP_ADDR"
	envPass = "XMPP_PASS"
)

// messageBody is a message stanza that contains a body. It is normally used for
// chat messages.
type messageBody struct {
	stanza.Message
	Body string `xml:"body"`
}

func main() {
	logger := log.New(os.Stderr, "", log.LstdFlags)

	// Get and parse the XMPP address to send from.
	addr := os.Getenv(envAddr)
	if addr == "" {
		logger.Fatalf("Environment variable $%s unset", envAddr)
	}

	parsedAddr, err := jid.Parse(addr)
	if err != nil {
		logger.Fatalf("Error parsing address %q: %w", addr, err)
	}

	// Get the password to use when logging in.
	pass := os.Getenv(envPass)
	if pass == "" {
		logger.Fatalf("Environment variable $%s unset", envPass)
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Login to the XMPP server.
	logger.Println("Logging in…")
	dialCtx, dialCtxCancel := context.WithTimeout(ctx, 30*time.Second)
	session, err := xmpp.DialClientSession(
		dialCtx, parsedAddr,
		xmpp.BindResource(),
		xmpp.StartTLS(true, &tls.Config{
			ServerName: parsedAddr.Domain().String(),
		}),
		xmpp.SASL("", pass, sasl.ScramSha1Plus, sasl.ScramSha1, sasl.Plain),
	)
	dialCtxCancel()
	if err != nil {
		logger.Fatalf("Error loging in: %w", err)
	}
	defer func() {
		if err := session.Close(); err != nil {
			logger.Fatalf("Error ending session: %w", err)
		}
		if err := session.Conn().Close(); err != nil {
			logger.Fatalf("Error closing connection: %w", err)
		}
	}()

	// Send initial presence to let the server know we want to receive messages.
	err = session.Send(ctx, stanza.Presence{Type: stanza.AvailablePresence}.Wrap(nil))
	if err != nil {
		logger.Fatalf("Error sending initial presence: %w", err)
	}

	// Handle incoming messages.
	go func() {
		err := session.Serve(xmpp.HandlerFunc(func(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
			d := xml.NewTokenDecoder(t)
			// Ignore anything that's not a message. In a real system we'd want to at
			// least respond to IQs.
			if start.Name.Local != "message" {
				return nil
			}

			msg := messageBody{}
			err = d.DecodeElement(&msg, start)
			if err != nil && err != io.EOF {
				logger.Printf("Error decoding message: %q", err)
				return nil
			}

			if msg.Body != "" {
				fmt.Printf("\nFrom %s: %q\n"+prompt, msg.From.Bare(), msg.Body)
			}
			return nil
		}))
		if err != nil {
			logger.Fatalf("Error handling incoming messages: %w", err)
		}
	}()

	printHelp()

	userInput := bufio.NewScanner(os.Stdin)
	for {
		fmt.Print(prompt)
		scanned := userInput.Scan()
		if !scanned {
			break
		}

		msg := userInput.Text()
		if msg == "" {
			return
		}

		if msg == "help" {
			printHelp()
			continue
		}

		idx := strings.IndexByte(msg, ':')
		if idx == -1 {
			printHelp()
			continue
		}

		parsedToAddr, err := jid.Parse(msg[:idx])
		if err != nil {
			logger.Printf("Error parsing address: %w", err)
			continue
		}

		msg = strings.TrimSpace(msg[idx+1:])

		err = session.Encode(messageBody{
			Message: stanza.Message{
				To:   parsedToAddr,
				From: parsedAddr,
				Type: stanza.ChatMessage,
			},
			Body: msg,
		})
		if err != nil {
			logger.Fatalf("Error sending message: %w", err)
		}
	}
	if err := userInput.Err(); err != nil {
		logger.Fatalf("Error reading user input: %w", err)
	}
}

func printHelp() {
	fmt.Println("Enter a JID, a colon, and a message to send. eg. me@example.net: Test message")
}