summaryrefslogtreecommitdiff
path: root/xmpp.go
blob: f1f0d22dd05717986680503c205524e5cad55844 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/xml"
	"log"
	"strings"
)

const (
	StreamCloser = `</stream:stream>`
)

type XmppEvent uint8

const (
	XmppDisconnect XmppEvent = iota
	XmppConnect
)

func (l *Limox) xmpp(jid string, pwd string) {
	log.Printf("JID: '%s' PWD: '%s'\n", jid, pwd)

	domain := domainpart(jid)
	log.Printf("Domain: '%s'\n", domain)

	roots, err := x509.SystemCertPool()
	if err != nil {
		l.XmppEvents <- err
		return
	}

	conn, err := tls.Dial("tcp", domain+":"+"5223", &tls.Config{RootCAs: roots})
	if err != nil {
		l.XmppEvents <- err
		return
	}
	l.XmppEvents <- XmppConnect

	sendStreamStart(conn, jid)

	var closing bool = false
	for {
		ev := <-l.GuiEvents
		switch ev {
		case Disconnect:
			closing = true
		default:
			log.Fatalf("Unknown GuiEvent '%d'!\n", ev)
		}
		if closing {
			break
		}
	}

	log.Print("C: " + StreamCloser)
	conn.Write([]byte(StreamCloser))
	conn.Close()
	l.XmppEvents <- XmppDisconnect
}

type StreamInit struct {
	XMLName     xml.Name `xml:"stream:stream"`
	From        string   `xml:"from,attr"`
	To          string   `xml:"to,attr"`
	Version     string   `xml:"version,attr"`
	XmlLang     string   `xml:"xml:lang,attr"`
	Xmlns       string   `xml:"xmlns,attr"`
	XmlnsStream string   `xml:"xmlns:stream,attr"`
}

func sendStreamStart(t *tls.Conn, jid string) {
	data := StreamInit{
		From:        jid,
		To:          domainpart(jid),
		Version:     "1.0",
		XmlLang:     "en",
		Xmlns:       "jabber:client",
		XmlnsStream: "http://etherx.jabber.org/streams",
	}

	serialized, err := xml.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	str := strings.TrimSuffix(string(serialized), StreamCloser)
	log.Print("C: " + str)

	t.Write([]byte(serialized))
}

// domainpart extracts the domain name from a JID / XMPP address. See
// https://datatracker.ietf.org/doc/html/rfc7622#section-3.2 for details.
func domainpart(jid string) string {
	list := []rune(jid)

	for i, v := range list {
		if v == '/' {
			list = list[:i]
			break
		}
	}

	for i, v := range list {
		if v == '@' {
			list = list[i+1:]
			break
		}
	}

	return string(list)
}