File: helpers.go

package info (click to toggle)
go-sendxmpp 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 332 kB
  • sloc: makefile: 11
file content (280 lines) | stat: -rw-r--r-- 8,070 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/gob"
	"fmt"
	"log"
	"log/slog"
	"math/big"
	"net/url"
	"os"
	"regexp"
	"runtime"
	"strings"
	"time"

	"github.com/google/uuid"     // BSD-3-Clause
	"github.com/xmppo/go-xmpp"   // BSD-3-Clause
	"golang.org/x/crypto/scrypt" // BSD-3-Clause
)

type prettyLogger struct{}

func (pl prettyLogger) Write(bytes []byte) (int, error) {
	return fmt.Print(time.Now().Format("2006-01-02 15:04:05 ") + string(bytes))
}

func validUTF8(s string) string {
	// Remove invalid code points.
	s = strings.ToValidUTF8(s, "�")
	reg := regexp.MustCompile(`[\x{0000}-\x{0008}\x{000B}\x{000C}\x{000E}-\x{001F}]`)
	s = reg.ReplaceAllString(s, "�")

	return s
}

func validURI(s string) (*url.URL, error) {
	// Check if URI is valid
	uri, err := url.ParseRequestURI(s)
	if err != nil {
		return uri, fmt.Errorf("valid uri: %w", err)
	}
	return uri, nil
}

func readFile(path string) (*bytes.Buffer, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("read file: %w", err)
	}
	defer file.Close()
	buffer := new(bytes.Buffer)
	_, err = buffer.ReadFrom(file)
	if err != nil {
		return nil, fmt.Errorf("read file: %w", err)
	}
	return buffer, nil
}

func getFastData(jid string, password string) (xmpp.Fast, error) {
	folder := fsFriendlyJid(jid)
	var fast xmpp.Fast
	fastPath, err := getDataPath(folder, true)
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache folder: %w", err)
	}
	fastFileLoc := fastPath + "fast.bin"
	slog.Info("reading FAST data:", "file", fastFileLoc)
	buf, err := readFile(fastFileLoc)
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
	}
	decBuf := bytes.NewBuffer(buf.Bytes())
	decoder := gob.NewDecoder(decBuf)
	err = decoder.Decode(&fast)
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
	}
	salt := make([]byte, 32)
	key, err := scrypt.Key([]byte(password), salt, 32768, 8, 1, 32)
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to create aes key: %w", err)
	}
	c, err := aes.NewCipher([]byte(key))
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
	}
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
	}
	nonceSize := gcm.NonceSize()
	cryptBuf := []byte(fast.Token)
	nonce, cryptBuf := cryptBuf[:nonceSize], cryptBuf[nonceSize:]
	tokenBuf, err := gcm.Open(nil, []byte(nonce), cryptBuf, nil)
	if err != nil {
		return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
	}
	fast.Token = string(tokenBuf)
	return fast, nil
}

func deleteFastData(jid string) error {
	folder := fsFriendlyJid(jid)
	fastPath, err := getDataPath(folder, true)
	if err != nil {
		return fmt.Errorf("write fast data: failed to write fast cache file: %w", err)
	}
	fastFileLoc := fastPath + "fast.bin"
	slog.Info("deleting FAST data:", "file", fastFileLoc)
	return os.Remove(fastFileLoc)
}

func writeFastData(jid string, password string, fast xmpp.Fast) error {
	var encBuf bytes.Buffer
	folder := fsFriendlyJid(jid)
	fastPath, err := getDataPath(folder, true)
	if err != nil {
		return fmt.Errorf("write fast data: failed to write fast cache file: %w", err)
	}
	fastFileLoc := fastPath + "fast.bin"
	slog.Info("writing FAST data:", "file", fastFileLoc)
	salt := make([]byte, 32)
	key, err := scrypt.Key([]byte(password), salt, 32768, 8, 1, 32)
	if err != nil {
		return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
	}
	c, err := aes.NewCipher(key)
	if err != nil {
		return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
	}
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
	}
	nonce := make([]byte, gcm.NonceSize())
	_, err = rand.Read(nonce)
	if err != nil {
		return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
	}
	buf := gcm.Seal(nonce, nonce, []byte(fast.Token), nil)
	fast.Token = string(buf)
	encode := gob.NewEncoder(&encBuf)
	err = encode.Encode(fast)
	if err != nil {
		return fmt.Errorf("write fast data: failed to create fast token file: %w", err)
	}
	file, err := os.Create(fastFileLoc)
	if err != nil {
		return fmt.Errorf("write fast data: failed to create fast token file: %w", err)
	}
	defer file.Close()
	if runtime.GOOS != "windows" {
		_ = file.Chmod(os.FileMode(defaultFileRights))
	} else {
		_ = file.Chmod(os.FileMode(defaultFileRightsWin))
	}
	_, err = file.Write(encBuf.Bytes())
	if err != nil {
		return fmt.Errorf("write fast data: failed to write fast token file: %w", err)
	}
	return nil
}

