| 1 |
// Copyright 2011 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// TODO(rsc): |
| 6 |
// More precise error handling. |
| 7 |
// Presence functionality. |
| 8 |
// TODO(mattn): |
| 9 |
// Add proxy authentication. |
| 10 |
|
| 11 |
// Package xmpp implements a simple Google Talk client |
| 12 |
// using the XMPP protocol described in RFC 3920 and RFC 3921. |
| 13 |
package xmpp |
| 14 |
|
| 15 |
import ( |
| 16 |
"bufio" |
| 17 |
"bytes" |
| 18 |
"crypto/hmac" |
| 19 |
"crypto/pbkdf2" |
| 20 |
"crypto/rand" |
| 21 |
"crypto/sha1" |
| 22 |
"crypto/sha256" |
| 23 |
"crypto/sha512" |
| 24 |
"crypto/tls" |
| 25 |
"crypto/x509" |
| 26 |
"encoding/base64" |
| 27 |
"encoding/binary" |
| 28 |
"encoding/xml" |
| 29 |
"errors" |
| 30 |
"fmt" |
| 31 |
"hash" |
| 32 |
"io" |
| 33 |
"log" |
| 34 |
"math/big" |
| 35 |
"net" |
| 36 |
"net/http" |
| 37 |
"net/url" |
| 38 |
"os" |
| 39 |
"regexp" |
| 40 |
"runtime" |
| 41 |
"slices" |
| 42 |
"strconv" |
| 43 |
"strings" |
| 44 |
"sync" |
| 45 |
"time" |
| 46 |
|
| 47 |
"github.com/google/uuid" |
| 48 |
"golang.org/x/net/proxy" |
| 49 |
) |
| 50 |
|
| 51 |
// Default TLS configuration options |
| 52 |
var DefaultConfig = &tls.Config{} //nolint: gosec,G402 // In go1.25 TLS 1.2 used as default. Used by servers for older clients. |
| 53 |
|
| 54 |
// DebugWriter is the writer used to write debugging output to. |
| 55 |
type debugWriter struct { |
| 56 |
w io.Writer |
| 57 |
prefix string |
| 58 |
} |
| 59 |
|
| 60 |
func (d debugWriter) Write(p []byte) (int, error) { |
| 61 |
nl := []byte("\n") |
| 62 |
switch { |
| 63 |
case len(p) == 0: |
| 64 |
return 0, nil |
| 65 |
case string(p) == "": |
| 66 |
return len(p), nil |
| 67 |
case string(p) == "\n": |
| 68 |
return len(p), nil |
| 69 |
} |
| 70 |
data := append([]byte(d.prefix), p...) |
| 71 |
if !strings.HasSuffix(string(p), "\n") { |
| 72 |
data = append(data, nl...) |
| 73 |
} |
| 74 |
n, err := d.w.Write(data) |
| 75 |
if err != nil { |
| 76 |
return n, err |
| 77 |
} |
| 78 |
if n != len(data) { |
| 79 |
return n, io.ErrShortWrite |
| 80 |
} |
| 81 |
return len(p), nil |
| 82 |
} |
| 83 |
|
| 84 |
// Cookie is a unique XMPP session identifier |
| 85 |
type Cookie uint64 |
| 86 |
|
| 87 |
func getCookie() Cookie { |
| 88 |
var buf [8]byte |
| 89 |
if _, err := rand.Reader.Read(buf[:]); err != nil { |
| 90 |
panic("Failed to read random bytes: " + err.Error()) |
| 91 |
} |
| 92 |
return Cookie(binary.LittleEndian.Uint64(buf[:])) |
| 93 |
} |
| 94 |
|
| 95 |
func getUUID() string { |
| 96 |
// Use github.com/google/uuid as XEP-0359 requires an UUID according to |
| 97 |
// RFC 4122. |
| 98 |
id, err := uuid.NewV7() |
| 99 |
if err != nil { |
| 100 |
log.Fatal(err) |
| 101 |
} |
| 102 |
return id.String() |
| 103 |
} |
| 104 |
|
| 105 |
// Fast holds the XEP-0484 fast token, mechanism and expiry date |
| 106 |
type Fast struct { |
| 107 |
Token string |
| 108 |
Mechanism string |
| 109 |
Expiry time.Time |
| 110 |
} |
| 111 |
|
| 112 |
// Client holds XMPP connection options |
| 113 |
type Client struct { |
| 114 |
conn net.Conn // connection to server |
| 115 |
jid string // Jabber ID for our connection |
| 116 |
domain string |
| 117 |
nextMutex sync.Mutex // Mutex to prevent multiple access to xml.Decoder |
| 118 |
shutdown bool // Variable signalling that the stream will be closed |
| 119 |
p *xml.Decoder |
| 120 |
stanzaWriter io.Writer |
| 121 |
subIDs []string // IDs of subscription stanzas |
| 122 |
unsubIDs []string // IDs of unsubscription stanzas |
| 123 |
itemsIDs []string // IDs of item requests |
| 124 |
periodicPings bool // Send periodic server pings. |
| 125 |
periodicPingTicker *time.Ticker // Ticker for periodic pings. |
| 126 |
periodicPingPeriod time.Duration // Period for periodic ping ticker. |
| 127 |
periodicPingTimeout time.Duration // Timeout for periodic pings. |
| 128 |
periodicPingID string // ID of the current periodic ping request. |
| 129 |
periodicPingReply bool // True if a reply for the current ping request was received. |
| 130 |
LimitMaxBytes int // Maximum stanza size (XEP-0478: Stream Limits Advertisement) |
| 131 |
LimitIdleSeconds int // Maximum idle seconds (XEP-0478: Stream Limits Advertisement) |
| 132 |
Mechanism string // SCRAM mechanism used. |
| 133 |
Fast Fast // XEP-0484 FAST Token, mechanism and expiry. |
| 134 |
Options *Options // Connection Options, including reported software versions |
| 135 |
} |
| 136 |
|
| 137 |
func (c *Client) JID() string { |
| 138 |
return c.jid |
| 139 |
} |
| 140 |
|
| 141 |
func containsIgnoreCase(s, substr string) bool { |
| 142 |
s, substr = strings.ToUpper(s), strings.ToUpper(substr) |
| 143 |
return strings.Contains(s, substr) |
| 144 |
} |
| 145 |
|
| 146 |
func connect(host string, user string, timeout time.Duration) (net.Conn, error) { |
| 147 |
addr := host |
| 148 |
|
| 149 |
if strings.TrimSpace(host) == "" { |
| 150 |
a := strings.SplitN(user, "@", 2) |
| 151 |
if len(a) == 2 { |
| 152 |
addr = a[1] |
| 153 |
} |
| 154 |
} |
| 155 |
a := strings.SplitN(host, ":", 2) |
| 156 |
if len(a) == 1 { |
| 157 |
addr += ":5222" |
| 158 |
} |
| 159 |
|
| 160 |
http_proxy := os.Getenv("HTTP_PROXY") |
| 161 |
if http_proxy == "" { |
| 162 |
http_proxy = os.Getenv("http_proxy") |
| 163 |
} |
| 164 |
// test for no proxy, takes a comma separated list with substrings to match |
| 165 |
if http_proxy != "" { |
| 166 |
noproxy := os.Getenv("NO_PROXY") |
| 167 |
if noproxy == "" { |
| 168 |
noproxy = os.Getenv("no_proxy") |
| 169 |
} |
| 170 |
if noproxy != "" { |
| 171 |
nplist := strings.Split(noproxy, ",") |
| 172 |
for _, s := range nplist { |
| 173 |
if containsIgnoreCase(addr, s) { |
| 174 |
http_proxy = "" |
| 175 |
break |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
} |
| 180 |
socks5Target, socks5 := strings.CutPrefix(http_proxy, "socks5://") |
| 181 |
if http_proxy != "" && !socks5 { |
| 182 |
url, err := url.Parse(http_proxy) |
| 183 |
if err == nil { |
| 184 |
addr = url.Host |
| 185 |
} |
| 186 |
} |
| 187 |
var c net.Conn |
| 188 |
var err error |
| 189 |
if socks5 { |
| 190 |
dialer, err := proxy.SOCKS5("tcp", socks5Target, nil, nil) |
| 191 |
if err != nil { |
| 192 |
return nil, err |
| 193 |
} |
| 194 |
c, err = dialer.Dial("tcp", addr) |
| 195 |
if err != nil { |
| 196 |
return nil, err |
| 197 |
} |
| 198 |
} else { |
| 199 |
c, err = net.DialTimeout("tcp", addr, timeout) |
| 200 |
if err != nil { |
| 201 |
return nil, err |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
if http_proxy != "" && !socks5 { |
| 206 |
fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\n", host) |
| 207 |
fmt.Fprintf(c, "Host: %s\r\n", host) |
| 208 |
fmt.Fprintf(c, "\r\n") |
| 209 |
br := bufio.NewReader(c) |
| 210 |
req, _ := http.NewRequest("CONNECT", host, nil) |
| 211 |
resp, err := http.ReadResponse(br, req) |
| 212 |
if err != nil { |
| 213 |
return nil, err |
| 214 |
} |
| 215 |
if resp.StatusCode != 200 { |
| 216 |
f := strings.SplitN(resp.Status, " ", 2) |
| 217 |
return nil, errors.New(f[1]) |
| 218 |
} |
| 219 |
} |
| 220 |
return c, nil |
| 221 |
} |
| 222 |
|
| 223 |
// Options are used to specify additional options for new clients, such as a Resource. |
| 224 |
type Options struct { |
| 225 |
// Host specifies what host to connect to, as either "hostname" or "hostname:port" |
| 226 |
// If host is not specified, the DNS SRV should be used to find the host from the domainpart of the JID. |
| 227 |
// Default the port to 5222. |
| 228 |
Host string |
| 229 |
|
| 230 |
// User specifies what user to authenticate to the remote server. |
| 231 |
User string |
| 232 |
|
| 233 |
// Password supplies the password to use for authentication with the remote server. |
| 234 |
Password string |
| 235 |
|
| 236 |
// DialTimeout is the time limit for establishing a connection. A |
| 237 |
// DialTimeout of zero means no timeout. |
| 238 |
DialTimeout time.Duration |
| 239 |
|
| 240 |
// Resource specifies an XMPP client resource, like "bot", instead of accepting one |
| 241 |
// from the server. Use "" to let the server generate one for your client. |
| 242 |
Resource string |
| 243 |
|
| 244 |
// OAuthScope provides go-xmpp the required scope for OAuth2 authentication. |
| 245 |
OAuthScope string |
| 246 |
|
| 247 |
// OAuthToken provides go-xmpp with the required OAuth2 token used to authenticate |
| 248 |
OAuthToken string |
| 249 |
|
| 250 |
// OAuthXmlNs provides go-xmpp with the required namespaced used for OAuth2 authentication. This is |
| 251 |
// provided to the server as the xmlns:auth attribute of the OAuth2 authentication request. |
| 252 |
OAuthXmlNs string |
| 253 |
|
| 254 |
// TLS Config |
| 255 |
TLSConfig *tls.Config |
| 256 |
|
| 257 |
// InsecureAllowUnencryptedAuth permits authentication over a TCP connection that has not been promoted to |
| 258 |
// TLS by STARTTLS; this could leak authentication information over the network, or permit man in the middle |
| 259 |
// attacks. |
| 260 |
InsecureAllowUnencryptedAuth bool |
| 261 |
|
| 262 |
// NoTLS directs go-xmpp to not use TLS initially to contact the server; instead, a plain old unencrypted |
| 263 |
// TCP connection should be used. (Can be combined with StartTLS to support STARTTLS-based servers.) |
| 264 |
NoTLS bool |
| 265 |
|
| 266 |
// StartTLS directs go-xmpp to STARTTLS if the server supports it; go-xmpp will automatically STARTTLS |
| 267 |
// if the server requires it regardless of this option. |
| 268 |
StartTLS bool |
| 269 |
|
| 270 |
// Debug output |
| 271 |
Debug bool |
| 272 |
|
| 273 |
// DebugWriter specifies where the debug output is written to |
| 274 |
DebugWriter io.Writer |
| 275 |
|
| 276 |
// Use server sessions |
| 277 |
Session bool |
| 278 |
|
| 279 |
// Presence Status |
| 280 |
Status string |
| 281 |
|
| 282 |
// Status message |
| 283 |
StatusMessage string |
| 284 |
|
| 285 |
// Auth mechanism to use |
| 286 |
Mechanism string |
| 287 |
|
| 288 |
// XEP-0474: SASL SCRAM Downgrade Protection |
| 289 |
SSDP bool |
| 290 |
|
| 291 |
// XEP-0388: Extensible SASL Profile |
| 292 |
// Value for software |
| 293 |
UserAgentSW string |
| 294 |
|
| 295 |
// XEP-0388: XEP-0388: Extensible SASL Profile |
| 296 |
// Value for device |
| 297 |
UserAgentDev string |
| 298 |
|
| 299 |
// XEP-0388: Extensible SASL Profile |
| 300 |
// Unique stable identifier for the client installation |
| 301 |
// MUST be a valid UUIDv4 |
| 302 |
UserAgentID string |
| 303 |
|
| 304 |
// Enable XEP-0484: Fast Authentication Streamlining Tokens |
| 305 |
Fast bool |
| 306 |
|
| 307 |
// XEP-0484: Fast Authentication Streamlining Tokens |
| 308 |
// Fast Token |
| 309 |
FastToken string |
| 310 |
|
| 311 |
// XEP-0484: Fast Authentication Streamlining Tokens |
| 312 |
// Fast Mechanism |
| 313 |
FastMechanism string |
| 314 |
|
| 315 |
// XEP-0484: Fast Authentication Streamlining Tokens |
| 316 |
// Invalidate the current token |
| 317 |
FastInvalidate bool |
| 318 |
|
| 319 |
// NoPLAIN forbids authentication using plain passwords |
| 320 |
NoPLAIN bool |
| 321 |
|
| 322 |
// NoSASLUpgrade disables XEP-0480 upgrades. |
| 323 |
NoSASLUpgrade bool |
| 324 |
|
| 325 |
// Send periodic XEP-0199 pings to the server. |
| 326 |
PeriodicServerPings bool |
| 327 |
|
| 328 |
// Period of inactivity after which the client sends a XEP-0199 ping |
| 329 |
// to the server. Specified in milliseconds, defaults to 20.000 (20 seconds). |
| 330 |
PeriodicServerPingsPeriod int |
| 331 |
|
| 332 |
// Timeout for ping replies. If no reply is received in this time period, the |
| 333 |
// connection is considered broken and gets closed. Specified in milliseconds, |
| 334 |
// defaults to 5.000 (5 seconds). |
| 335 |
PeriodicServerPingsTimeout int |
| 336 |
|
| 337 |
// ReportSoftwareVersion if set to true iq response will be generated |
| 338 |
// according to xep-0092. If set to false all iq version queries will be |
| 339 |
// silently ignored. By default set to false. |
| 340 |
ReportSoftwareVersion bool |
| 341 |
|
| 342 |
// SoftwareName is client software name (UserAgent in web browsers terms), |
| 343 |
// reported in response to information query as described in xep-0092. |
| 344 |
// By default it is "go-xmpp" (no quotes), and can be overridden here. |
| 345 |
// Responses can be enabled via ReportSoftwareVersion. |
| 346 |
SoftwareName string |
| 347 |
|
| 348 |
// SoftwareVersion reported in response to iq version as described in |
| 349 |
// xep-0092. If SoftwareName is not overridden in SoftwareName option go-xmpp |
| 350 |
// version will be reported. Otherwise set as "undefined" if not overridden |
| 351 |
// here. |
| 352 |
SoftwareVersion string |
| 353 |
|
| 354 |
// ReportSoftwareOS if set to true information about os go-xmpp being built |
| 355 |
// for will be reported. It considered not safe (secure) enough in xep-0092 |
| 356 |
// for some unknown reasons, so by default this option set to false. |
| 357 |
ReportSoftwareOS bool |
| 358 |
} |
| 359 |
|
| 360 |
// NewClient establishes a new Client connection based on a set of Options. |
| 361 |
func (o Options) NewClient() (*Client, error) { |
| 362 |
host := o.Host |
| 363 |
if strings.TrimSpace(host) == "" { |
| 364 |
a := strings.SplitN(o.User, "@", 2) |
| 365 |
if len(a) == 2 { |
| 366 |
if _, addrs, err := net.LookupSRV("xmpp-client", "tcp", a[1]); err == nil { |
| 367 |
if len(addrs) > 0 { |
| 368 |
// default to first record |
| 369 |
host = fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port) |
| 370 |
defP := addrs[0].Priority |
| 371 |
for _, adr := range addrs { |
| 372 |
if adr.Priority < defP { |
| 373 |
host = fmt.Sprintf("%s:%d", adr.Target, adr.Port) |
| 374 |
defP = adr.Priority |
| 375 |
} |
| 376 |
} |
| 377 |
} else { |
| 378 |
host = a[1] |
| 379 |
} |
| 380 |
} else { |
| 381 |
host = a[1] |
| 382 |
} |
| 383 |
} |
| 384 |
} |
| 385 |
c, err := connect(host, o.User, o.DialTimeout) |
| 386 |
if err != nil { |
| 387 |
return nil, err |
| 388 |
} |
| 389 |
|
| 390 |
if strings.LastIndex(host, ":") > 0 { |
| 391 |
host = host[:strings.LastIndex(host, ":")] |
| 392 |
} |
| 393 |
|
| 394 |
client := new(Client) |
| 395 |
client.Options = &o |
| 396 |
|
| 397 |
if o.NoTLS { |
| 398 |
client.conn = c |
| 399 |
} else { |
| 400 |
var tlsconn *tls.Conn |
| 401 |
if o.TLSConfig != nil { |
| 402 |
tlsconn = tls.Client(c, o.TLSConfig) |
| 403 |
host = o.TLSConfig.ServerName |
| 404 |
} else { |
| 405 |
newconfig := DefaultConfig.Clone() |
| 406 |
newconfig.ServerName = host |
| 407 |
tlsconn = tls.Client(c, newconfig) |
| 408 |
} |
| 409 |
if err = tlsconn.Handshake(); err != nil { |
| 410 |
return nil, err |
| 411 |
} |
| 412 |
insecureSkipVerify := DefaultConfig.InsecureSkipVerify |
| 413 |
if o.TLSConfig != nil { |
| 414 |
insecureSkipVerify = o.TLSConfig.InsecureSkipVerify |
| 415 |
} |
| 416 |
if !insecureSkipVerify { |
| 417 |
if err = tlsconn.VerifyHostname(host); err != nil { |
| 418 |
return nil, err |
| 419 |
} |
| 420 |
} |
| 421 |
client.conn = tlsconn |
| 422 |
} |
| 423 |
|
| 424 |
if err := client.init(&o); err != nil { |
| 425 |
return nil, err |
| 426 |
} |
| 427 |
|
| 428 |
if o.PeriodicServerPings { |
| 429 |
client.periodicPings = true |
| 430 |
// Set periodic pings period to 20 seconds if not specified. |
| 431 |
if o.PeriodicServerPingsPeriod == 0 { |
| 432 |
client.periodicPingPeriod = time.Duration(20000 * time.Millisecond) |
| 433 |
} else { |
| 434 |
client.periodicPingPeriod = time.Duration(o.PeriodicServerPingsPeriod) * time.Millisecond |
| 435 |
} |
| 436 |
// Set periodic pings timeout to 5 seconds if not specified. |
| 437 |
if o.PeriodicServerPingsTimeout == 0 { |
| 438 |
client.periodicPingTimeout = time.Duration(5000 * time.Millisecond) |
| 439 |
} else { |
| 440 |
client.periodicPingTimeout = time.Duration(o.PeriodicServerPingsTimeout) * time.Millisecond |
| 441 |
} |
| 442 |
client.periodicPingTicker = time.NewTicker(client.periodicPingPeriod) |
| 443 |
// Start sending periodic pings |
| 444 |
go client.sendPeriodicPings() |
| 445 |
} |
| 446 |
|
| 447 |
if client.Options.SoftwareName == "" { |
| 448 |
client.Options.SoftwareName = "go-xmpp" |
| 449 |
client.Options.SoftwareVersion = Version |
| 450 |
} else { |
| 451 |
if client.Options.SoftwareVersion == "" { |
| 452 |
client.Options.SoftwareVersion = "undefined" |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
return client, nil |
| 457 |
} |
| 458 |
|
| 459 |
// NewClient creates a new connection to a host given as "hostname" or "hostname:port". |
| 460 |
// If host is not specified, the DNS SRV should be used to find the host from the domainpart of the JID. |
| 461 |
// Default the port to 5222. |
| 462 |
func NewClient(host, user, passwd string, debug bool) (*Client, error) { |
| 463 |
opts := Options{ |
| 464 |
Host: host, |
| 465 |
User: user, |
| 466 |
Password: passwd, |
| 467 |
Debug: debug, |
| 468 |
Session: false, |
| 469 |
SoftwareName: "go-xmpp", |
| 470 |
SoftwareVersion: Version, |
| 471 |
} |
| 472 |
return opts.NewClient() |
| 473 |
} |
| 474 |
|
| 475 |
// NewClientNoTLS creates a new client without TLS |
| 476 |
func NewClientNoTLS(host, user, passwd string, debug bool) (*Client, error) { |
| 477 |
opts := Options{ |
| 478 |
Host: host, |
| 479 |
User: user, |
| 480 |
Password: passwd, |
| 481 |
NoTLS: true, |
| 482 |
Debug: debug, |
| 483 |
Session: false, |
| 484 |
SoftwareName: "go-xmpp", |
| 485 |
SoftwareVersion: Version, |
| 486 |
} |
| 487 |
return opts.NewClient() |
| 488 |
} |
| 489 |
|
| 490 |
// Close closes the XMPP connection |
| 491 |
func (c *Client) Close() error { |
| 492 |
c.shutdown = true |
| 493 |
if c.periodicPings { |
| 494 |
c.periodicPingTicker.Stop() |
| 495 |
} |
| 496 |
if c.conn != (*tls.Conn)(nil) { |
| 497 |
fmt.Fprintf(c.stanzaWriter, "</stream:stream>\n") |
| 498 |
go func() { |
| 499 |
<-time.After(10 * time.Second) |
| 500 |
c.conn.Close() |
| 501 |
}() |
| 502 |
// Wait for the server also closing the stream. |
| 503 |
for { |
| 504 |
ee, err := c.nextEnd() |
| 505 |
// If the server already closed the stream it is |
| 506 |
// likely to receive an error when trying to parse |
| 507 |
// the stream. Therefore the connection is also closed |
| 508 |
// if an error is received. |
| 509 |
switch err { |
| 510 |
case io.EOF: |
| 511 |
return c.conn.Close() |
| 512 |
case nil: |
| 513 |
if ee.Name.Local == "stream" { |
| 514 |
return c.conn.Close() |
| 515 |
} |
| 516 |
default: |
| 517 |
c.conn.Close() |
| 518 |
return err |
| 519 |
} |
| 520 |
} |
| 521 |
} |
| 522 |
return nil |
| 523 |
} |
| 524 |
|
| 525 |
func cnonce() string { |
| 526 |
randSize := big.NewInt(0) |
| 527 |
randSize.Lsh(big.NewInt(1), 64) |
| 528 |
cn, err := rand.Int(rand.Reader, randSize) |
| 529 |
if err != nil { |
| 530 |
return "" |
| 531 |
} |
| 532 |
return fmt.Sprintf("%016x", cn) |
| 533 |
} |
| 534 |
|
| 535 |
func (c *Client) init(o *Options) error { |
| 536 |
var domain string |
| 537 |
var user string |
| 538 |
a := strings.SplitN(o.User, "@", 2) |
| 539 |
// Check if User is not empty. Otherwise, we'll be attempting ANONYMOUS with Host domain. |
| 540 |
switch { |
| 541 |
case len(o.User) > 0: |
| 542 |
switch len(a) { |
| 543 |
case 1: |
| 544 |
// Allow it to specify the domain as username for ANONYMOUS authentication. |
| 545 |
// Otherwise connection fails if the connection target differs from the server |
| 546 |
// name |
| 547 |
domain = o.User |
| 548 |
user = "" |
| 549 |
o.User = "" |
| 550 |
case 2: |
| 551 |
user = a[0] |
| 552 |
domain = a[1] |
| 553 |
} |
| 554 |
default: |
| 555 |
domain = o.Host |
| 556 |
} |
| 557 |
if strings.Contains(domain, ":") { |
| 558 |
domain = strings.SplitN(domain, ":", 2)[0] |
| 559 |
} |
| 560 |
|
| 561 |
// Declare intent to be a jabber client and gather stream features. |
| 562 |
f, err := c.startStream(o, domain) |
| 563 |
if err != nil { |
| 564 |
return err |
| 565 |
} |
| 566 |
// Make the max. stanza size limit available. |
| 567 |
if f.Limits.MaxBytes != "" { |
| 568 |
c.LimitMaxBytes, err = strconv.Atoi(f.Limits.MaxBytes) |
| 569 |
if err != nil { |
| 570 |
c.LimitMaxBytes = 0 |
| 571 |
} |
| 572 |
} |
| 573 |
// Make the servers time limit after which it might consider the stream idle available. |
| 574 |
if f.Limits.IdleSeconds != "" { |
| 575 |
c.LimitIdleSeconds, err = strconv.Atoi(f.Limits.IdleSeconds) |
| 576 |
if err != nil { |
| 577 |
c.LimitIdleSeconds = 0 |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
// If the connection is not yet encrypted attempt StartTLS. |
| 582 |
if !c.IsEncrypted() { |
| 583 |
if f, err = c.startTLSIfRequired(f, o, domain); err != nil { |
| 584 |
return err |
| 585 |
} |
| 586 |
} |
| 587 |
var mechanism, channelBinding, clientFirstMessage, clientFinalMessageBare, authMessage string |
| 588 |
var bind2Data, resource, userAgentSW, userAgentDev, userAgentID, fastAuth, saslUpgrade string |
| 589 |
var saslUpgradeMech string |
| 590 |
var serverSignature, keyingMaterial, successMsg []byte |
| 591 |
var scramPLUS, ok, tlsConnOK, tls13, serverEndPoint, sasl2, bind2 bool |
| 592 |
var cbsSlice, mechSlice, upgrSlice []string |
| 593 |
var tlsConn *tls.Conn |
| 594 |
// Use SASL2 if available |
| 595 |
if f.Authentication.Mechanism != nil && c.IsEncrypted() { |
| 596 |
sasl2 = true |
| 597 |
mechSlice = f.Authentication.Mechanism |
| 598 |
// Detect whether bind2 is available |
| 599 |
if f.Authentication.Inline.Bind.Xmlns != "" { |
| 600 |
bind2 = true |
| 601 |
if o.UserAgentSW != "" { |
| 602 |
userAgentSW = fmt.Sprintf("<software>%s</software>", o.UserAgentSW) |
| 603 |
resource = o.UserAgentSW |
| 604 |
} else { |
| 605 |
userAgentSW = "<software>go-xmpp</software>" |
| 606 |
resource = "go-xmpp" |
| 607 |
} |
| 608 |
bind2Data = fmt.Sprintf("<bind xmlns='%s'><tag>%s</tag></bind>", |
| 609 |
XMPPNS_BIND_0, resource) |
| 610 |
} |
| 611 |
if o.UserAgentDev != "" { |
| 612 |
userAgentDev = fmt.Sprintf("<device>%s</device>", o.UserAgentDev) |
| 613 |
} |
| 614 |
if o.UserAgentID != "" { |
| 615 |
userAgentID = fmt.Sprintf(" id='%s'", o.UserAgentID) |
| 616 |
} |
| 617 |
} else { |
| 618 |
mechSlice = f.Mechanisms.Mechanism |
| 619 |
} |
| 620 |
if o.User == "" && o.Password == "" { |
| 621 |
foundAnonymous := false |
| 622 |
for _, m := range mechSlice { |
| 623 |
if m == "ANONYMOUS" { |
| 624 |
mechanism = m |
| 625 |
if sasl2 { |
| 626 |
fmt.Fprintf(c.stanzaWriter, |
| 627 |
"<authenticate xmlns='%s' mechanism='%s'><user-agent%s>%s%s</user-agent>%s%s</authenticate>\n", |
| 628 |
XMPPNS_SASL_2, mechanism, userAgentID, userAgentSW, userAgentDev, bind2Data, fastAuth) |
| 629 |
} else { |
| 630 |
fmt.Fprintf(c.stanzaWriter, "<auth xmlns='%s' mechanism='ANONYMOUS' />\n", XMPPNS_XMPP_SASL) |
| 631 |
} |
| 632 |
foundAnonymous = true |
| 633 |
break |
| 634 |
} |
| 635 |
} |
| 636 |
if !foundAnonymous { |
| 637 |
return fmt.Errorf("ANONYMOUS authentication is not an option and username and password were not specified") |
| 638 |
} |
| 639 |
} else { |
| 640 |
// Even digest forms of authentication are unsafe if we do not know that the host |
| 641 |
// we are talking to is the actual server, and not a man in the middle playing |
| 642 |
// proxy. |
| 643 |
if !c.IsEncrypted() && !o.InsecureAllowUnencryptedAuth { |
| 644 |
return errors.New("refusing to authenticate over unencrypted TCP connection") |
| 645 |
} |
| 646 |
|
| 647 |
tlsConn, ok = c.conn.(*tls.Conn) |
| 648 |
if ok { |
| 649 |
tlsConnOK = true |
| 650 |
} |
| 651 |
mechanism = "" |
| 652 |
if o.Mechanism != "" { |
| 653 |
if slices.Contains(mechSlice, o.Mechanism) { |
| 654 |
mechanism = o.Mechanism |
| 655 |
} |
| 656 |
} else { |
| 657 |
switch { |
| 658 |
case slices.Contains(mechSlice, SCRAM_SHA_512_PLUS) && tlsConnOK: |
| 659 |
mechanism = SCRAM_SHA_512_PLUS |
| 660 |
case slices.Contains(mechSlice, SCRAM_SHA_256_PLUS) && tlsConnOK: |
| 661 |
mechanism = SCRAM_SHA_256_PLUS |
| 662 |
case slices.Contains(mechSlice, SCRAM_SHA_1_PLUS) && tlsConnOK: |
| 663 |
mechanism = SCRAM_SHA_1_PLUS |
| 664 |
case slices.Contains(mechSlice, SCRAM_SHA_512): |
| 665 |
mechanism = SCRAM_SHA_512 |
| 666 |
case slices.Contains(mechSlice, SCRAM_SHA_256): |
| 667 |
mechanism = SCRAM_SHA_256 |
| 668 |
case slices.Contains(mechSlice, SCRAM_SHA_1): |
| 669 |
mechanism = SCRAM_SHA_1 |
| 670 |
case slices.Contains(mechSlice, "X-OAUTH2") && o.OAuthToken != "" && o.OAuthScope != "": |
| 671 |
mechanism = "X-OAUTH2" |
| 672 |
// Do not use PLAIN auth if NoPlain is set. |
| 673 |
case slices.Contains(mechSlice, "PLAIN") && !o.NoPLAIN && (tlsConnOK || o.InsecureAllowUnencryptedAuth): |
| 674 |
mechanism = "PLAIN" |
| 675 |
} |
| 676 |
} |
| 677 |
if strings.HasPrefix(mechanism, "SCRAM-SHA") { |
| 678 |
if strings.HasSuffix(mechanism, "PLUS") { |
| 679 |
scramPLUS = true |
| 680 |
} |
| 681 |
for _, cbs := range f.ChannelBindings.ChannelBinding { |
| 682 |
cbsSlice = append(cbsSlice, cbs.Type) |
| 683 |
} |
| 684 |
if scramPLUS { |
| 685 |
tlsState := tlsConn.ConnectionState() |
| 686 |
switch tlsState.Version { |
| 687 |
case tls.VersionTLS13: |
| 688 |
tls13 = true |
| 689 |
if slices.Contains(cbsSlice, "tls-server-end-point") && !slices.Contains(cbsSlice, "tls-exporter") { |
| 690 |
serverEndPoint = true |
| 691 |
} else { |
| 692 |
keyingMaterial, err = tlsState.ExportKeyingMaterial("EXPORTER-Channel-Binding", nil, 32) |
| 693 |
if err != nil { |
| 694 |
return err |
| 695 |
} |
| 696 |
} |
| 697 |
case tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12: |
| 698 |
if slices.Contains(cbsSlice, "tls-server-end-point") && !slices.Contains(cbsSlice, "tls-unique") { |
| 699 |
serverEndPoint = true |
| 700 |
} else { |
| 701 |
keyingMaterial = tlsState.TLSUnique |
| 702 |
} |
| 703 |
default: |
| 704 |
return errors.New(mechanism + ": unknown TLS version") |
| 705 |
} |
| 706 |
if serverEndPoint { |
| 707 |
var h hash.Hash |
| 708 |
// This material is not necessary for `tls-server-end-point` binding, but it is required to check that |
| 709 |
// the TLS connection was not renegotiated. This function will fail if that's the case (see |
| 710 |
// https://pkg.go.dev/crypto/tls#ConnectionState.ExportKeyingMaterial |
| 711 |
_, err = tlsState.ExportKeyingMaterial("EXPORTER-Channel-Binding", nil, 32) |
| 712 |
if err != nil { |
| 713 |
return err |
| 714 |
} |
| 715 |
switch tlsState.PeerCertificates[0].SignatureAlgorithm { |
| 716 |
case x509.SHA1WithRSA, x509.SHA256WithRSA, x509.ECDSAWithSHA1, |
| 717 |
x509.ECDSAWithSHA256, x509.SHA256WithRSAPSS: |
| 718 |
h = sha256.New() |
| 719 |
case x509.SHA384WithRSA, x509.ECDSAWithSHA384, x509.SHA384WithRSAPSS: |
| 720 |
h = sha512.New384() |
| 721 |
case x509.SHA512WithRSA, x509.ECDSAWithSHA512, x509.SHA512WithRSAPSS: |
| 722 |
h = sha512.New() |
| 723 |
} |
| 724 |
h.Write(tlsState.PeerCertificates[0].Raw) |
| 725 |
keyingMaterial = h.Sum(nil) |
| 726 |
h.Reset() |
| 727 |
} |
| 728 |
if len(keyingMaterial) == 0 { |
| 729 |
return errors.New(mechanism + ": no keying material") |
| 730 |
} |
| 731 |
switch { |
| 732 |
case tls13 && !serverEndPoint: |
| 733 |
channelBinding = base64.StdEncoding.EncodeToString(slices.Concat([]byte("p=tls-exporter,,"), keyingMaterial)) |
| 734 |
case serverEndPoint: |
| 735 |
channelBinding = base64.StdEncoding.EncodeToString(slices.Concat([]byte("p=tls-server-end-point,,"), keyingMaterial)) |
| 736 |
default: |
| 737 |
channelBinding = base64.StdEncoding.EncodeToString(slices.Concat([]byte("p=tls-unique,,"), keyingMaterial)) |
| 738 |
} |
| 739 |
} |
| 740 |
var shaNewFn func() hash.Hash |
| 741 |
switch mechanism { |
| 742 |
case SCRAM_SHA_512, SCRAM_SHA_512_PLUS: |
| 743 |
shaNewFn = sha512.New |
| 744 |
case SCRAM_SHA_256, SCRAM_SHA_256_PLUS: |
| 745 |
shaNewFn = sha256.New |
| 746 |
case SCRAM_SHA_1, SCRAM_SHA_1_PLUS: |
| 747 |
shaNewFn = sha1.New |
| 748 |
default: |
| 749 |
return errors.New("unsupported auth mechanism") |
| 750 |
} |
| 751 |
clientNonce := cnonce() |
| 752 |
if scramPLUS { |
| 753 |
switch { |
| 754 |
case tls13 && !serverEndPoint: |
| 755 |
clientFirstMessage = "p=tls-exporter,,n=" + user + ",r=" + clientNonce |
| 756 |
case serverEndPoint: |
| 757 |
clientFirstMessage = "p=tls-server-end-point,,n=" + user + ",r=" + clientNonce |
| 758 |
default: |
| 759 |
clientFirstMessage = "p=tls-unique,,n=" + user + ",r=" + clientNonce |
| 760 |
} |
| 761 |
} else { |
| 762 |
clientFirstMessage = "n,,n=" + user + ",r=" + clientNonce |
| 763 |
} |
| 764 |
if sasl2 { |
| 765 |
if !o.NoSASLUpgrade && |
| 766 |
!(o.Fast && f.Authentication.Inline.Fast.Mechanism != nil) { |
| 767 |
for _, um := range f.Authentication.Upgrade { |
| 768 |
upgrSlice = append(upgrSlice, um.Text) |
| 769 |
} |
| 770 |
switch { |
| 771 |
case slices.Contains(upgrSlice, UPGR_SCRAM_SHA_512): |
| 772 |
saslUpgradeMech = UPGR_SCRAM_SHA_512 |
| 773 |
case slices.Contains(upgrSlice, UPGR_SCRAM_SHA_256): |
| 774 |
saslUpgradeMech = UPGR_SCRAM_SHA_256 |
| 775 |
} |
| 776 |
if saslUpgradeMech != "" { |
| 777 |
saslUpgrade = fmt.Sprintf("<upgrade xmlns='%s'>%s</upgrade>", |
| 778 |
XMPPNS_SASL_UPGRADE_0, saslUpgradeMech) |
| 779 |
} |
| 780 |
} |
| 781 |
if o.Fast && f.Authentication.Inline.Fast.Mechanism != nil && o.UserAgentID != "" && c.IsEncrypted() { |
| 782 |
var mech string |
| 783 |
if o.FastToken == "" { |
| 784 |
m := f.Authentication.Inline.Fast.Mechanism |
| 785 |
switch { |
| 786 |
case slices.Contains(m, HT_SHA_256_EXPR) && tls13: |
| 787 |
mech = HT_SHA_256_EXPR |
| 788 |
case slices.Contains(m, HT_SHA_256_UNIQ) && !tls13: |
| 789 |
mech = HT_SHA_256_UNIQ |
| 790 |
case slices.Contains(m, HT_SHA_256_ENDP): |
| 791 |
mech = HT_SHA_256_ENDP |
| 792 |
case slices.Contains(m, HT_SHA_256_NONE): |
| 793 |
mech = HT_SHA_256_NONE |
| 794 |
default: |
| 795 |
return fmt.Errorf("fast: unsupported auth mechanism %s", m) |
| 796 |
} |
| 797 |
fastAuth = fmt.Sprintf("<request-token xmlns='%s' mechanism='%s'/>", XMPPNS_FAST_0, mech) |
| 798 |
} else { |
| 799 |
var fastInvalidate string |
| 800 |
if o.FastInvalidate { |
| 801 |
fastInvalidate = " invalidate='true'" |
| 802 |
} |
| 803 |
fastAuth = fmt.Sprintf("<fast xmlns='%s'%s/>", XMPPNS_FAST_0, fastInvalidate) |
| 804 |
tlsState := tlsConn.ConnectionState() |
| 805 |
mechanism = o.FastMechanism |
| 806 |
switch mechanism { |
| 807 |
case HT_SHA_256_EXPR: |
| 808 |
if !tls13 { |
| 809 |
return fmt.Errorf("fast: %s can only be used when using TLSv1.3", HT_SHA_256_EXPR) |
| 810 |
} |
| 811 |
keyingMaterial, err = tlsState.ExportKeyingMaterial("EXPORTER-Channel-Binding", nil, 32) |
| 812 |
if err != nil { |
| 813 |
return err |
| 814 |
} |
| 815 |
case HT_SHA_256_UNIQ: |
| 816 |
if tls13 { |
| 817 |
return fmt.Errorf("fast: %s can not be used when using TLSv1.3", HT_SHA_256_UNIQ) |
| 818 |
} |
| 819 |
keyingMaterial = tlsState.TLSUnique |
| 820 |
case HT_SHA_256_ENDP: |
| 821 |
var h hash.Hash |
| 822 |
switch tlsState.PeerCertificates[0].SignatureAlgorithm { |
| 823 |
case x509.SHA1WithRSA, x509.SHA256WithRSA, x509.ECDSAWithSHA1, |
| 824 |
x509.ECDSAWithSHA256, x509.SHA256WithRSAPSS: |
| 825 |
h = sha256.New() |
| 826 |
case x509.SHA384WithRSA, x509.ECDSAWithSHA384, x509.SHA384WithRSAPSS: |
| 827 |
h = sha512.New384() |
| 828 |
case x509.SHA512WithRSA, x509.ECDSAWithSHA512, x509.SHA512WithRSAPSS: |
| 829 |
h = sha512.New() |
| 830 |
} |
| 831 |
h.Write(tlsState.PeerCertificates[0].Raw) |
| 832 |
keyingMaterial = h.Sum(nil) |
| 833 |
h.Reset() |
| 834 |
case HT_SHA_256_NONE: |
| 835 |
keyingMaterial = []byte("") |
| 836 |
default: |
| 837 |
return fmt.Errorf("fast: unsupported auth mechanism %s", mechanism) |
| 838 |
} |
| 839 |
h := hmac.New(sha256.New, []byte(o.FastToken)) |
| 840 |
initiator := slices.Concat([]byte("Initiator"), keyingMaterial) |
| 841 |
_, err = h.Write(initiator) |
| 842 |
if err != nil { |
| 843 |
return err |
| 844 |
} |
| 845 |
initiatorHashedToken := h.Sum(nil) |
| 846 |
user := strings.Split(o.User, "@")[0] |
| 847 |
clientFirstMessage = user + "\x00" + string(initiatorHashedToken) |
| 848 |
} |
| 849 |
} |
| 850 |
fmt.Fprintf(c.stanzaWriter, |
| 851 |
"<authenticate xmlns='%s' mechanism='%s'>%s<initial-response>%s</initial-response><user-agent%s>%s%s</user-agent>%s%s</authenticate>\n", |
| 852 |
XMPPNS_SASL_2, mechanism, saslUpgrade, base64.StdEncoding.EncodeToString([]byte(clientFirstMessage)), userAgentID, userAgentSW, userAgentDev, bind2Data, fastAuth) |
| 853 |
} else { |
| 854 |
fmt.Fprintf(c.stanzaWriter, "<auth xmlns='%s' mechanism='%s'>%s</auth>\n", |
| 855 |
XMPPNS_XMPP_SASL, mechanism, base64.StdEncoding.EncodeToString([]byte(clientFirstMessage))) |
| 856 |
} |
| 857 |
var sfm string |
| 858 |
_, val, err := c.next() |
| 859 |
if err != nil { |
| 860 |
return err |
| 861 |
} |
| 862 |
switch v := val.(type) { |
| 863 |
case *sasl2Failure: |
| 864 |
errorMessage := v.Text |
| 865 |
if errorMessage == "" { |
| 866 |
// v.Any is type of sub-element in failure, |
| 867 |
// which gives a description of what failed if there was no text element |
| 868 |
errorMessage = v.Any.Local |
| 869 |
} |
| 870 |
return errors.New("auth failure: " + errorMessage) |
| 871 |
case *saslFailure: |
| 872 |
errorMessage := v.Text |
| 873 |
if errorMessage == "" { |
| 874 |
// v.Any is type of sub-element in failure, |
| 875 |
// which gives a description of what failed if there was no text element |
| 876 |
errorMessage = v.Any.Local |
| 877 |
} |
| 878 |
return errors.New("auth failure: " + errorMessage) |
| 879 |
case *sasl2Success: |
| 880 |
if strings.HasPrefix(mechanism, "SCRAM-SHA") { |
| 881 |
successMsg, err := base64.StdEncoding.DecodeString(v.AdditionalData) |
| 882 |
if err != nil { |
| 883 |
return err |
| 884 |
} |
| 885 |
if !strings.HasPrefix(string(successMsg), "v=") { |
| 886 |
return errors.New("server sent unexpected content in SCRAM success message") |
| 887 |
} |
| 888 |
c.Mechanism = mechanism |
| 889 |
} |
| 890 |
if strings.HasPrefix(mechanism, "HT-SHA") { |
| 891 |
// TODO: Check whether server implementations already support |
| 892 |
// https://www.ietf.org/archive/id/draft-schmaus-kitten-sasl-ht-09.html#section-3.3 |
| 893 |
h := hmac.New(sha256.New, []byte(o.FastToken)) |
| 894 |
responder := slices.Concat([]byte("Responder"), keyingMaterial) |
| 895 |
_, err = h.Write(responder) |
| 896 |
if err != nil { |
| 897 |
return err |
| 898 |
} |
| 899 |
responderMsgRcv, err := base64.StdEncoding.DecodeString(v.AdditionalData) |
| 900 |
if err != nil { |
| 901 |
return err |
| 902 |
} |
| 903 |
responderMsgCalc := h.Sum(nil) |
| 904 |
if string(responderMsgCalc) != string(responderMsgRcv) { |
| 905 |
return fmt.Errorf("server sent unexpected content in FAST success message") |
| 906 |
} |
| 907 |
c.Mechanism = mechanism |
| 908 |
} |
| 909 |
if bind2 { |
| 910 |
c.jid = v.AuthorizationIdentifier |
| 911 |
c.domain = domain |
| 912 |
} |
| 913 |
if v.Token.Token != "" && v.Token.Token != o.FastToken { |
| 914 |
m := f.Authentication.Inline.Fast.Mechanism |
| 915 |
switch { |
| 916 |
case slices.Contains(m, HT_SHA_256_EXPR) && tls13: |
| 917 |
c.Fast.Mechanism = HT_SHA_256_EXPR |
| 918 |
case slices.Contains(m, HT_SHA_256_UNIQ) && !tls13: |
| 919 |
c.Fast.Mechanism = HT_SHA_256_UNIQ |
| 920 |
case slices.Contains(m, HT_SHA_256_ENDP): |
| 921 |
c.Fast.Mechanism = HT_SHA_256_ENDP |
| 922 |
case slices.Contains(m, HT_SHA_256_NONE): |
| 923 |
c.Fast.Mechanism = HT_SHA_256_NONE |
| 924 |
} |
| 925 |
c.Fast.Token = v.Token.Token |
| 926 |
c.Fast.Expiry, _ = time.Parse(time.RFC3339, v.Token.Expiry) |
| 927 |
} |
| 928 |
// Next message should be update of stream features. |
| 929 |
_, val, err := c.next() |
| 930 |
if err != nil { |
| 931 |
return err |
| 932 |
} |
| 933 |
switch v := val.(type) { |
| 934 |
case *streamFeatures: |
| 935 |
// Update the max. stanza size and idle seconds limit if provided again as some servers might apply greater limit after auth. |
| 936 |
if v.Limits.MaxBytes != "" { |
| 937 |
lim, err := strconv.Atoi(v.Limits.MaxBytes) |
| 938 |
// Only overwrite if it can be parsed successfully, otherwise keep the previous limit. |
| 939 |
if err == nil { |
| 940 |
c.LimitMaxBytes = lim |
| 941 |
} |
| 942 |
} |
| 943 |
if v.Limits.IdleSeconds != "" { |
| 944 |
lim, err := strconv.Atoi(v.Limits.IdleSeconds) |
| 945 |
// Only overwrite if it can be parsed successfully, otherwise keep the previous limit. |
| 946 |
if err == nil { |
| 947 |
c.LimitIdleSeconds = lim |
| 948 |
} |
| 949 |
} |
| 950 |
} |
| 951 |
if o.Session { |
| 952 |
// if server support session, open it |
| 953 |
cookie := getCookie() // generate new id value for session |
| 954 |
fmt.Fprintf(c.stanzaWriter, "<iq to='%s' type='set' id='%x'><session xmlns='%s'/></iq>\n", xmlEscape(domain), cookie, XMPPNS_XMPP_SESSION) |
| 955 |
} |
| 956 |
|
| 957 |
// We're connected and can now receive and send messages. |
| 958 |
fmt.Fprintf(c.stanzaWriter, "<presence xml:lang='en'><show>%s</show><status>%s</status></presence>\n", o.Status, o.StatusMessage) |
| 959 |
return nil |
| 960 |
case *sasl2Challenge: |
| 961 |
sfm = v.Text |
| 962 |
case *saslChallenge: |
| 963 |
sfm = v.Text |
| 964 |
} |
| 965 |
b, err := base64.StdEncoding.DecodeString(sfm) |
| 966 |
if err != nil { |
| 967 |
return err |
| 968 |
} |
| 969 |
var serverNonce string |
| 970 |
var dgProtect, dgProtectSep, dgProtectCBSep []byte |
| 971 |
var salt []byte |
| 972 |
var iterations int |
| 973 |
var dgMechs []string |
| 974 |
for _, serverReply := range strings.Split(string(b), ",") { |
| 975 |
switch { |
| 976 |
case strings.HasPrefix(serverReply, "r="): |
| 977 |
serverNonce = strings.SplitN(serverReply, "=", 2)[1] |
| 978 |
if !strings.HasPrefix(serverNonce, clientNonce) { |
| 979 |
return errors.New("SCRAM: server nonce didn't start with client nonce") |
| 980 |
} |
| 981 |
case strings.HasPrefix(serverReply, "s="): |
| 982 |
salt, err = base64.StdEncoding.DecodeString(strings.SplitN(serverReply, "=", 2)[1]) |
| 983 |
if err != nil { |
| 984 |
return err |
| 985 |
} |
| 986 |
if string(salt) == "" { |
| 987 |
return errors.New("SCRAM: server sent empty salt") |
| 988 |
} |
| 989 |
case strings.HasPrefix(serverReply, "i="): |
| 990 |
iterations, err = strconv.Atoi(strings.SplitN(serverReply, |
| 991 |
"=", 2)[1]) |
| 992 |
if err != nil { |
| 993 |
return err |
| 994 |
} |
| 995 |
case (strings.HasPrefix(serverReply, "d=") || strings.HasPrefix(serverReply, "h=")) && o.SSDP: |
| 996 |
dgProtectSep = []byte{0x1e} |
| 997 |
dgProtectCBSep = []byte{0x1f} |
| 998 |
serverDgProtectHash := strings.SplitN(serverReply, "=", 2)[1] |
| 999 |
if sasl2 { |
| 1000 |
dgMechs = f.Authentication.Mechanism |
| 1001 |
} else { |
| 1002 |
dgMechs = f.Mechanisms.Mechanism |
| 1003 |
} |
| 1004 |
slices.Sort(dgMechs) |
| 1005 |
for _, mech := range dgMechs { |
| 1006 |
if len(dgProtect) == 0 { |
| 1007 |
dgProtect = []byte(mech) |
| 1008 |
} else { |
| 1009 |
dgProtect = append(dgProtect, dgProtectSep...) |
| 1010 |
dgProtect = append(dgProtect, []byte(mech)...) |
| 1011 |
} |
| 1012 |
} |
| 1013 |
slices.Sort(cbsSlice) |
| 1014 |
for i, cb := range cbsSlice { |
| 1015 |
if i == 0 { |
| 1016 |
dgProtect = append(dgProtect, dgProtectCBSep...) |
| 1017 |
dgProtect = append(dgProtect, []byte(cb)...) |
| 1018 |
} else { |
| 1019 |
dgProtect = append(dgProtect, dgProtectSep...) |
| 1020 |
dgProtect = append(dgProtect, []byte(cb)...) |
| 1021 |
} |
| 1022 |
} |
| 1023 |
dgh := shaNewFn() |
| 1024 |
dgh.Write(dgProtect) |
| 1025 |
dHash := dgh.Sum(nil) |
| 1026 |
dHashb64 := base64.StdEncoding.EncodeToString(dHash) |
| 1027 |
if dHashb64 != serverDgProtectHash { |
| 1028 |
return fmt.Errorf("SCRAM: downgrade protection hash mismatch, expected: %s (hash of %s), received: %s", |
| 1029 |
dHashb64, dgProtect, serverDgProtectHash) |
| 1030 |
} |
| 1031 |
dgh.Reset() |
| 1032 |
case strings.HasPrefix(serverReply, "m="): |
| 1033 |
return errors.New("scram: server sent reserved 'm' attribute") |
| 1034 |
} |
| 1035 |
} |
| 1036 |
if scramPLUS { |
| 1037 |
clientFinalMessageBare = "c=" + channelBinding + ",r=" + serverNonce |
| 1038 |
} else { |
| 1039 |
clientFinalMessageBare = "c=biws,r=" + serverNonce |
| 1040 |
} |
| 1041 |
saltedPassword, err := pbkdf2.Key(shaNewFn, o.Password, salt, |
| 1042 |
iterations, shaNewFn().Size()) |
| 1043 |
if err != nil { |
| 1044 |
return err |
| 1045 |
} |
| 1046 |
h := hmac.New(shaNewFn, saltedPassword) |
| 1047 |
_, err = h.Write([]byte("Client Key")) |
| 1048 |
if err != nil { |
| 1049 |
return err |
| 1050 |
} |
| 1051 |
clientKey := h.Sum(nil) |
| 1052 |
h.Reset() |
| 1053 |
var storedKey []byte |
| 1054 |
switch mechanism { |
| 1055 |
case SCRAM_SHA_512, SCRAM_SHA_512_PLUS: |
| 1056 |
storedKey512 := sha512.Sum512(clientKey) |
| 1057 |
storedKey = storedKey512[:] |
| 1058 |
case SCRAM_SHA_256, SCRAM_SHA_256_PLUS: |
| 1059 |
storedKey256 := sha256.Sum256(clientKey) |
| 1060 |
storedKey = storedKey256[:] |
| 1061 |
case SCRAM_SHA_1, SCRAM_SHA_1_PLUS: |
| 1062 |
storedKey1 := sha1.Sum(clientKey) //nolint: gosec,G401 // Servers use this because of older clients. |
| 1063 |
storedKey = storedKey1[:] |
| 1064 |
} |
| 1065 |
_, err = h.Write([]byte("Server Key")) |
| 1066 |
if err != nil { |
| 1067 |
return err |
| 1068 |
} |
| 1069 |
serverFirstMessage, err := base64.StdEncoding.DecodeString(sfm) |
| 1070 |
if err != nil { |
| 1071 |
return err |
| 1072 |
} |
| 1073 |
split := strings.SplitAfter(clientFirstMessage, ",,") |
| 1074 |
if len(split) < 2 { |
| 1075 |
return errors.New("SCRAM: clientFirstMessage didn't contain ',,'") |
| 1076 |
} |
| 1077 |
authMessage = split[1] + "," + string(serverFirstMessage) + "," + clientFinalMessageBare |
| 1078 |
h = hmac.New(shaNewFn, storedKey) |
| 1079 |
_, err = h.Write([]byte(authMessage)) |
| 1080 |
if err != nil { |
| 1081 |
return err |
| 1082 |
} |
| 1083 |
clientSignature := h.Sum(nil) |
| 1084 |
h.Reset() |
| 1085 |
if len(clientKey) != len(clientSignature) { |
| 1086 |
return errors.New("SCRAM: client key and signature length mismatch") |
| 1087 |
} |
| 1088 |
clientProof := make([]byte, len(clientKey)) |
| 1089 |
for i := range clientKey { |
| 1090 |
clientProof[i] = clientKey[i] ^ clientSignature[i] |
| 1091 |
} |
| 1092 |
h = hmac.New(shaNewFn, saltedPassword) |
| 1093 |
_, err = h.Write([]byte("Server Key")) |
| 1094 |
if err != nil { |
| 1095 |
return err |
| 1096 |
} |
| 1097 |
serverKey := h.Sum(nil) |
| 1098 |
h.Reset() |
| 1099 |
h = hmac.New(shaNewFn, serverKey) |
| 1100 |
_, err = h.Write([]byte(authMessage)) |
| 1101 |
if err != nil { |
| 1102 |
return err |
| 1103 |
} |
| 1104 |
serverSignature = h.Sum(nil) |
| 1105 |
if string(serverSignature) == "" { |
| 1106 |
return errors.New("SCRAM: calculated an empty server signature") |
| 1107 |
} |
| 1108 |
clientFinalMessage := base64.StdEncoding.EncodeToString([]byte(clientFinalMessageBare + |
| 1109 |
",p=" + base64.StdEncoding.EncodeToString(clientProof))) |
| 1110 |
if sasl2 { |
| 1111 |
fmt.Fprintf(c.stanzaWriter, "<response xmlns='%s'>%s</response>\n", XMPPNS_SASL_2, |
| 1112 |
clientFinalMessage) |
| 1113 |
} else { |
| 1114 |
fmt.Fprintf(c.stanzaWriter, "<response xmlns='%s'>%s</response>\n", XMPPNS_XMPP_SASL, |
| 1115 |
clientFinalMessage) |
| 1116 |
} |
| 1117 |
} |
| 1118 |
if mechanism == "X-OAUTH2" { |
| 1119 |
// Oauth authentication: send base64-encoded \x00 user \x00 token. |
| 1120 |
raw := "\x00" + user + "\x00" + o.OAuthToken |
| 1121 |
enc := make([]byte, base64.StdEncoding.EncodedLen(len(raw))) |
| 1122 |
base64.StdEncoding.Encode(enc, []byte(raw)) |
| 1123 |
if sasl2 { |
| 1124 |
fmt.Fprintf(c.stanzaWriter, "<authenticate xmlns='%s' mechanism='X-OAUTH2' auth:service='oauth2' "+ |
| 1125 |
"xmlns:auth='%s'>%s</authenticate>\n", XMPPNS_SASL_2, o.OAuthXmlNs, enc) |
| 1126 |
} else { |
| 1127 |
fmt.Fprintf(c.stanzaWriter, "<auth xmlns='%s' mechanism='X-OAUTH2' auth:service='oauth2' "+ |
| 1128 |
"xmlns:auth='%s'>%s</auth>\n", XMPPNS_XMPP_SASL, o.OAuthXmlNs, enc) |
| 1129 |
} |
| 1130 |
} |
| 1131 |
if mechanism == "PLAIN" { |
| 1132 |
// Plain authentication: send base64-encoded \x00 user \x00 password. |
| 1133 |
raw := "\x00" + user + "\x00" + o.Password |
| 1134 |
enc := make([]byte, base64.StdEncoding.EncodedLen(len(raw))) |
| 1135 |
base64.StdEncoding.Encode(enc, []byte(raw)) |
| 1136 |
if sasl2 { |
| 1137 |
fmt.Fprintf(c.conn, "<authenticate xmlns='%s' mechanism='PLAIN'><initial-response>%s</initial-response>%s</authenticate>\n", XMPPNS_SASL_2, enc, bind2Data) |
| 1138 |
} else { |
| 1139 |
fmt.Fprintf(c.conn, "<auth xmlns='%s' mechanism='PLAIN'>%s</auth>\n", XMPPNS_XMPP_SASL, enc) |
| 1140 |
} |
| 1141 |
} |
| 1142 |
} |
| 1143 |
if mechanism == "" { |
| 1144 |
return fmt.Errorf("no viable authentication method available: %v", f.Mechanisms.Mechanism) |
| 1145 |
} |
| 1146 |
var connected bool |
| 1147 |
for !connected { |
| 1148 |
// Next message should be either success or failure. |
| 1149 |
name, val, err := c.next() |
| 1150 |
if err != nil { |
| 1151 |
return err |
| 1152 |
} |
| 1153 |
switch v := val.(type) { |
| 1154 |
case *sasl2Continue: |
| 1155 |
successMsg, err = base64.StdEncoding.DecodeString(v.AdditionalData) |
| 1156 |
if err != nil { |
| 1157 |
return err |
| 1158 |
} |
| 1159 |
fmt.Fprintf(c.stanzaWriter, "<next xmlns='%s' task='%s'/>\n", |
| 1160 |
XMPPNS_SASL_2, saslUpgradeMech) |
| 1161 |
name, val, err = c.next() |
| 1162 |
if err != nil { |
| 1163 |
return err |
| 1164 |
} |
| 1165 |
switch v := val.(type) { |
| 1166 |
case *sasl2TaskData: |
| 1167 |
var shaNewFn func() hash.Hash |
| 1168 |
switch saslUpgradeMech { |
| 1169 |
case UPGR_SCRAM_SHA_512: |
| 1170 |
shaNewFn = sha512.New |
| 1171 |
case UPGR_SCRAM_SHA_256: |
| 1172 |
shaNewFn = sha256.New |
| 1173 |
} |
| 1174 |
salt, err := base64.StdEncoding.DecodeString(v.Salt.Text) |
| 1175 |
if err != nil { |
| 1176 |
return err |
| 1177 |
} |
| 1178 |
saltedPassword, err := pbkdf2.Key(shaNewFn, o.Password, salt, |
| 1179 |
v.Salt.Iterations, shaNewFn().Size()) |
| 1180 |
if err != nil { |
| 1181 |
return err |
| 1182 |
} |
| 1183 |
saltedPasswordB64 := base64.StdEncoding.EncodeToString(saltedPassword) |
| 1184 |
fmt.Fprintf(c.stanzaWriter, "<task-data xmlns='%s'><hash xmlns='%s'>%s</hash></task-data>\n", XMPPNS_SASL_2, XMPPNS_SCRAM_UPGRADE_0, saltedPasswordB64) |
| 1185 |
continue |
| 1186 |
default: |
| 1187 |
return fmt.Errorf("sasl2 upgrade failure: expected *sasl2TaskData, got %s", name.Local) |
| 1188 |
} |
| 1189 |
|
| 1190 |
case *sasl2Success: |
| 1191 |
if strings.HasPrefix(mechanism, "SCRAM-SHA") { |
| 1192 |
if len(successMsg) == 0 { |
| 1193 |
successMsg, err = base64.StdEncoding.DecodeString(v.AdditionalData) |
| 1194 |
if err != nil { |
| 1195 |
return err |
| 1196 |
} |
| 1197 |
} |
| 1198 |
if !strings.HasPrefix(string(successMsg), "v=") { |
| 1199 |
return errors.New("server sent unexpected content in SCRAM success message") |
| 1200 |
} |
| 1201 |
serverSignatureReply := strings.SplitN(string(successMsg), "v=", 2)[1] |
| 1202 |
serverSignatureRemote, err := base64.StdEncoding.DecodeString(serverSignatureReply) |
| 1203 |
if err != nil { |
| 1204 |
return err |
| 1205 |
} |
| 1206 |
if string(serverSignature) != string(serverSignatureRemote) { |
| 1207 |
return errors.New("SCRAM: server signature mismatch") |
| 1208 |
} |
| 1209 |
c.Mechanism = mechanism |
| 1210 |
} |
| 1211 |
if bind2 { |
| 1212 |
c.jid = v.AuthorizationIdentifier |
| 1213 |
c.domain = domain |
| 1214 |
} |
| 1215 |
if v.Token.Token != "" { |
| 1216 |
m := f.Authentication.Inline.Fast.Mechanism |
| 1217 |
switch { |
| 1218 |
case slices.Contains(m, HT_SHA_256_EXPR) && tls13: |
| 1219 |
c.Fast.Mechanism = HT_SHA_256_EXPR |
| 1220 |
case slices.Contains(m, HT_SHA_256_UNIQ) && !tls13: |
| 1221 |
c.Fast.Mechanism = HT_SHA_256_UNIQ |
| 1222 |
case slices.Contains(m, HT_SHA_256_ENDP): |
| 1223 |
c.Fast.Mechanism = HT_SHA_256_ENDP |
| 1224 |
case slices.Contains(m, HT_SHA_256_NONE): |
| 1225 |
c.Fast.Mechanism = HT_SHA_256_NONE |
| 1226 |
} |
| 1227 |
c.Fast.Token = v.Token.Token |
| 1228 |
c.Fast.Expiry, _ = time.Parse(time.RFC3339, v.Token.Expiry) |
| 1229 |
} |
| 1230 |
// Next message should be update of stream features. |
| 1231 |
_, val, err := c.next() |
| 1232 |
if err != nil { |
| 1233 |
return err |
| 1234 |
} |
| 1235 |
switch v := val.(type) { |
| 1236 |
case *streamFeatures: |
| 1237 |
// Update the max. stanza size and idle limits if provided again as some servers might apply greater limit after auth. |
| 1238 |
if v.Limits.MaxBytes != "" { |
| 1239 |
lim, err := strconv.Atoi(v.Limits.MaxBytes) |
| 1240 |
// Only overwrite if it can be parsed successfully, otherwise keep the previous limit. |
| 1241 |
if err == nil { |
| 1242 |
c.LimitMaxBytes = lim |
| 1243 |
} |
| 1244 |
} |
| 1245 |
if v.Limits.IdleSeconds != "" { |
| 1246 |
lim, err := strconv.Atoi(v.Limits.IdleSeconds) |
| 1247 |
// Only overwrite if it can be parsed successfully, otherwise keep the previous limit. |
| 1248 |
if err == nil { |
| 1249 |
c.LimitIdleSeconds = lim |
| 1250 |
} |
| 1251 |
} |
| 1252 |
} |
| 1253 |
case *saslSuccess: |
| 1254 |
if strings.HasPrefix(mechanism, "SCRAM-SHA") { |
| 1255 |
successMsg, err := base64.StdEncoding.DecodeString(v.Text) |
| 1256 |
if err != nil { |
| 1257 |
return err |
| 1258 |
} |
| 1259 |
if !strings.HasPrefix(string(successMsg), "v=") { |
| 1260 |
return errors.New("server sent unexpected content in SCRAM success message") |
| 1261 |
} |
| 1262 |
serverSignatureReply := strings.SplitN(string(successMsg), "v=", 2)[1] |
| 1263 |
serverSignatureRemote, err := base64.StdEncoding.DecodeString(serverSignatureReply) |
| 1264 |
if err != nil { |
| 1265 |
return err |
| 1266 |
} |
| 1267 |
if string(serverSignature) != string(serverSignatureRemote) { |
| 1268 |
return errors.New("SCRAM: server signature mismatch") |
| 1269 |
} |
| 1270 |
c.Mechanism = mechanism |
| 1271 |
} |
| 1272 |
case *sasl2Failure: |
| 1273 |
errorMessage := v.Text |
| 1274 |
if errorMessage == "" { |
| 1275 |
// v.Any is type of sub-element in failure, |
| 1276 |
// which gives a description of what failed if there was no text element |
| 1277 |
errorMessage = v.Any.Local |
| 1278 |
} |
| 1279 |
return errors.New("auth failure: " + errorMessage) |
| 1280 |
case *saslFailure: |
| 1281 |
errorMessage := v.Text |
| 1282 |
if errorMessage == "" { |
| 1283 |
// v.Any is type of sub-element in failure, |
| 1284 |
// which gives a description of what failed if there was no text element |
| 1285 |
errorMessage = v.Any.Local |
| 1286 |
} |
| 1287 |
return errors.New("auth failure: " + errorMessage) |
| 1288 |
default: |
| 1289 |
return errors.New("expected <success> or <failure>, got <" + name.Local + "> in " + name.Space) |
| 1290 |
} |
| 1291 |
|
| 1292 |
if !sasl2 { |
| 1293 |
// Now that we're authenticated, we're supposed to start the stream over again. |
| 1294 |
// Declare intent to be a jabber client. |
| 1295 |
if f, err = c.startStream(o, domain); err != nil { |
| 1296 |
return err |
| 1297 |
} |
| 1298 |
// Update the max. stanza size and idle seconds limits if provided again as some servers might apply greater limit after auth. |
| 1299 |
if f.Limits.MaxBytes != "" { |
| 1300 |
lim, err := strconv.Atoi(f.Limits.MaxBytes) |
| 1301 |
// Only overwrite if it can be parsed successfully, otherwise keep the previous limit. |
| 1302 |
if err == nil { |
| 1303 |
c.LimitMaxBytes = lim |
| 1304 |
} |
| 1305 |
} |
| 1306 |
if f.Limits.IdleSeconds != "" { |
| 1307 |
lim, err := strconv.Atoi(f.Limits.IdleSeconds) |
| 1308 |
// Only overwrite if it can be parsed successfully, otherwise keep the previous limit. |
| 1309 |
if err == nil { |
| 1310 |
c.LimitIdleSeconds = lim |
| 1311 |
} |
| 1312 |
} |
| 1313 |
} |
| 1314 |
// Make the servers time limit after which it might consider the stream idle available. |
| 1315 |
if f.Limits.IdleSeconds != "" { |
| 1316 |
c.LimitIdleSeconds, err = strconv.Atoi(f.Limits.IdleSeconds) |
| 1317 |
if err != nil { |
| 1318 |
c.LimitIdleSeconds = 0 |
| 1319 |
} |
| 1320 |
} |
| 1321 |
|
| 1322 |
if !bind2 { |
| 1323 |
// Generate a unique cookie |
| 1324 |
cookie := getCookie() |
| 1325 |
|
| 1326 |
// Send IQ message asking to bind to the local user name. |
| 1327 |
if o.Resource == "" { |
| 1328 |
fmt.Fprintf(c.stanzaWriter, "<iq type='set' id='%x'><bind xmlns='%s'></bind></iq>\n", cookie, XMPPNS_XMPP_BIND) |
| 1329 |
} else { |
| 1330 |
fmt.Fprintf(c.stanzaWriter, "<iq type='set' id='%x'><bind xmlns='%s'><resource>%s</resource></bind></iq>\n", cookie, XMPPNS_XMPP_BIND, o.Resource) |
| 1331 |
} |
| 1332 |
_, val, err = c.next() |
| 1333 |
if err != nil { |
| 1334 |
return err |
| 1335 |
} |
| 1336 |
switch v := val.(type) { |
| 1337 |
case *streamError: |
| 1338 |
errorMessage := v.Text.Text |
| 1339 |
if errorMessage == "" { |
| 1340 |
// v.Any is type of sub-element in failure, |
| 1341 |
// which gives a description of what failed if there was no text element |
| 1342 |
errorMessage = v.Any.Space |
| 1343 |
} |
| 1344 |
return errors.New("stream error: " + errorMessage) |
| 1345 |
case *clientIQ: |
| 1346 |
if v.Bind.XMLName.Space == XMPPNS_XMPP_BIND { |
| 1347 |
c.jid = v.Bind.Jid // our local id |
| 1348 |
c.domain = domain |
| 1349 |
} else { |
| 1350 |
return errors.New("bind: unexpected reply to xmpp-bind IQ") |
| 1351 |
} |
| 1352 |
} |
| 1353 |
} |
| 1354 |
if o.Session { |
| 1355 |
// if server support session, open it |
| 1356 |
cookie := getCookie() // generate new id value for session |
| 1357 |
fmt.Fprintf(c.stanzaWriter, "<iq to='%s' type='set' id='%x'><session xmlns='%s'/></iq>\n", xmlEscape(domain), cookie, XMPPNS_XMPP_SESSION) |
| 1358 |
} |
| 1359 |
|
| 1360 |
// We're connected and can now receive and send messages. |
| 1361 |
fmt.Fprintf(c.stanzaWriter, "<presence xml:lang='en'><show>%s</show><status>%s</status></presence>\n", o.Status, o.StatusMessage) |
| 1362 |
connected = true |
| 1363 |
} |
| 1364 |
return nil |
| 1365 |
} |
| 1366 |
|
| 1367 |
// startTlsIfRequired examines the server's stream features and, if STARTTLS is required or supported, performs the TLS handshake. |
| 1368 |
// f will be updated if the handshake completes, as the new stream's features are typically different from the original. |
| 1369 |
func (c *Client) startTLSIfRequired(f *streamFeatures, o *Options, domain string) (*streamFeatures, error) { |
| 1370 |
// whether we start tls is a matter of opinion: the server's and the user's. |
| 1371 |
switch { |
| 1372 |
case f.StartTLS == nil && o.InsecureAllowUnencryptedAuth && !o.StartTLS: |
| 1373 |
// the server does not support StartTLS and the user doesn't require it. |
| 1374 |
return f, nil |
| 1375 |
case f.StartTLS == nil && o.StartTLS: |
| 1376 |
// the server does not support StartTLS but the user requires it. |
| 1377 |
return f, fmt.Errorf("StartTLS is required but the server doesn't support it") |
| 1378 |
case f.StartTLS == nil: |
| 1379 |
// the server does not support StartTLS but InsecureAllowUnencryptedAuth is not set. |
| 1380 |
return f, fmt.Errorf("StartTLS is not supported by the server but InsecureAllowUnencryptedAuth is not set") |
| 1381 |
case f.StartTLS != nil: |
| 1382 |
// the server does not require StartTLS and user does not require it. |
| 1383 |
if f.StartTLS.Required == nil && o.InsecureAllowUnencryptedAuth && !o.StartTLS { |
| 1384 |
return f, nil |
| 1385 |
} |
| 1386 |
} |
| 1387 |
var err error |
| 1388 |
|
| 1389 |
fmt.Fprintf(c.stanzaWriter, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n") |
| 1390 |
var k tlsProceed |
| 1391 |
if err = c.p.DecodeElement(&k, nil); err != nil { |
| 1392 |
return f, errors.New("unmarshal <proceed>: " + err.Error()) |
| 1393 |
} |
| 1394 |
|
| 1395 |
tc := o.TLSConfig |
| 1396 |
if tc == nil { |
| 1397 |
tc = DefaultConfig.Clone() |
| 1398 |
// TODO(scott): we should consider using the server's address or reverse lookup |
| 1399 |
tc.ServerName = domain |
| 1400 |
} |
| 1401 |
t := tls.Client(c.conn, tc) |
| 1402 |
|
| 1403 |
if err = t.Handshake(); err != nil { |
| 1404 |
return f, errors.New("starttls handshake: " + err.Error()) |
| 1405 |
} |
| 1406 |
c.conn = t |
| 1407 |
|
| 1408 |
// restart our declaration of XMPP stream intentions. |
| 1409 |
tf, err := c.startStream(o, domain) |
| 1410 |
if err != nil { |
| 1411 |
return f, err |
| 1412 |
} |
| 1413 |
return tf, nil |
| 1414 |
} |
| 1415 |
|
| 1416 |
// startStream will start a new XML decoder for the connection, signal the start of a stream to the server and verify that the server has |
| 1417 |
// also started the stream; if o.Debug is true, startStream will tee decoded XML data to stderr. The features advertised by the server |
| 1418 |
// will be returned. |
| 1419 |
func (c *Client) startStream(o *Options, domain string) (*streamFeatures, error) { |
| 1420 |
if o.Debug { |
| 1421 |
if o.DebugWriter == nil { |
| 1422 |
o.DebugWriter = os.Stderr |
| 1423 |
} |
| 1424 |
debugRecv := &debugWriter{w: o.DebugWriter, prefix: "RECV "} |
| 1425 |
c.p = xml.NewDecoder(tee{c.conn, debugRecv}) |
| 1426 |
debugSend := &debugWriter{w: o.DebugWriter, prefix: "SEND "} |
| 1427 |
c.stanzaWriter = io.MultiWriter(c.conn, debugSend) |
| 1428 |
} else { |
| 1429 |
c.p = xml.NewDecoder(c.conn) |
| 1430 |
c.stanzaWriter = c.conn |
| 1431 |
} |
| 1432 |
|
| 1433 |
var fromString string |
| 1434 |
if len(o.User) > 0 { |
| 1435 |
fromString = fmt.Sprintf("from='%s' ", xmlEscape(o.User)) |
| 1436 |
} |
| 1437 |
if c.IsEncrypted() { |
| 1438 |
_, err := fmt.Fprintf(c.stanzaWriter, "<?xml version='1.0'?>"+ |
| 1439 |
"<stream:stream %sto='%s' xmlns='%s'"+ |
| 1440 |
" xmlns:stream='%s' version='1.0'>\n", |
| 1441 |
fromString, xmlEscape(domain), XMPPNS_CLIENT, XMPPNS_STREAM) |
| 1442 |
if err != nil { |
| 1443 |
return nil, err |
| 1444 |
} |
| 1445 |
} else { |
| 1446 |
_, err := fmt.Fprintf(c.stanzaWriter, "<?xml version='1.0'?>"+ |
| 1447 |
"<stream:stream to='%s' xmlns='%s' xmlns:stream='%s' version='1.0'>\n", |
| 1448 |
xmlEscape(domain), XMPPNS_CLIENT, XMPPNS_STREAM) |
| 1449 |
if err != nil { |
| 1450 |
return nil, err |
| 1451 |
} |
| 1452 |
} |
| 1453 |
|
| 1454 |
// We expect the server to start a <stream>. |
| 1455 |
se, err := c.nextStart() |
| 1456 |
if err != nil { |
| 1457 |
return nil, err |
| 1458 |
} |
| 1459 |
if se.Name.Space != XMPPNS_STREAM || se.Name.Local != "stream" { |
| 1460 |
return nil, fmt.Errorf("expected <stream> but got <%v> in %v", se.Name.Local, se.Name.Space) |
| 1461 |
} |
| 1462 |
|
| 1463 |
// Now we're in the stream and can use Unmarshal. |
| 1464 |
// Next message should be <features> to tell us authentication options. |
| 1465 |
// See section 4.6 in RFC 3920. |
| 1466 |
f := new(streamFeatures) |
| 1467 |
name, val, err := c.next() |
| 1468 |
if err != nil { |
| 1469 |
return f, err |
| 1470 |
} |
| 1471 |
switch v := val.(type) { |
| 1472 |
case *streamFeatures: |
| 1473 |
return v, nil |
| 1474 |
case *streamError: |
| 1475 |
if c.IsEncrypted() && v.SeeOtherHost.Text != "" { |
| 1476 |
c.conn.Close() |
| 1477 |
c.conn, err = connect(v.SeeOtherHost.Text, o.User, o.DialTimeout) |
| 1478 |
if err != nil { |
| 1479 |
return f, err |
| 1480 |
} |
| 1481 |
f, err = c.startStream(o, domain) |
| 1482 |
if err != nil { |
| 1483 |
return f, errors.New("unmarshal <features>: " + err.Error()) |
| 1484 |
} |
| 1485 |
return f, nil |
| 1486 |
} |
| 1487 |
errorMessage := v.Text.Text |
| 1488 |
if errorMessage == "" { |
| 1489 |
// v.Any is type of sub-element in failure, |
| 1490 |
// which gives a description of what failed if there was no text element |
| 1491 |
errorMessage = v.Any.Space |
| 1492 |
} |
| 1493 |
return f, errors.New("stream error: " + errorMessage) |
| 1494 |
default: |
| 1495 |
return f, errors.New("expected <success> or <failure>, got <" + name.Local + "> in " + name.Space) |
| 1496 |
} |
| 1497 |
} |
| 1498 |
|
| 1499 |
// IsEncrypted will return true if the client is connected using a TLS transport, either because it used. |
| 1500 |
// TLS to connect from the outset, or because it successfully used STARTTLS to promote a TCP connection to TLS. |
| 1501 |
func (c *Client) IsEncrypted() bool { |
| 1502 |
_, ok := c.conn.(*tls.Conn) |
| 1503 |
return ok |
| 1504 |
} |
| 1505 |
|
| 1506 |
// Chat is an incoming or outgoing XMPP chat message. |
| 1507 |
type Chat struct { |
| 1508 |
Remote string |
| 1509 |
Type string |
| 1510 |
Text string |
| 1511 |
Subject string |
| 1512 |
Thread string |
| 1513 |
// XEP-0066 Out-Of-Band url/desc |
| 1514 |
Oob Oob |
| 1515 |
// Deprecated Oob settings, use Oob.Url and Oob.Desc (above) instead. |
| 1516 |
Ooburl string |
| 1517 |
Oobdesc string |
| 1518 |
Lang string |
| 1519 |
// Only for incoming messages, ID for outgoing messages will be generated. |
| 1520 |
OriginID string |
| 1521 |
// Only for incoming messages, ID for outgoing messages will be generated. |
| 1522 |
StanzaID StanzaID |
| 1523 |
Roster Roster |
| 1524 |
Other []string |
| 1525 |
OtherElem []XMLElement |
| 1526 |
Stamp time.Time |
| 1527 |
} |
| 1528 |
|
| 1529 |
type Roster []Contact |
| 1530 |
|
| 1531 |
type Contact struct { |
| 1532 |
Remote string |
| 1533 |
Name string |
| 1534 |
Group []string |
| 1535 |
} |
| 1536 |
|
| 1537 |
// Presence is an XMPP presence notification. |
| 1538 |
type Presence struct { |
| 1539 |
From string |
| 1540 |
To string |
| 1541 |
Type string |
| 1542 |
Show string |
| 1543 |
Status string |
| 1544 |
Priority string |
| 1545 |
ID string |
| 1546 |
Affiliation string |
| 1547 |
Role string |
| 1548 |
JID string |
| 1549 |
Error string |
| 1550 |
} |
| 1551 |
|
| 1552 |
type IQError struct { |
| 1553 |
Condition string |
| 1554 |
Type string |
| 1555 |
Text string |
| 1556 |
} |
| 1557 |
|
| 1558 |
type IQ struct { |
| 1559 |
ID string |
| 1560 |
From string |
| 1561 |
To string |
| 1562 |
Type string |
| 1563 |
Query []byte |
| 1564 |
Error IQError |
| 1565 |
} |
| 1566 |
|
| 1567 |
// Recv waits to receive the next XMPP stanza. |
| 1568 |
func (c *Client) Recv() (stanza interface{}, err error) { |
| 1569 |
for { |
| 1570 |
_, val, err := c.next() |
| 1571 |
if err != nil { |
| 1572 |
return Chat{}, err |
| 1573 |
} |
| 1574 |
// Reset ticker for periodic pings if configured. |
| 1575 |
if c.periodicPings { |
| 1576 |
c.periodicPingTicker.Reset(c.periodicPingPeriod) |
| 1577 |
} |
| 1578 |
switch v := val.(type) { |
| 1579 |
case *streamError: |
| 1580 |
errorMessage := v.Text.Text |
| 1581 |
if errorMessage == "" { |
| 1582 |
// v.Any is type of sub-element in failure, |
| 1583 |
// which gives a description of what failed if there was no text element |
| 1584 |
errorMessage = v.Any.Space |
| 1585 |
} |
| 1586 |
return Chat{}, errors.New("stream error: " + errorMessage) |
| 1587 |
case *clientMessage: |
| 1588 |
if v.Event.XMLNS == XMPPNS_PUBSUB_EVENT { |
| 1589 |
// Handle Pubsub notifications |
| 1590 |
switch v.Event.Items.Node { |
| 1591 |
case XMPPNS_AVATAR_PEP_METADATA: |
| 1592 |
if len(v.Event.Items.Items) == 0 { |
| 1593 |
return AvatarMetadata{}, errors.New("no avatar metadata items available") |
| 1594 |
} |
| 1595 |
|
| 1596 |
return handleAvatarMetadata(v.Event.Items.Items[0].Body, |
| 1597 |
v.From) |
| 1598 |
// I am not sure whether this can even happen. |
| 1599 |
// XEP-0084 only specifies a subscription to |
| 1600 |
// the metadata node. |
| 1601 |
/*case XMPPNS_AVATAR_PEP_DATA: |
| 1602 |
return handleAvatarData(v.Event.Items.Items[0].Body, |
| 1603 |
v.From, |
| 1604 |
v.Event.Items.Items[0].ID)*/ |
| 1605 |
default: |
| 1606 |
return pubsubClientToReturn(v.Event), nil |
| 1607 |
} |
| 1608 |
} |
| 1609 |
|
| 1610 |
stamp, _ := time.Parse( |
| 1611 |
"2006-01-02T15:04:05Z", |
| 1612 |
v.Delay.Stamp, |
| 1613 |
) |
| 1614 |
chat := Chat{ |
| 1615 |
Remote: v.From, |
| 1616 |
Type: v.Type, |
| 1617 |
Text: v.Body, |
| 1618 |
Subject: v.Subject, |
| 1619 |
Thread: v.Thread, |
| 1620 |
Other: v.OtherStrings(), |
| 1621 |
OtherElem: v.Other, |
| 1622 |
Stamp: stamp, |
| 1623 |
Lang: v.Lang, |
| 1624 |
OriginID: v.OriginID.ID, |
| 1625 |
StanzaID: v.StanzaID, |
| 1626 |
Oob: v.Oob, |
| 1627 |
} |
| 1628 |
return chat, nil |
| 1629 |
case *clientQuery: |
| 1630 |
var r Roster |
| 1631 |
for _, item := range v.Item { |
| 1632 |
r = append(r, Contact{item.Jid, item.Name, item.Group}) |
| 1633 |
} |
| 1634 |
return Chat{Type: "roster", Roster: r}, nil |
| 1635 |
case *clientPresence: |
| 1636 |
return Presence{ |
| 1637 |
v.From, |
| 1638 |
v.To, |
| 1639 |
v.Type, |
| 1640 |
v.Show, |
| 1641 |
v.Status, |
| 1642 |
v.Priority, |
| 1643 |
v.ID, |
| 1644 |
v.X.Item.Affiliation, |
| 1645 |
v.X.Item.Role, |
| 1646 |
v.X.Item.Jid, |
| 1647 |
v.Error.Any.Local, |
| 1648 |
}, nil |
| 1649 |
case *clientIQ: |
| 1650 |
switch { |
| 1651 |
case v.Query.XMLName.Space == XMPPNS_PING && v.Type == "get": |
| 1652 |
// TODO check more strictly |
| 1653 |
err := c.SendResultPing(v.ID, v.From) |
| 1654 |
if err != nil { |
| 1655 |
return Chat{}, err |
| 1656 |
} |
| 1657 |
|
| 1658 |
case v.Query.XMLName.Space == XMPPNS_IQ_VERSION && v.Type == "get": |
| 1659 |
if c.Options.ReportSoftwareVersion { |
| 1660 |
var osName string |
| 1661 |
|
| 1662 |
if c.Options.ReportSoftwareOS { |
| 1663 |
osName = strings.SplitN(runtime.GOOS, "/", 2)[0] |
| 1664 |
} |
| 1665 |
|
| 1666 |
id, err := c.IqVersionResponse( |
| 1667 |
IQ{ID: v.ID, From: v.From, To: v.To}, |
| 1668 |
c.Options.SoftwareName, |
| 1669 |
c.Options.SoftwareVersion, |
| 1670 |
osName, |
| 1671 |
) |
| 1672 |
if err != nil { |
| 1673 |
err := fmt.Errorf( |
| 1674 |
"unable to send version info to jabber server: id=%s, err=%w", |
| 1675 |
id, |
| 1676 |
err, |
| 1677 |
) |
| 1678 |
|
| 1679 |
return Chat{}, err |
| 1680 |
} |
| 1681 |
} else { |
| 1682 |
id, err := c.ErrorServiceUnavailable( |
| 1683 |
IQ{ID: v.ID, From: v.From, To: v.To}, |
| 1684 |
XMPPNS_IQ_VERSION, |
| 1685 |
"", |
| 1686 |
) |
| 1687 |
if err != nil { |
| 1688 |
err = fmt.Errorf( |
| 1689 |
"unable to send service unavailable message stanza to jabber server: id=%s, err=%w", |
| 1690 |
id, |
| 1691 |
err, |
| 1692 |
) |
| 1693 |
|
| 1694 |
return Chat{}, err |
| 1695 |
} |
| 1696 |
} |
| 1697 |
|
| 1698 |
case v.Type == "error": |
| 1699 |
switch { |
| 1700 |
case slices.Contains(c.subIDs, v.ID): |
| 1701 |
index := slices.Index(c.subIDs, v.ID) |
| 1702 |
c.subIDs = slices.Delete(c.subIDs, index, index) |
| 1703 |
// Pubsub subscription failed |
| 1704 |
return PubsubSubscription{ |
| 1705 |
Error: v.Error.Any.Local, |
| 1706 |
}, nil |
| 1707 |
default: |
| 1708 |
res, err := xml.Marshal(v.Query) |
| 1709 |
if err != nil { |
| 1710 |
return Chat{}, err |
| 1711 |
} |
| 1712 |
return IQ{ |
| 1713 |
ID: v.ID, From: v.From, To: v.To, Type: v.Type, |
| 1714 |
Query: res, |
| 1715 |
Error: IQError{ |
| 1716 |
Condition: v.Error.Any.Local, |
| 1717 |
Type: v.Error.Type, |
| 1718 |
Text: v.Error.Text.Text, |
| 1719 |
}, |
| 1720 |
}, nil |
| 1721 |
} |
| 1722 |
case v.Type == "result": |
| 1723 |
switch { |
| 1724 |
case c.periodicPings && v.ID == c.periodicPingID: |
| 1725 |
if v.ID == c.periodicPingID { |
| 1726 |
c.periodicPingReply = true |
| 1727 |
} |
| 1728 |
case v.Query.XMLName.Space == XMPPNS_DISCO_ITEMS: |
| 1729 |
var itemsQuery clientDiscoItemsQuery |
| 1730 |
err := xml.Unmarshal(v.InnerXML, &itemsQuery) |
| 1731 |
if err != nil { |
| 1732 |
return []DiscoItem{}, err |
| 1733 |
} |
| 1734 |
|
| 1735 |
return DiscoItems{ |
| 1736 |
ID: v.ID, |
| 1737 |
Jid: v.From, |
| 1738 |
Items: clientDiscoItemsToReturn(itemsQuery.Items), |
| 1739 |
}, nil |
| 1740 |
case v.Query.XMLName.Space == XMPPNS_DISCO_INFO: |
| 1741 |
var disco clientDiscoQuery |
| 1742 |
err := xml.Unmarshal(v.InnerXML, &disco) |
| 1743 |
if err != nil { |
| 1744 |
return DiscoResult{}, err |
| 1745 |
} |
| 1746 |
|
| 1747 |
return DiscoResult{ |
| 1748 |
ID: v.ID, |
| 1749 |
From: v.From, |
| 1750 |
To: v.To, |
| 1751 |
Features: clientFeaturesToReturn(disco.Features), |
| 1752 |
Identities: clientIdentitiesToReturn(disco.Identities), |
| 1753 |
X: disco.X, |
| 1754 |
}, nil |
| 1755 |
case v.Query.XMLName.Space == XMPPNS_HTTP_UPLOAD_0: |
| 1756 |
var uploadSlot Slot |
| 1757 |
err := xml.Unmarshal([]byte(v.InnerXML), &uploadSlot) |
| 1758 |
uploadSlot.ID = v.ID |
| 1759 |
// TODO: Validate that the URLs contain HTTPS |
| 1760 |
return uploadSlot, err |
| 1761 |
case slices.Contains(c.subIDs, v.ID): |
| 1762 |
index := slices.Index(c.subIDs, v.ID) |
| 1763 |
c.subIDs = slices.Delete(c.subIDs, index, index) |
| 1764 |
if v.Query.XMLName.Local == "pubsub" { |
| 1765 |
// Subscription or unsubscription was successful |
| 1766 |
var sub clientPubsubSubscription |
| 1767 |
err := xml.Unmarshal([]byte(v.Query.InnerXML), &sub) |
| 1768 |
if err != nil { |
| 1769 |
return PubsubSubscription{}, err |
| 1770 |
} |
| 1771 |
|
| 1772 |
return PubsubSubscription{ |
| 1773 |
SubID: sub.SubID, |
| 1774 |
JID: sub.JID, |
| 1775 |
Node: sub.Node, |
| 1776 |
Error: "", |
| 1777 |
}, nil |
| 1778 |
} |
| 1779 |
case slices.Contains(c.unsubIDs, v.ID): |
| 1780 |
index := slices.Index(c.unsubIDs, v.ID) |
| 1781 |
c.unsubIDs = slices.Delete(c.unsubIDs, index, index) |
| 1782 |
if v.Query.XMLName.Local == "pubsub" { |
| 1783 |
var sub clientPubsubSubscription |
| 1784 |
err := xml.Unmarshal([]byte(v.Query.InnerXML), &sub) |
| 1785 |
if err != nil { |
| 1786 |
return PubsubUnsubscription{}, err |
| 1787 |
} |
| 1788 |
|
| 1789 |
return PubsubUnsubscription{ |
| 1790 |
SubID: sub.SubID, |
| 1791 |
JID: v.From, |
| 1792 |
Node: sub.Node, |
| 1793 |
Error: "", |
| 1794 |
}, nil |
| 1795 |
} else { |
| 1796 |
// Unsubscribing MAY contain a pubsub element. But it does |
| 1797 |
// not have to |
| 1798 |
return PubsubUnsubscription{ |
| 1799 |
SubID: "", |
| 1800 |
JID: v.From, |
| 1801 |
Node: "", |
| 1802 |
Error: "", |
| 1803 |
}, nil |
| 1804 |
} |
| 1805 |
case slices.Contains(c.itemsIDs, v.ID): |
| 1806 |
index := slices.Index(c.itemsIDs, v.ID) |
| 1807 |
c.itemsIDs = slices.Delete(c.itemsIDs, index, index) |
| 1808 |
if v.Query.XMLName.Local == "pubsub" { |
| 1809 |
var p clientPubsubItems |
| 1810 |
err := xml.Unmarshal([]byte(v.Query.InnerXML), &p) |
| 1811 |
if err != nil { |
| 1812 |
return PubsubItems{}, err |
| 1813 |
} |
| 1814 |
|
| 1815 |
switch p.Node { |
| 1816 |
case XMPPNS_AVATAR_PEP_DATA: |
| 1817 |
if len(p.Items) == 0 { |
| 1818 |
return AvatarData{}, errors.New("no avatar data items available") |
| 1819 |
} |
| 1820 |
|
| 1821 |
return handleAvatarData(p.Items[0].Body, |
| 1822 |
v.From, |
| 1823 |
p.Items[0].ID) |
| 1824 |
case XMPPNS_AVATAR_PEP_METADATA: |
| 1825 |
if len(p.Items) == 0 { |
| 1826 |
return AvatarMetadata{}, errors.New("no avatar metadata items available") |
| 1827 |
} |
| 1828 |
|
| 1829 |
return handleAvatarMetadata(p.Items[0].Body, |
| 1830 |
v.From) |
| 1831 |
default: |
| 1832 |
return PubsubItems{ |
| 1833 |
p.Node, |
| 1834 |
pubsubItemsToReturn(p.Items), |
| 1835 |
}, nil |
| 1836 |
} |
| 1837 |
} |
| 1838 |
// Note: XEP-0084 states that metadata and data |
| 1839 |
// should be fetched with an id of retrieve1. |
| 1840 |
// Since we already have PubSub implemented, we |
| 1841 |
// can just use items1 and items3 to do the same |
| 1842 |
// as an Avatar node is just a PEP (PubSub) node. |
| 1843 |
/*case "retrieve1": |
| 1844 |
var p clientPubsubItems |
| 1845 |
err := xml.Unmarshal([]byte(v.Query.InnerXML), &p) |
| 1846 |
if err != nil { |
| 1847 |
return PubsubItems{}, err |
| 1848 |
} |
| 1849 |
|
| 1850 |
switch p.Node { |
| 1851 |
case XMPPNS_AVATAR_PEP_DATA: |
| 1852 |
return handleAvatarData(p.Items[0].Body, |
| 1853 |
v.From, |
| 1854 |
p.Items[0].ID) |
| 1855 |
case XMPPNS_AVATAR_PEP_METADATA: |
| 1856 |
return handleAvatarMetadata(p.Items[0].Body, |
| 1857 |
v |
| 1858 |
}*/ |
| 1859 |
default: |
| 1860 |
res, err := xml.Marshal(v.Query) |
| 1861 |
if err != nil { |
| 1862 |
return Chat{}, err |
| 1863 |
} |
| 1864 |
|
| 1865 |
return IQ{ |
| 1866 |
ID: v.ID, From: v.From, To: v.To, Type: v.Type, |
| 1867 |
Query: res, |
| 1868 |
}, nil |
| 1869 |
} |
| 1870 |
case v.Query.XMLName.Local == "": |
| 1871 |
return IQ{ID: v.ID, From: v.From, To: v.To, Type: v.Type}, nil |
| 1872 |
default: |
| 1873 |
res, err := xml.Marshal(v.Query) |
| 1874 |
if err != nil { |
| 1875 |
return Chat{}, err |
| 1876 |
} |
| 1877 |
|
| 1878 |
return IQ{ |
| 1879 |
ID: v.ID, From: v.From, To: v.To, Type: v.Type, |
| 1880 |
Query: res, |
| 1881 |
}, nil |
| 1882 |
} |
| 1883 |
} |
| 1884 |
} |
| 1885 |
} |
| 1886 |
|
| 1887 |
// Send sends the message wrapped inside an XMPP message stanza body. |
| 1888 |
func (c *Client) Send(chat Chat) (n int, err error) { |
| 1889 |
var subtext, thdtext, oobtext string |
| 1890 |
if chat.Subject != `` { |
| 1891 |
subtext = `<subject>` + xmlEscape(chat.Subject) + `</subject>` |
| 1892 |
} |
| 1893 |
if chat.Thread != `` { |
| 1894 |
thdtext = `<thread>` + xmlEscape(chat.Thread) + `</thread>` |
| 1895 |
} |
| 1896 |
if chat.Oob.Url != `` || chat.Ooburl != `` { |
| 1897 |
if chat.Oob.Url == `` { |
| 1898 |
chat.Oob.Url = chat.Ooburl |
| 1899 |
fmt.Println("xmpp: chat.Ooburl is deprecated, use chat.Oob.Url instead.") |
| 1900 |
} |
| 1901 |
oobtext = `<x xmlns="jabber:x:oob"><url>` + xmlEscape(chat.Oob.Url) + `</url>` |
| 1902 |
if chat.Oob.Desc != `` || chat.Oobdesc != `` { |
| 1903 |
if chat.Oob.Desc == `` { |
| 1904 |
chat.Oob.Desc = chat.Oobdesc |
| 1905 |
fmt.Println("xmpp: chat.Oobdesc is deprecated, use chat.Oob.Desc instead.") |
| 1906 |
} |
| 1907 |
oobtext += `<desc>` + xmlEscape(chat.Oob.Desc) + `</desc>` |
| 1908 |
} |
| 1909 |
oobtext += `</x>` |
| 1910 |
} |
| 1911 |
|
| 1912 |
chat.Text = validUTF8(chat.Text) |
| 1913 |
id := getUUID() |
| 1914 |
stanza := fmt.Sprintf("<message to='%s' type='%s' id='%s' xml:lang='en'>%s<body>%s</body>"+ |
| 1915 |
"<origin-id xmlns='%s' id='%s'/>%s%s</message>\n", |
| 1916 |
xmlEscape(chat.Remote), xmlEscape(chat.Type), id, subtext, xmlEscape(chat.Text), |
| 1917 |
XMPPNS_SID_0, id, oobtext, thdtext) |
| 1918 |
if c.LimitMaxBytes != 0 && len(stanza) > c.LimitMaxBytes { |
| 1919 |
return 0, fmt.Errorf("stanza size (%v bytes) exceeds server limit (%v bytes)", |
| 1920 |
len(stanza), c.LimitMaxBytes) |
| 1921 |
} |
| 1922 |
|
| 1923 |
return fmt.Fprint(c.stanzaWriter, stanza) |
| 1924 |
} |
| 1925 |
|
| 1926 |
// SendOOB sends OOB data wrapped inside an XMPP message stanza. Any message body will be discarded |
| 1927 |
// and replaced by the OOB URL.. |
| 1928 |
func (c *Client) SendOOB(chat Chat) (n int, err error) { |
| 1929 |
var thdtext, oobtext string |
| 1930 |
if chat.Thread != `` { |
| 1931 |
thdtext = `<thread>` + xmlEscape(chat.Thread) + `</thread>` |
| 1932 |
} |
| 1933 |
if chat.Oob.Url == `` && chat.Ooburl == `` { |
| 1934 |
return 0, fmt.Errorf("SendOOB requires chat.Oob.Url to be set") |
| 1935 |
} |
| 1936 |
if chat.Oob.Url == `` { |
| 1937 |
chat.Oob.Url = chat.Ooburl |
| 1938 |
fmt.Println("xmpp: chat.Ooburl is deprecated, use chat.Oob.Url instead.") |
| 1939 |
} |
| 1940 |
if chat.Oob.Desc == `` && chat.Oobdesc != `` { |
| 1941 |
chat.Oob.Desc = chat.Oobdesc |
| 1942 |
fmt.Println("xmpp: chat.Oobdesc is deprecated, use chat.Oob.Desc instead.") |
| 1943 |
} |
| 1944 |
oobtext = `<x xmlns="jabber:x:oob"><url>` + xmlEscape(chat.Oob.Url) + `</url>` |
| 1945 |
if chat.Oob.Desc != `` { |
| 1946 |
oobtext += `<desc>` + xmlEscape(chat.Oob.Desc) + `</desc>` |
| 1947 |
} |
| 1948 |
oobtext += `</x>` |
| 1949 |
id := getUUID() |
| 1950 |
stanza := fmt.Sprintf("<message to='%s' type='%s' id='%s' xml:lang='en'>"+ |
| 1951 |
"<origin-id xmlns='%s' id='%s'/>%s%s<body>%s</body></message>\n", |
| 1952 |
xmlEscape(chat.Remote), xmlEscape(chat.Type), id, XMPPNS_SID_0, id, |
| 1953 |
oobtext, thdtext, xmlEscape(chat.Oob.Url)) |
| 1954 |
if c.LimitMaxBytes != 0 && len(stanza) > c.LimitMaxBytes { |
| 1955 |
return 0, fmt.Errorf("stanza size (%v bytes) exceeds server limit (%v bytes)", |
| 1956 |
len(stanza), c.LimitMaxBytes) |
| 1957 |
} |
| 1958 |
return fmt.Fprint(c.stanzaWriter, stanza) |
| 1959 |
} |
| 1960 |
|
| 1961 |
// SendOrg sends the original text without being wrapped in an XMPP message stanza. |
| 1962 |
func (c *Client) SendOrg(org string) (n int, err error) { |
| 1963 |
stanza := fmt.Sprint(org + "\n") |
| 1964 |
if c.LimitMaxBytes != 0 && len(stanza) > c.LimitMaxBytes { |
| 1965 |
return 0, fmt.Errorf("stanza size (%v bytes) exceeds server limit (%v bytes)", |
| 1966 |
len(stanza), c.LimitMaxBytes) |
| 1967 |
} |
| 1968 |
return fmt.Fprint(c.stanzaWriter, stanza) |
| 1969 |
} |
| 1970 |
|
| 1971 |
// SendPresence sends Presence wrapped inside XMPP presence stanza. |
| 1972 |
func (c *Client) SendPresence(presence Presence) (n int, err error) { |
| 1973 |
// Forge opening presence tag |
| 1974 |
var buf string = "<presence" |
| 1975 |
|
| 1976 |
if presence.From != "" { |
| 1977 |
buf = buf + fmt.Sprintf(" from='%s'", xmlEscape(presence.From)) |
| 1978 |
} |
| 1979 |
|
| 1980 |
if presence.To != "" { |
| 1981 |
buf = buf + fmt.Sprintf(" to='%s'", xmlEscape(presence.To)) |
| 1982 |
} |
| 1983 |
|
| 1984 |
if presence.Type != "" { |
| 1985 |
// https://www.ietf.org/rfc/rfc3921.txt, 2.2.1, types can only be |
| 1986 |
// unavailable, subscribe, subscribed, unsubscribe, unsubscribed, probe, error |
| 1987 |
switch presence.Type { |
| 1988 |
case "unavailable", "subscribe", "subscribed", "unsubscribe", "unsubscribed", "probe", "error": |
| 1989 |
buf = buf + fmt.Sprintf(" type='%s'", xmlEscape(presence.Type)) |
| 1990 |
} |
| 1991 |
} |
| 1992 |
|
| 1993 |
buf = buf + ">" |
| 1994 |
|
| 1995 |
// TODO: there may be optional tag "priority", but former presence type does not take this into account |
| 1996 |
// so either we must follow std, change type xmpp.Presence and break backward compatibility |
| 1997 |
// or leave it as-is and potentially break client software |
| 1998 |
|
| 1999 |
if presence.Show != "" { |
| 2000 |
// https://www.ietf.org/rfc/rfc3921.txt 2.2.2.1, show can be only |
| 2001 |
// away, chat, dnd, xa |
| 2002 |
switch presence.Show { |
| 2003 |
case "away", "chat", "dnd", "xa": |
| 2004 |
buf = buf + fmt.Sprintf("<show>%s</show>", xmlEscape(presence.Show)) |
| 2005 |
} |
| 2006 |
} |
| 2007 |
|
| 2008 |
if presence.Status != "" { |
| 2009 |
buf = buf + fmt.Sprintf("<status>%s</status>", xmlEscape(presence.Status)) |
| 2010 |
} |
| 2011 |
|
| 2012 |
stanza := fmt.Sprintf("%s</presence>\n", buf) |
| 2013 |
if c.LimitMaxBytes != 0 && len(stanza) > c.LimitMaxBytes { |
| 2014 |
return 0, fmt.Errorf("stanza size (%v bytes) exceeds server limit (%v bytes)", |
| 2015 |
len(stanza), c.LimitMaxBytes) |
| 2016 |
} |
| 2017 |
return fmt.Fprint(c.stanzaWriter, stanza) |
| 2018 |
} |
| 2019 |
|
| 2020 |
// SendKeepAlive sends a "whitespace keepalive" as described in chapter 4.6.1 of RFC6120. |
| 2021 |
func (c *Client) SendKeepAlive() (n int, err error) { |
| 2022 |
return fmt.Fprintf(c.conn, " ") |
| 2023 |
} |
| 2024 |
|
| 2025 |
// SendHtml sends the message as HTML as defined by XEP-0071 |
| 2026 |
func (c *Client) SendHtml(chat Chat) (n int, err error) { |
| 2027 |
id := getUUID() |
| 2028 |
stanza := fmt.Sprintf("<message to='%s' type='%s' xml:lang='en'><body>%s</body><origin-id xmlns='%s' id='%s'/>"+ |
| 2029 |
"<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns='http://www.w3.org/1999/xhtml'>%s</body>"+ |
| 2030 |
"</html></message>\n", |
| 2031 |
xmlEscape(chat.Remote), xmlEscape(chat.Type), xmlEscape(chat.Text), XMPPNS_SID_0, id, chat.Text) |
| 2032 |
if c.LimitMaxBytes != 0 && len(stanza) > c.LimitMaxBytes { |
| 2033 |
return 0, fmt.Errorf("stanza size (%v bytes) exceeds server limit (%v bytes)", |
| 2034 |
len(stanza), c.LimitMaxBytes) |
| 2035 |
} |
| 2036 |
return fmt.Fprint(c.stanzaWriter, stanza) |
| 2037 |
} |
| 2038 |
|
| 2039 |
// Roster asks for the chat roster. |
| 2040 |
func (c *Client) Roster() error { |
| 2041 |
fmt.Fprintf(c.stanzaWriter, "<iq from='%s' type='get' id='roster1'><query xmlns='jabber:iq:roster'/></iq>\n", xmlEscape(c.jid)) |
| 2042 |
return nil |
| 2043 |
} |
| 2044 |
|
| 2045 |
// RFC 3920 C.1 Streams name space |
| 2046 |
type streamFeatures struct { |
| 2047 |
XMLName xml.Name `xml:"http://etherx.jabber.org/streams features"` |
| 2048 |
Authentication sasl2Authentication |
| 2049 |
StartTLS *tlsStartTLS |
| 2050 |
Mechanisms saslMechanisms |
| 2051 |
ChannelBindings saslChannelBindings |
| 2052 |
Bind bindBind |
| 2053 |
Session bool |
| 2054 |
Limits streamLimits |
| 2055 |
} |
| 2056 |
|
| 2057 |
type streamError struct { |
| 2058 |
XMLName xml.Name `xml:"http://etherx.jabber.org/streams error"` |
| 2059 |
Any xml.Name |
| 2060 |
Text struct { |
| 2061 |
Text string `xml:",chardata"` |
| 2062 |
Lang string `xml:"lang,attr"` |
| 2063 |
Xmlns string `xml:"xmlns,attr"` |
| 2064 |
} `xml:"text"` |
| 2065 |
SeeOtherHost struct { |
| 2066 |
Text string `xml:",chardata"` |
| 2067 |
Xmlns string `xml:"xmlns,attr"` |
| 2068 |
} `xml:"see-other-host"` |
| 2069 |
} |
| 2070 |
|
| 2071 |
// RFC 3920 C.3 TLS name space |
| 2072 |
type tlsStartTLS struct { |
| 2073 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls starttls"` |
| 2074 |
Required *string `xml:"required"` |
| 2075 |
} |
| 2076 |
|
| 2077 |
type tlsProceed struct { |
| 2078 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls proceed"` |
| 2079 |
} |
| 2080 |
|
| 2081 |
type tlsFailure struct { |
| 2082 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls failure"` |
| 2083 |
} |
| 2084 |
|
| 2085 |
type sasl2Authentication struct { |
| 2086 |
XMLName xml.Name `xml:"urn:xmpp:sasl:2 authentication"` |
| 2087 |
Mechanism []string `xml:"mechanism"` |
| 2088 |
Inline struct { |
| 2089 |
Text string `xml:",chardata"` |
| 2090 |
Bind struct { |
| 2091 |
XMLName xml.Name `xml:"urn:xmpp:bind:0 bind"` |
| 2092 |
Xmlns string `xml:"xmlns,attr"` |
| 2093 |
Text string `xml:",chardata"` |
| 2094 |
} `xml:"bind"` |
| 2095 |
Fast struct { |
| 2096 |
XMLName xml.Name `xml:"urn:xmpp:fast:0 fast"` |
| 2097 |
Text string `xml:",chardata"` |
| 2098 |
Tls0rtt string `xml:"tls-0rtt,attr"` |
| 2099 |
Mechanism []string `xml:"mechanism"` |
| 2100 |
} `xml:"fast"` |
| 2101 |
} `xml:"inline"` |
| 2102 |
Upgrade []struct { |
| 2103 |
Text string `xml:",chardata"` |
| 2104 |
Xmlns string `xml:"xmlns,attr"` |
| 2105 |
} `xml:"upgrade"` |
| 2106 |
} |
| 2107 |
|
| 2108 |
// RFC 3920 C.4 SASL name space |
| 2109 |
type saslMechanisms struct { |
| 2110 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl mechanisms"` |
| 2111 |
Mechanism []string `xml:"mechanism"` |
| 2112 |
} |
| 2113 |
|
| 2114 |
type saslChannelBindings struct { |
| 2115 |
XMLName xml.Name `xml:"sasl-channel-binding"` |
| 2116 |
Text string `xml:",chardata"` |
| 2117 |
Xmlns string `xml:"xmlns,attr"` |
| 2118 |
ChannelBinding []struct { |
| 2119 |
Text string `xml:",chardata"` |
| 2120 |
Type string `xml:"type,attr"` |
| 2121 |
} `xml:"channel-binding"` |
| 2122 |
} |
| 2123 |
|
| 2124 |
type saslAbort struct { |
| 2125 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl abort"` |
| 2126 |
} |
| 2127 |
|
| 2128 |
type sasl2Success struct { |
| 2129 |
XMLName xml.Name `xml:"urn:xmpp:sasl:2 success"` |
| 2130 |
Text string `xml:",chardata"` |
| 2131 |
AdditionalData string `xml:"additional-data"` |
| 2132 |
AuthorizationIdentifier string `xml:"authorization-identifier"` |
| 2133 |
Bound struct { |
| 2134 |
Text string `xml:",chardata"` |
| 2135 |
Xmlns string `xml:"urn:xmpp:bind:0,attr"` |
| 2136 |
} `xml:"bound"` |
| 2137 |
Token struct { |
| 2138 |
Text string `xml:",chardata"` |
| 2139 |
Xmlns string `xml:"urn:xmpp:fast:0,attr"` |
| 2140 |
Expiry string `xml:"expiry,attr"` |
| 2141 |
Token string `xml:"token,attr"` |
| 2142 |
} `xml:"token"` |
| 2143 |
} |
| 2144 |
|
| 2145 |
type sasl2Continue struct { |
| 2146 |
XMLName xml.Name `xml:"continue"` |
| 2147 |
Text string `xml:",chardata"` |
| 2148 |
Xmlns string `xml:"xmlns,attr"` |
| 2149 |
AdditionalData string `xml:"additional-data"` |
| 2150 |
Tasks struct { |
| 2151 |
Text string `xml:",chardata"` |
| 2152 |
Task string `xml:"task"` |
| 2153 |
} `xml:"tasks"` |
| 2154 |
} |
| 2155 |
|
| 2156 |
type sasl2TaskData struct { |
| 2157 |
XMLName xml.Name `xml:"task-data"` |
| 2158 |
Text string `xml:",chardata"` |
| 2159 |
Xmlns string `xml:"xmlns,attr"` |
| 2160 |
Salt struct { |
| 2161 |
Text string `xml:",chardata"` |
| 2162 |
Xmlns string `xml:"xmlns,attr"` |
| 2163 |
Iterations int `xml:"iterations,attr"` |
| 2164 |
} `xml:"salt"` |
| 2165 |
} |
| 2166 |
|
| 2167 |
type saslSuccess struct { |
| 2168 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl success"` |
| 2169 |
Text string `xml:",chardata"` |
| 2170 |
} |
| 2171 |
|
| 2172 |
type sasl2Failure struct { |
| 2173 |
XMLName xml.Name `xml:"urn:xmpp:sasl:2 failure"` |
| 2174 |
Any xml.Name `xml:",any"` |
| 2175 |
Text string `xml:"text"` |
| 2176 |
} |
| 2177 |
|
| 2178 |
type saslFailure struct { |
| 2179 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl failure"` |
| 2180 |
Any xml.Name `xml:",any"` |
| 2181 |
Text string `xml:"text"` |
| 2182 |
} |
| 2183 |
|
| 2184 |
type sasl2Challenge struct { |
| 2185 |
XMLName xml.Name `xml:"urn:xmpp:sasl:2 challenge"` |
| 2186 |
Text string `xml:",chardata"` |
| 2187 |
} |
| 2188 |
|
| 2189 |
type saslChallenge struct { |
| 2190 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl challenge"` |
| 2191 |
Text string `xml:",chardata"` |
| 2192 |
} |
| 2193 |
|
| 2194 |
type streamLimits struct { |
| 2195 |
XMLName xml.Name `xml:"limits"` |
| 2196 |
Text string `xml:",chardata"` |
| 2197 |
Xmlns string `xml:"xmlns,attr"` |
| 2198 |
MaxBytes string `xml:"max-bytes"` |
| 2199 |
IdleSeconds string `xml:"idle-seconds"` |
| 2200 |
} |
| 2201 |
|
| 2202 |
// RFC 3920 C.5 Resource binding name space |
| 2203 |
type bindBind struct { |
| 2204 |
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"` |
| 2205 |
Resource string |
| 2206 |
Jid string `xml:"jid"` |
| 2207 |
} |
| 2208 |
|
| 2209 |
// XEP-0359 Origin ID |
| 2210 |
type originID struct { |
| 2211 |
XMLName xml.Name `xml:"origin-id"` |
| 2212 |
Text string `xml:",chardata"` |
| 2213 |
Xmlns string `xml:"xmlns,attr"` |
| 2214 |
ID string `xml:"id,attr"` |
| 2215 |
} |
| 2216 |
|
| 2217 |
// XEP-0359 Stanza ID |
| 2218 |
type StanzaID struct { |
| 2219 |
XMLName xml.Name `xml:"stanza-id"` |
| 2220 |
Text string `xml:",chardata"` |
| 2221 |
Xmlns string `xml:"xmlns,attr"` |
| 2222 |
ID string `xml:"id,attr"` |
| 2223 |
By string `xml:"by,attr"` |
| 2224 |
} |
| 2225 |
|
| 2226 |
// RFC 3921 B.1 jabber:client |
| 2227 |
type clientMessage struct { |
| 2228 |
XMLName xml.Name `xml:"jabber:client message"` |
| 2229 |
From string `xml:"from,attr"` |
| 2230 |
ID string `xml:"id,attr"` |
| 2231 |
To string `xml:"to,attr"` |
| 2232 |
Type string `xml:"type,attr"` // chat, error, groupchat, headline, or normal |
| 2233 |
Lang string `xml:"lang,attr"` |
| 2234 |
|
| 2235 |
// These should technically be []clientText, but string is much more convenient. |
| 2236 |
Subject string `xml:"subject"` |
| 2237 |
Body string `xml:"body"` |
| 2238 |
Thread string `xml:"thread"` |
| 2239 |
|
| 2240 |
// XEP-0359 |
| 2241 |
OriginID originID `xml:"origin-id"` |
| 2242 |
StanzaID StanzaID `xml:"stanza-id"` |
| 2243 |
|
| 2244 |
// Pubsub |
| 2245 |
Event clientPubsubEvent `xml:"event"` |
| 2246 |
|
| 2247 |
// XEP-0060 OOB |
| 2248 |
Oob Oob |
| 2249 |
|
| 2250 |
// Any hasn't matched element |
| 2251 |
Other []XMLElement `xml:",any"` |
| 2252 |
|
| 2253 |
Delay Delay `xml:"delay"` |
| 2254 |
} |
| 2255 |
|
| 2256 |
func (m *clientMessage) OtherStrings() []string { |
| 2257 |
a := make([]string, len(m.Other)) |
| 2258 |
for i, e := range m.Other { |
| 2259 |
a[i] = e.String() |
| 2260 |
} |
| 2261 |
return a |
| 2262 |
} |
| 2263 |
|
| 2264 |
type XMLElement struct { |
| 2265 |
XMLName xml.Name |
| 2266 |
Attr []xml.Attr `xml:",any,attr"` // Save the attributes of the xml element |
| 2267 |
InnerXML string `xml:",innerxml"` |
| 2268 |
} |
| 2269 |
|
| 2270 |
func (e *XMLElement) String() string { |
| 2271 |
r := bytes.NewReader([]byte(e.InnerXML)) |
| 2272 |
d := xml.NewDecoder(r) |
| 2273 |
var buf bytes.Buffer |
| 2274 |
for { |
| 2275 |
tok, err := d.Token() |
| 2276 |
if err != nil { |
| 2277 |
break |
| 2278 |
} |
| 2279 |
switch v := tok.(type) { |
| 2280 |
case xml.StartElement: |
| 2281 |
err = d.Skip() |
| 2282 |
case xml.CharData: |
| 2283 |
_, err = buf.Write(v) |
| 2284 |
} |
| 2285 |
if err != nil { |
| 2286 |
break |
| 2287 |
} |
| 2288 |
} |
| 2289 |
return buf.String() |
| 2290 |
} |
| 2291 |
|
| 2292 |
type Delay struct { |
| 2293 |
Stamp string `xml:"stamp,attr"` |
| 2294 |
} |
| 2295 |
|
| 2296 |
type clientPresence struct { |
| 2297 |
XMLName xml.Name `xml:"jabber:client presence"` |
| 2298 |
From string `xml:"from,attr"` |
| 2299 |
ID string `xml:"id,attr"` |
| 2300 |
To string `xml:"to,attr"` |
| 2301 |
Type string `xml:"type,attr"` // error, probe, subscribe, subscribed, unavailable, unsubscribe, unsubscribed |
| 2302 |
Lang string `xml:"lang,attr"` |
| 2303 |
X struct { |
| 2304 |
Text string `xml:",chardata"` |
| 2305 |
Xmlns string `xml:"xmlns,attr"` |
| 2306 |
Item struct { |
| 2307 |
Text string `xml:",chardata"` |
| 2308 |
Affiliation string `xml:"affiliation,attr"` |
| 2309 |
Jid string `xml:"jid,attr"` |
| 2310 |
Role string `xml:"role,attr"` |
| 2311 |
} `xml:"item"` |
| 2312 |
} `xml:"x"` |
| 2313 |
Show string `xml:"show"` // away, chat, dnd, xa |
| 2314 |
Status string `xml:"status"` // sb []clientText |
| 2315 |
Priority string `xml:"priority,attr"` |
| 2316 |
Error struct { |
| 2317 |
By string `xml:"by,attr"` |
| 2318 |
Type string `xml:"type,attr"` |
| 2319 |
Any xml.Name `xml:",any"` |
| 2320 |
} `xml:"error"` |
| 2321 |
} |
| 2322 |
|
| 2323 |
type clientIQ struct { |
| 2324 |
// info/query |
| 2325 |
XMLName xml.Name `xml:"jabber:client iq"` |
| 2326 |
From string `xml:"from,attr"` |
| 2327 |
ID string `xml:"id,attr"` |
| 2328 |
To string `xml:"to,attr"` |
| 2329 |
Type string `xml:"type,attr"` // error, get, result, set |
| 2330 |
Query XMLElement `xml:",any"` |
| 2331 |
Error clientError |
| 2332 |
Bind bindBind |
| 2333 |
|
| 2334 |
InnerXML []byte `xml:",innerxml"` |
| 2335 |
} |
| 2336 |
|
| 2337 |
type clientError struct { |
| 2338 |
XMLName xml.Name `xml:"jabber:client error"` |
| 2339 |
Any xml.Name `xml:",any"` |
| 2340 |
Code string `xml:",attr"` |
| 2341 |
Type string `xml:"type,attr"` |
| 2342 |
Text struct { |
| 2343 |
Text string `xml:",chardata"` |
| 2344 |
Xmlns string `xml:"xmlns,attr"` |
| 2345 |
Lang string `xml:"lang,attr"` |
| 2346 |
} `xml:"text"` |
| 2347 |
} |
| 2348 |
|
| 2349 |
type clientQuery struct { |
| 2350 |
Item []rosterItem |
| 2351 |
} |
| 2352 |
|
| 2353 |
type rosterItem struct { |
| 2354 |
XMLName xml.Name `xml:"jabber:iq:roster item"` |
| 2355 |
Jid string `xml:",attr"` |
| 2356 |
Name string `xml:",attr"` |
| 2357 |
Subscription string `xml:",attr"` |
| 2358 |
Group []string |
| 2359 |
} |
| 2360 |
|
| 2361 |
// Scan XML token stream to find next StartElement. |
| 2362 |
func (c *Client) nextStart() (xml.StartElement, error) { |
| 2363 |
for { |
| 2364 |
// Do not read from the stream if it's |
| 2365 |
// going to be closed. |
| 2366 |
if c.shutdown { |
| 2367 |
return xml.StartElement{}, io.EOF |
| 2368 |
} |
| 2369 |
c.nextMutex.Lock() |
| 2370 |
to, err := c.p.Token() |
| 2371 |
if err != nil || to == nil { |
| 2372 |
c.nextMutex.Unlock() |
| 2373 |
return xml.StartElement{}, err |
| 2374 |
} |
| 2375 |
t := xml.CopyToken(to) |
| 2376 |
switch t := t.(type) { |
| 2377 |
case xml.StartElement: |
| 2378 |
c.nextMutex.Unlock() |
| 2379 |
return t, nil |
| 2380 |
case xml.EndElement: |
| 2381 |
if t.Name.Space == XMPPNS_STREAM && t.Name.Local == "stream" { |
| 2382 |
c.nextMutex.Unlock() |
| 2383 |
return xml.StartElement{}, fmt.Errorf("server closed stream") |
| 2384 |
} |
| 2385 |
} |
| 2386 |
c.nextMutex.Unlock() |
| 2387 |
} |
| 2388 |
} |
| 2389 |
|
| 2390 |
// Scan XML token stream to find next EndElement |
| 2391 |
func (c *Client) nextEnd() (xml.EndElement, error) { |
| 2392 |
c.p.Strict = false |
| 2393 |
for { |
| 2394 |
c.nextMutex.Lock() |
| 2395 |
to, err := c.p.Token() |
| 2396 |
if err != nil || to == nil { |
| 2397 |
c.nextMutex.Unlock() |
| 2398 |
return xml.EndElement{}, err |
| 2399 |
} |
| 2400 |
t := xml.CopyToken(to) |
| 2401 |
switch t := t.(type) { |
| 2402 |
case xml.EndElement: |
| 2403 |
// Do not unlock mutex if the stream is closed to |
| 2404 |
// prevent further reading on the stream. |
| 2405 |
if t.Name.Space == XMPPNS_STREAM && t.Name.Local == "error" { |
| 2406 |
return t, fmt.Errorf("server closed stream with error") |
| 2407 |
} |
| 2408 |
if t.Name.Space == XMPPNS_STREAM && t.Name.Local == "stream" { |
| 2409 |
return t, nil |
| 2410 |
} |
| 2411 |
c.nextMutex.Unlock() |
| 2412 |
return t, nil |
| 2413 |
} |
| 2414 |
c.nextMutex.Unlock() |
| 2415 |
} |
| 2416 |
} |
| 2417 |
|
| 2418 |
// Scan XML token stream for next element and save into val. |
| 2419 |
// If val == nil, allocate new element based on proto map. |
| 2420 |
// Either way, return val. |
| 2421 |
func (c *Client) next() (xml.Name, interface{}, error) { |
| 2422 |
// Read start element to find out what type we want. |
| 2423 |
se, err := c.nextStart() |
| 2424 |
if err != nil { |
| 2425 |
return xml.Name{}, nil, err |
| 2426 |
} |
| 2427 |
|
| 2428 |
// Put it in an interface and allocate one. |
| 2429 |
var nv interface{} |
| 2430 |
switch se.Name.Space + " " + se.Name.Local { |
| 2431 |
case XMPPNS_STREAM + " features": |
| 2432 |
nv = &streamFeatures{} |
| 2433 |
case XMPPNS_STREAM + " error": |
| 2434 |
nv = &streamError{} |
| 2435 |
case XMPPNS_XMPP_TLS + " starttls": |
| 2436 |
nv = &tlsStartTLS{} |
| 2437 |
case XMPPNS_XMPP_TLS + " proceed": |
| 2438 |
nv = &tlsProceed{} |
| 2439 |
case XMPPNS_XMPP_TLS + " failure": |
| 2440 |
nv = &tlsFailure{} |
| 2441 |
case XMPPNS_XMPP_SASL + " mechanisms": |
| 2442 |
nv = &saslMechanisms{} |
| 2443 |
case XMPPNS_SASL_2 + " challenge": |
| 2444 |
nv = &sasl2Challenge{} |
| 2445 |
case XMPPNS_XMPP_SASL + " challenge": |
| 2446 |
nv = &saslChallenge{} |
| 2447 |
case XMPPNS_XMPP_SASL + " response": |
| 2448 |
nv = "" |
| 2449 |
case XMPPNS_XMPP_SASL + " abort": |
| 2450 |
nv = &saslAbort{} |
| 2451 |
case XMPPNS_SASL_2 + " success": |
| 2452 |
nv = &sasl2Success{} |
| 2453 |
case XMPPNS_SASL_2 + " continue": |
| 2454 |
nv = &sasl2Continue{} |
| 2455 |
case XMPPNS_SASL_2 + " task-data": |
| 2456 |
nv = &sasl2TaskData{} |
| 2457 |
case XMPPNS_XMPP_SASL + " success": |
| 2458 |
nv = &saslSuccess{} |
| 2459 |
case XMPPNS_SASL_2 + " failure": |
| 2460 |
nv = &sasl2Failure{} |
| 2461 |
case XMPPNS_XMPP_SASL + " failure": |
| 2462 |
nv = &saslFailure{} |
| 2463 |
case XMPPNS_SASL_CB_0 + " sasl-channel-binding": |
| 2464 |
nv = &saslChannelBindings{} |
| 2465 |
case XMPPNS_XMPP_BIND + " bind": |
| 2466 |
nv = &bindBind{} |
| 2467 |
case XMPPNS_CLIENT + " message": |
| 2468 |
nv = &clientMessage{} |
| 2469 |
case XMPPNS_CLIENT + " presence": |
| 2470 |
nv = &clientPresence{} |
| 2471 |
case XMPPNS_CLIENT + " iq": |
| 2472 |
nv = &clientIQ{} |
| 2473 |
case XMPPNS_CLIENT + " error": |
| 2474 |
nv = &clientError{} |
| 2475 |
default: |
| 2476 |
return xml.Name{}, nil, errors.New("unexpected XMPP message " + |
| 2477 |
se.Name.Space + " <" + se.Name.Local + "/>") |
| 2478 |
} |
| 2479 |
|
| 2480 |
// Unmarshal into that storage. |
| 2481 |
c.nextMutex.Lock() |
| 2482 |
if err = c.p.DecodeElement(nv, &se); err != nil { |
| 2483 |
return xml.Name{}, nil, err |
| 2484 |
} |
| 2485 |
c.nextMutex.Unlock() |
| 2486 |
|
| 2487 |
return se.Name, nv, err |
| 2488 |
} |
| 2489 |
|
| 2490 |
func xmlEscape(s string) string { |
| 2491 |
var b bytes.Buffer |
| 2492 |
xml.Escape(&b, []byte(s)) |
| 2493 |
|
| 2494 |
return b.String() |
| 2495 |
} |
| 2496 |
|
| 2497 |
type tee struct { |
| 2498 |
r io.Reader |
| 2499 |
w io.Writer |
| 2500 |
} |
| 2501 |
|
| 2502 |
func (t tee) Read(p []byte) (n int, err error) { |
| 2503 |
n, err = t.r.Read(p) |
| 2504 |
if n > 0 { |
| 2505 |
_, err = t.w.Write(p[0:n]) |
| 2506 |
if err != nil { |
| 2507 |
return n, err |
| 2508 |
} |
| 2509 |
_, err = t.w.Write([]byte("\n")) |
| 2510 |
} |
| 2511 |
return n, err |
| 2512 |
} |
| 2513 |
|
| 2514 |
func validUTF8(s string) string { |
| 2515 |
// Remove invalid code points. |
| 2516 |
s = strings.ToValidUTF8(s, "�") |
| 2517 |
reg := regexp.MustCompile(`[\x{0000}-\x{0008}\x{000B}\x{000C}\x{000E}-\x{001F}]`) |
| 2518 |
s = reg.ReplaceAllString(s, "�") |
| 2519 |
|
| 2520 |
return s |
| 2521 |
} |