mirror of
https://salsa.debian.org/mdosch/go-sendxmpp
synced 2024-11-15 00:15:10 +00:00
83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
// 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/rand"
|
||
"fmt"
|
||
"log"
|
||
"math/big"
|
||
"net/url"
|
||
"os"
|
||
"regexp"
|
||
"strings"
|
||
)
|
||
|
||
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
|
||
}
|
||
|
||
func validURI(s string) (*url.URL, error) {
|
||
// Check if URI is valid
|
||
uri, err := url.ParseRequestURI(s)
|
||
return uri, fmt.Errorf("validURI: %w", err)
|
||
}
|
||
|
||
func readFile(path string) (*bytes.Buffer, error) {
|
||
file, err := os.Open(path)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("readFile: %w", err)
|
||
}
|
||
buffer := new(bytes.Buffer)
|
||
_, err = buffer.ReadFrom(file)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("readFile: %w", err)
|
||
}
|
||
err = file.Close()
|
||
if err != nil {
|
||
fmt.Println("error while closing file:", err)
|
||
}
|
||
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)
|
||
}
|
||
|
||
func getID() string {
|
||
id := make([]byte, defaultIDBytes)
|
||
_, err := rand.Read(id)
|
||
if err != nil {
|
||
log.Fatal(err)
|
||
}
|
||
return fmt.Sprintf("%x-%x-%x", id[0:4], id[4:8], id[8:])
|
||
}
|
||
|
||
func getShortID() string {
|
||
id := make([]byte, defaultShortIDBytes)
|
||
_, err := rand.Read(id)
|
||
if err != nil {
|
||
log.Fatal(err)
|
||
}
|
||
return fmt.Sprintf("%x", id[0:4])
|
||
}
|