func getClientID(jid string) (string, error) {
	var clientID string
	folder := fsFriendlyJid(jid)
	clientIDLoc, err := getClientIDLoc(folder)
	if err != nil {
		return strError, err
	}
	buf, err := readFile(clientIDLoc)
	if err != nil {
		clientID = uuid.NewString()
		file, err := os.Create(clientIDLoc)
		if err != nil {
			return strEmpty, fmt.Errorf("get client id: failed to create clientid file: %w", err)
		}
		defer file.Close()
		if runtime.GOOS != "windows" {
			_ = file.Chmod(os.FileMode(defaultFileRights))
		} else {
			_ = file.Chmod(os.FileMode(defaultFileRightsWin))
		}
		_, err = file.Write([]byte(clientID))
		if err != nil {
			return strEmpty, fmt.Errorf("get client id: failed to write client id file: %w", err)
		}
	} else {
		clientID = buf.String()
	}
	return clientID, nil
}

func getDataPath(folder string, create bool) (string, error) {
	var err error
	var homeDir, dataDir string
	switch {
	case os.Getenv("$XDG_DATA_HOME") != "":
		dataDir = os.Getenv("$XDG_DATA_HOME")
		slog.Info("using", "XDG_DATA_HOME", dataDir)
	case os.Getenv("$XDG_HOME") != "":
		homeDir = os.Getenv("$XDG_HOME")
		slog.Info("using", "XDG_HOME", homeDir)
		dataDir = homeDir + "/.local/share"
	case os.Getenv("$HOME") != "":
		homeDir = os.Getenv("$HOME")
		slog.Info("using", "HOME", homeDir)
		dataDir = homeDir + "/.local/share"
	default:
		homeDir, err = os.UserHomeDir()
		if err != nil {
			return strError, fmt.Errorf("get data path: failed to determine user dir: %w", err)
		}
		if homeDir == "" {
			return strError, fmt.Errorf("get data path: received empty string for home directory")
		}
		slog.Info("using", "HOME", homeDir)
		dataDir = homeDir + "/.local/share"
	}
	if folder != "" && !strings.HasSuffix(folder, "/") {
		folder = fmt.Sprintf("%s/", folder)
	}
	dataDir = fmt.Sprintf("%s/go-sendxmpp/%s", dataDir, folder)
	slog.Info("using data", "dir", dataDir)
	_, err = os.Stat(dataDir)
	if create && os.IsNotExist(err) {
		err = os.MkdirAll(dataDir, defaultDirRights)
		if err != nil {
			return strError, fmt.Errorf("get data path: could not create folder: %w", err)
		}
	}
	return dataDir, nil
}

func getClientIDLoc(folder string) (string, error) {
	dataDir, err := getDataPath(folder, true)
	if err != nil {
		return strError, fmt.Errorf("get client id location: %w", err)
	}
	dataFile := dataDir + "clientid"
	slog.Info("using client id", "location", dataDir)
	return dataFile, nil
}

func getRpad(messageLength int) string {
	rpadRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	length := defaultRpadMultiple - messageLength%defaultRpadMultiple
	max := big.NewInt(int64(len(rpadRunes)))
	rpad := make([]rune, length)
	for i := range rpad {
		randInt, err := rand.Int(rand.Reader, max)
		if err != nil {
			log.Fatal(err)
		}
		rpad[i] = rpadRunes[randInt.Int64()]
	}
	return string(rpad)
}

func getID() string {
	return uuid.NewString()
}

func getShortID() string {
	return uuid.NewString()[:6]
}

// Remove @ and dots
func fsFriendlyJid(jid string) string {
	jid = strings.ReplaceAll(jid, "@", "_at_")
	return strings.ReplaceAll(jid, ".", "_")
}