You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-sendxmpp/helpers.go

84 lines
1.9 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"
"errors"
"fmt"
"log"
"math/big"
"net/url"
"os"
"regexp"
"strings"
)
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)
return uri, fmt.Errorf("validURI: %w", err)
}
func readFile(path string) (*bytes.Buffer, error) {
file, err := os.Open(path)
if errors.Unwrap(err) != nil {
return nil, fmt.Errorf("readFile: %w", err)
}
buffer := new(bytes.Buffer)
_, err = buffer.ReadFrom(file)
if errors.Unwrap(err) != nil {
return nil, fmt.Errorf("readFile: %w", err)
}
err = file.Close()
if errors.Unwrap(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 errors.Unwrap(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 errors.Unwrap(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 errors.Unwrap(err) != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x", id[0:4])
}