go-sendxmpp/helpers.go

83 lines
1.8 KiB
Go
Raw Normal View History

2023-05-11 18:05:31 +00:00
// Copyright Martin Dosch.
2022-04-09 03:00:38 +00:00
// 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/rand"
2022-04-09 03:00:38 +00:00
"fmt"
"log"
"math/big"
2023-02-18 14:42:04 +00:00
"net/url"
"os"
"regexp"
"strings"
2022-04-09 03:00:38 +00:00
)
func validUTF8(s string) string {
// Remove invalid code points.
s = strings.ToValidUTF8(s, "<22>")
reg := regexp.MustCompile(`[\x{0000}-\x{0008}\x{000B}\x{000C}\x{000E}-\x{001F}]`)
s = reg.ReplaceAllString(s, "<22>")
return s
}
2023-02-18 15:24:46 +00:00
func validURI(s string) (*url.URL, error) {
2023-02-18 14:42:04 +00:00
// Check if URI is valid
2023-02-18 15:24:46 +00:00
uri, err := url.ParseRequestURI(s)
2023-06-06 20:09:59 +00:00
return uri, fmt.Errorf("validURI: %w", err)
2023-02-18 14:42:04 +00:00
}
func readFile(path string) (*bytes.Buffer, error) {
file, err := os.Open(path)
if err != nil {
2023-06-06 20:09:59 +00:00
return nil, fmt.Errorf("readFile: %w", err)
}
buffer := new(bytes.Buffer)
_, err = buffer.ReadFrom(file)
if err != nil {
2023-06-06 20:09:59 +00:00
return nil, fmt.Errorf("readFile: %w", err)
}
2023-06-04 13:15:31 +00:00
err = file.Close()
if err != nil {
2023-06-06 20:09:59 +00:00
fmt.Println("error while closing file:", err)
2023-06-04 13:15:31 +00:00
}
return buffer, 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)
}
2022-04-09 03:00:38 +00:00
func getID() string {
id := make([]byte, defaultIDBytes)
2022-05-02 14:13:00 +00:00
_, err := rand.Read(id)
if err != nil {
2022-04-09 03:00:38 +00:00
log.Fatal(err)
}
2022-05-02 14:13:00 +00:00
return fmt.Sprintf("%x-%x-%x", id[0:4], id[4:8], id[8:])
2022-04-09 03:00:38 +00:00
}
func getShortID() string {
id := make([]byte, defaultShortIDBytes)
2022-05-02 14:13:00 +00:00
_, err := rand.Read(id)
if err != nil {
log.Fatal(err)
}
2022-05-02 14:13:00 +00:00
return fmt.Sprintf("%x", id[0:4])
}