Debian Codegraph @

helpers.go

raw
1 // Copyright Martin Dosch.
2 // Use of this source code is governed by the BSD-2-clause
3 // license that can be found in the LICENSE file.
4
5 package main
6
7 import (
8 "bytes"
9 "crypto/aes"
10 "crypto/cipher"
11 "crypto/rand"
12 "encoding/gob"
13 "fmt"
14 "log"
15 "log/slog"
16 "math/big"
17 "net/url"
18 "os"
19 "regexp"
20 "runtime"
21 "strings"
22 "time"
23
24 "github.com/google/uuid" // BSD-3-Clause
25 "github.com/xmppo/go-xmpp" // BSD-3-Clause
26 "golang.org/x/crypto/scrypt" // BSD-3-Clause
27 )
28
29 type prettyLogger struct{}
30
31 func (pl prettyLogger) Write(bytes []byte) (int, error) {
32 return fmt.Print(time.Now().Format("2006-01-02 15:04:05 ") + string(bytes))
33 }
34
35 func validUTF8(s string) string {
36 // Remove invalid code points.
37 s = strings.ToValidUTF8(s, "�")
38 reg := regexp.MustCompile(`[\x{0000}-\x{0008}\x{000B}\x{000C}\x{000E}-\x{001F}]`)
39 s = reg.ReplaceAllString(s, "�")
40
41 return s
42 }
43
44 func validURI(s string) (*url.URL, error) {
45 // Check if URI is valid
46 uri, err := url.ParseRequestURI(s)
47 if err != nil {
48 return uri, fmt.Errorf("valid uri: %w", err)
49 }
50 return uri, nil
51 }
52
53 func readFile(path string) (*bytes.Buffer, error) {
54 // #nosec G304 -- path comes from the local system, it's no untrusted input from the network
55 file, err := os.Open(path)
56 if err != nil {
57 return nil, fmt.Errorf("read file: %w", err)
58 }
59 defer func() {
60 derr := file.Close()
61 if derr != nil {
62 slog.Warn("closing file failed", "error", derr)
63 }
64 }()
65 buffer := new(bytes.Buffer)
66 _, err = buffer.ReadFrom(file)
67 if err != nil {
68 return nil, fmt.Errorf("read file: %w", err)
69 }
70 return buffer, nil
71 }
72
73 func getFastData(jid string, password string, clientID string) (xmpp.Fast, error) {
74 folder := fsFriendlyJid(jid)
75 var fast xmpp.Fast
76 fastPath, err := getDataPath(folder, true)
77 if err != nil {
78 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache folder: %w", err)
79 }
80 fastFileLoc := fastPath + "fast.bin"
81 slog.Info("reading FAST data:", "file", fastFileLoc)
82 buf, err := readFile(fastFileLoc)
83 if err != nil {
84 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
85 }
86 decBuf := bytes.NewBuffer(buf.Bytes())
87 decoder := gob.NewDecoder(decBuf)
88 err = decoder.Decode(&fast)
89 if err != nil {
90 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
91 }
92 salt := []byte(clientID)
93 key, err := scrypt.Key([]byte(password), salt, 65536, 8, 1, 32)
94 if err != nil {
95 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to create aes key: %w", err)
96 }
97 c, err := aes.NewCipher([]byte(key))
98 if err != nil {
99 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
100 }
101 gcm, err := cipher.NewGCM(c)
102 if err != nil {
103 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
104 }
105 nonceSize := gcm.NonceSize()
106 cryptBuf := []byte(fast.Token)
107 nonce, cryptBuf := cryptBuf[:nonceSize], cryptBuf[nonceSize:]
108 tokenBuf, err := gcm.Open(nil, []byte(nonce), cryptBuf, nil)
109 if err != nil {
110 return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err)
111 }
112 fast.Token = string(tokenBuf)
113 return fast, nil
114 }
115
116 func deleteFastData(jid string) error {
117 folder := fsFriendlyJid(jid)
118 fastPath, err := getDataPath(folder, true)
119 if err != nil {
120 return fmt.Errorf("write fast data: failed to write fast cache file: %w", err)
121 }
122 fastFileLoc := fastPath + "fast.bin"
123 slog.Info("deleting FAST data:", "file", fastFileLoc)
124 return os.Remove(fastFileLoc)
125 }
126
127 func writeFastData(jid string, password string, clientID string, fast xmpp.Fast) error {
128 var encBuf bytes.Buffer
129 folder := fsFriendlyJid(jid)
130 fastPath, err := getDataPath(folder, true)
131 if err != nil {
132 return fmt.Errorf("write fast data: failed to write fast cache file: %w", err)
133 }
134 fastFileLoc := fastPath + "fast.bin"
135 slog.Info("writing FAST data:", "file", fastFileLoc)
136 salt := []byte(clientID)
137 key, err := scrypt.Key([]byte(password), salt, 65536, 8, 1, 32)
138 if err != nil {
139 return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
140 }
141 c, err := aes.NewCipher(key)
142 if err != nil {
143 return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
144 }
145 gcm, err := cipher.NewGCM(c)
146 if err != nil {
147 return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
148 }
149 nonce := make([]byte, gcm.NonceSize())
150 _, err = rand.Read(nonce)
151 if err != nil {
152 return fmt.Errorf("write fast data: failed to create aes cipher: %w", err)
153 }
154 buf := gcm.Seal(nonce, nonce, []byte(fast.Token), nil)
155 fast.Token = string(buf)
156 encode := gob.NewEncoder(&encBuf)
157 err = encode.Encode(fast)
158 if err != nil {
159 return fmt.Errorf("write fast data: failed to create fast token file: %w", err)
160 }
161 // #nosec G304 -- fast file loc comes from the local system, it's no untrusted input from the network
162 file, err := os.Create(fastFileLoc)
163 if err != nil {
164 return fmt.Errorf("write fast data: failed to create fast token file: %w", err)
165 }
166 defer func() {
167 derr := file.Close()
168 if derr != nil {
169 slog.Warn("closing file failed", "error", derr)
170 }
171 }()
172 if runtime.GOOS != "windows" {
173 _ = file.Chmod(os.FileMode(defaultFileRights))
174 } else {
175 _ = file.Chmod(os.FileMode(defaultFileRightsWin))
176 }
177 _, err = file.Write(encBuf.Bytes())
178 if err != nil {
179 return fmt.Errorf("write fast data: failed to write fast token file: %w", err)
180 }
181 return nil
182 }
183
184 func getClientID(jid string) (string, error) {
185 var clientID string
186 folder := fsFriendlyJid(jid)
187 clientIDLoc, err := getClientIDLoc(folder)
188 if err != nil {
189 return strError, err
190 }
191 buf, err := readFile(clientIDLoc)
192 if err != nil {
193 clientID = uuid.NewString()
194 // #nosec G304 -- client ID location comes from the local system,
195 // it's no untrusted input from the network
196 file, err := os.Create(clientIDLoc)
197 if err != nil {
198 return strEmpty, fmt.Errorf("get client id: failed to create clientid file: %w", err)
199 }
200 defer func() {
201 derr := file.Close()
202 if derr != nil {
203 slog.Warn("closing file failed", "error", derr)
204 }
205 }()
206 if runtime.GOOS != "windows" {
207 _ = file.Chmod(os.FileMode(defaultFileRights))
208 } else {
209 _ = file.Chmod(os.FileMode(defaultFileRightsWin))
210 }
211 _, err = file.Write([]byte(clientID))
212 if err != nil {
213 return strEmpty, fmt.Errorf("get client id: failed to write client id file: %w", err)
214 }
215 } else {
216 clientID = buf.String()
217 }
218 return clientID, nil
219 }
220
221 func getDataPath(folder string, create bool) (string, error) {
222 var err error
223 var homeDir, dataDir string
224 switch {
225 case os.Getenv("XDG_DATA_HOME") != "":
226 dataDir = os.Getenv("XDG_DATA_HOME")
227 slog.Info("using", "XDG_DATA_HOME", dataDir)
228 case os.Getenv("XDG_HOME") != "":
229 homeDir = os.Getenv("XDG_HOME")
230 slog.Info("using", "XDG_HOME", homeDir)
231 dataDir = homeDir + "/.local/share"
232 case os.Getenv("HOME") != "":
233 homeDir = os.Getenv("HOME")
234 slog.Info("using", "HOME", homeDir)
235 dataDir = homeDir + "/.local/share"
236 default:
237 homeDir, err = os.UserHomeDir()
238 if err != nil {
239 return strError, fmt.Errorf("get data path: failed to determine user dir: %w", err)
240 }
241 if homeDir == "" {
242 return strError, fmt.Errorf("get data path: received empty string for home directory")
243 }
244 slog.Info("using", "HOME", homeDir)
245 dataDir = homeDir + "/.local/share"
246 }
247 if folder != "" && !strings.HasSuffix(folder, "/") {
248 folder = fmt.Sprintf("%s/", folder)
249 }
250 dataDir = fmt.Sprintf("%s/go-sendxmpp/%s", dataDir, folder)
251 slog.Info("using data", "dir", dataDir)
252 // #nosec G703 -- data dir comes from the local system, it's no untrusted input from the network
253 _, err = os.Stat(dataDir)
254 if create && os.IsNotExist(err) {
255 // #nosec G703 -- data dir comes from the local system, it's no untrusted input from the network
256 err = os.MkdirAll(dataDir, defaultDirRights)
257 if err != nil {
258 return strError, fmt.Errorf("get data path: could not create folder: %w", err)
259 }
260 }
261 return dataDir, nil
262 }
263
264 func getClientIDLoc(folder string) (string, error) {
265 dataDir, err := getDataPath(folder, true)
266 if err != nil {
267 return strError, fmt.Errorf("get client id location: %w", err)
268 }
269 dataFile := dataDir + "clientid"
270 slog.Info("using client id", "location", dataDir)
271 return dataFile, nil
272 }
273
274 func getRpad(messageLength int) string {
275 rpadRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
276 length := defaultRpadMultiple - messageLength%defaultRpadMultiple
277 max := big.NewInt(int64(len(rpadRunes)))
278 rpad := make([]rune, length)
279 for i := range rpad {
280 randInt, err := rand.Int(rand.Reader, max)
281 if err != nil {
282 log.Fatal(err)
283 }
284 rpad[i] = rpadRunes[randInt.Int64()]
285 }
286 return string(rpad)
287 }
288
289 func getID() string {
290 id, err := uuid.NewV7()
291 if err != nil {
292 log.Fatal(err)
293 }
294 return id.String()
295 }
296
297 func getShortID() string {
298 return uuid.NewString()[:6]
299 }
300
301 func getSecret(alphabet string, length int, chunkSize int) (string, error) {
302 if length%chunkSize != 0 {
303 return strEmpty, fmt.Errorf("%d is not a multiple of %d", length, chunkSize)
304 }
305 secret := make([]rune, length+length/chunkSize-1)
306 secretRunes := []rune(alphabet)
307 delimiter := []rune("-")
308 max := big.NewInt(int64(len(secretRunes)))
309 chunks := length / chunkSize
310 secretLength := length + chunks - 1
311 count := 0
312 for range chunks {
313 for range chunkSize {
314 randInt, err := rand.Int(rand.Reader, max)
315 if err != nil {
316 return strEmpty, err
317 }
318 secret[count] = secretRunes[randInt.Int64()]
319 count++
320 }
321 if count >= secretLength {
322 break
323 }
324 secret[count] = delimiter[0]
325 count++
326 }
327 return string(secret), nil
328 }
329
330 // Remove @ and dots
331 func fsFriendlyJid(jid string) string {
332 jid = strings.ReplaceAll(jid, "@", "_at_")
333 return strings.ReplaceAll(jid, ".", "_")
334 }
335
336 func checkPEPsupport(jid string, client *xmpp.Client, iqc chan xmpp.IQ, drc chan xmpp.DiscoResult) error {
337 var pep bool
338 slog.Info("check pep support:", "target", jid)
339 discoResult, err := getDiscoInfo(client, drc, jid)
340 if err != nil {
341 return fmt.Errorf("check pep support: %w", err)
342 }
343 slog.Info("ox: check disco info reply for:", "type", "pep", "category", "pubsub")
344 for _, identity := range discoResult.Identities {
345 if identity.Category == "pubsub" && identity.Type == "pep" {
346 pep = true
347 }
348 }
349 if !pep {
350 return fmt.Errorf("no pep support")
351 }
352 return nil
353 }