utils

package
v0.0.0-...-7c04fb6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const AlphaNum = "abcdefghijklmnopqrstuvwxyz0123456789"
View Source
const AlphaNumCaseSymbol = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_!?§$%&/()=*+#,;.:<>|°^"
View Source
const AlphaNumDash = "abcdefghijklmnopqrstuvwxyz0123456789-"
View Source
const NetworkSizeSkip = 327168 // Networks larger than this will be dropped
View Source
const NetworkSizeSplit = 2048 // Networks larger than this will be split into smaller subnets
View Source
const ReconnectInterval = time.Second * 5

Variables

View Source
var ErrNotifierShuttingDown = fmt.Errorf("notifier shutting down")
View Source
var ErrRpcCompatibility = fmt.Errorf("RPC client incompatible") // Error indicating that the RPC client is incompatible and needs to be updated
View Source
var ErrRpcConnectivity = fmt.Errorf("RPC server not available") // Error indicating connectivity error which might be gone already or temporary
View Source
var ErrRpcGeneric = fmt.Errorf("RPC endpoint not available") // Generic error returned by the RPC client, which may not contain sensitive details

Functions

func CheckPasswordHash

func CheckPasswordHash(hashedPwd string, plainPwd string) error

CheckPasswordHash compares a password hash generated by CreatePasswordHash() with a given plaintext password. Returns nil if password matches given hash.

func CountIpsInInput

func CountIpsInInput(subnet string) (uint, error)

CountIpsInInput calculates the amount of possible IP addresses within a network range

func CreatePasswordHash

func CreatePasswordHash(pwd string) (string, error)

CreatePasswordHash creates a salted password hash from a given password

func GenerateToken

func GenerateToken(letters string, length int) (string, error)

GenerateToken generates a random string based allowed letters and a given length

func GetLocalIp

func GetLocalIp() (string, error)

GetLocalIp retrieves the IP address of the local default interface

func GetOutboundIP

func GetOutboundIP() string

GetOutboundIP gets preferred outbound ip of this machine by initializing a logical (fake) connection and reading the local address from it. By using UDP, the sample target does not actually need to exist, because no TCP handshake is required. Also the port does not matter.

func HashScramSha256Postgres

func HashScramSha256Postgres(password string) (string, error)

HashScramSha256Postgres generates a Scram-Sha-256 hash in the format used by Postgres for storing user passwords

func IntContained

func IntContained(candidate int, slices ...[]int) bool

IntContained checks whether a given int value is contained within one or multiple given slices

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError detects whether a given error is one of the many types and sources of connectivity errors

func IsPlausibleEmail

func IsPlausibleEmail(mail string) bool

IsPlausibleEmail validates whether a given string is a plausible e-mail address

func IsRpcConnectionError

func IsRpcConnectionError(err error) bool

IsRpcConnectionError validates a given error and checks whether it is a kind of error indicating connectivity issues

func JoinInt

func JoinInt(ints []int, delimiter string) string

JoinInt converts a slice of ints into strings and concatenates them using the given delimiter

func JoinUint64

func JoinUint64(uints []uint64, delimiter string) string

JoinUint64 converts a slice of int64's into strings and concatenates them using the given delimiter

func JoinWeekdays

func JoinWeekdays(days []time.Weekday, delimiter string) string

JoinWeekdays converts weekday integers into string and concatenates them using the given delimiter

func JsonToStruct

func JsonToStruct(jsonData interface{}, jsonStruct interface{}) error

JsonToStruct parses JSON data (e.g. map[string]interface) and populates a referenced struct. ATTENTION: The JSON keys must either match the struct attribute names or the JSON struct tags to fill!

func RemoveFromSlice

func RemoveFromSlice(list []string, s string) []string

RemoveFromSlice removes a given element (and potential duplicates) from a slice and returns a new slice

func ServeRpc

func ServeRpc(
	logger scanUtils.Logger,
	ctx context.Context,
	name string,
	certFilePath string,
	keyFilePath string,
	listenAddress string,
) error

ServeRpc loops to accept and process RPC connections until the passed context is terminated

func SplitNetworkIpV4

func SplitNetworkIpV4(network string, targetSize uint32) ([]string, error)

SplitNetworkIpV4 splits a larger network range into smaller subnets of given size. Returns original input if it is already smaller than the given target size.

func SslSocket

func SslSocket(listenAddress string, certFile string, keyFile string) (net.Listener, error)

SslSocket initializes an SSL socket listening for RPC connections

func TimeInRange

func TimeInRange(candidate time.Time, start time.Time, end time.Time) bool

TimeInRange decides whether a given time is between two clocks, ignoring dates.

func TimezonesBetween

func TimezonesBetween(startClock string, endClock string, invalidDays []time.Weekday) [][]int

TimezonesBetween calculates timezones that have a current time between earliest and latest. Each slice returned represents a from-to timezone range. Returns one timezone range if the time spawn does not cross midnight, or two otherwise. Timezone ranges are better than a simple list of timezones, because they also cover potential/rare half or three quarter step time zones, such as, 11.5. Returns the complete timezone range if start clock equals end clock.

func TlsConfigFactory

func TlsConfigFactory() *tls.Config

TlsConfigFactory returns a secure SSL connection configuration

func TlsConfigFactoryPinned

func TlsConfigFactoryPinned(publicKeyPath string) (*tls.Config, error)

TlsConfigFactoryPinned returns an SSL client configuration that is verified by fingerprint matching against a provided public key file. This way a secure SSL connection can be established without relying on PKI.

func ToSlice

func ToSlice(s, sep string) []string

ToSlice splits a string by separator. In contrast to Golang's own split function, this one returns an empty slice if the input string was empty. Golang's original function would return a slice with one entry being an empty string.

func ToValidUtf8String

func ToValidUtf8String(b []byte) string

ToValidUtf8String returns a valid utf-8 string by replacing all invalid byte sequences with a hardcoded replacement character. Additionally, it gets rid of trailing null bytes and replaces none-trailing null bytes.

func TrimToUpper

func TrimToUpper(slice []string) []string

TrimToUpper converts slice elements to upper case and trim whitespaces

func Uint64Contained

func Uint64Contained(candidate uint64, slices ...[]uint64) bool

Uint64Contained checks whether a given int64 value is contained within one or multiple given slices

func UniqueInts

func UniqueInts(elements []int) []int

UniqueInts gets rid of redundant elements

func UniqueWeekdays

func UniqueWeekdays(elements []time.Weekday) []time.Weekday

UniqueWeekdays gets rid of redundant elements

func ValidPassword

func ValidPassword(
	password string,
	minLength int,
	requiresLower bool,
	requiresUpper bool,
	requiresNumber bool,
	requiresSymbol bool,
) bool

ValidPassword checks whether a given string matches password requirements

func ValidUtf8String

func ValidUtf8String(str string) string

ValidUtf8String returns a valid utf-8 string by replacing all invalid byte sequences with a hardcoded replacement character. Additionally, it gets rid of trailing null bytes and replaces none-trailing null bytes.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewRpcClient

func NewRpcClient(
	server string,
	serverSsl bool,
	serverCertPath string,
) *Client

NewRpcClient prepares an RPC client struct providing connectivity to an RPC server.

func (*Client) Call

func (c *Client) Call(logger scanUtils.Logger, rpcEndpoint string, rpcArgs interface{}, rpcReply interface{}) error

Call executes an RPC call and writes back the response into rpcReply. In case of a connection issues, a re-connection loop is started in the background and an error returned. Users can subscribe to and wait for a re-connection notification (via Established()), or just retry later.

This function returns:

  • nil, if everything went fine
  • ErrRpcConnectivity, if something was wrong with the RPC connection
  • rpc.ServerError, if the RPC request failed. Unfortunately, net/rpc converts all errors into this type.

func (*Client) Connect

func (c *Client) Connect(logger scanUtils.Logger, continueBackground bool) bool

Connect tries to establish a connection (if no other goroutine does yet). Returns boolean indicating whether a connection could be established. Optionally, after the first try, the connection attempt can be continued in the background sending a notification to current subscribers on success. Subscribe via "Established()".

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect disconnects an RPC connection

func (*Client) Established

func (c *Client) Established() <-chan struct{}

Established returns a notification channel triggering when an RPC connection was (re)established. This can be used to block after connections issues until it re-connection. The channel will not trigger, if a connection is currently established and working!

type Gracy

type Gracy struct {
	// contains filtered or unexported fields
}

Gracy handles our graceful shutdown procedure. Fortunately, Gracy is more capable in doing so then Golang itself. Unfortunately, Golang does not execute registered deferred statements after an interrupt. Instead, it aborts affected Goroutines right away and jumps into the signal handling function. So, Gracy will keep track of everything you want to clean up instead.

func NewGracy

func NewGracy() *Gracy

NewGracy yields a fresh Gracy keeping track of registered shutdown functions.

func (*Gracy) Promote

func (g *Gracy) Promote()

Promote assigns Gracy as our default interrupt handler. In her duty, she will listen for interrupts and run all previously registered shutdown functions.

func (*Gracy) Register

func (g *Gracy) Register(shutdownFn func())

Register registers a function to be executed on shutdown. Comparable to the defer statement.

func (*Gracy) Shutdown

func (g *Gracy) Shutdown()

Shutdown executes all registered shutdown functions sequentially in reverse order. Comparable to the execution of deferred statements.

type Json

type Json json.RawMessage

Json implements a scanner valuer interface for json.RawMessage as required by GORM to handle JSON data types. The JSON byte stream can be scanned into a given JSON struct for processing. https://gorm.io/docs/data_types.html

func (*Json) Scan

func (j *Json) Scan(value interface{}) error

Scan scan value into Jsonb, implements sql.Scanner interface

func (Json) Value

func (j Json) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type JsonMap

type JsonMap map[string]interface{}

JsonMap is a generic helper type to allow reading writing dynamic map structures. The map's value types can be arbitrary and arbitrarily deep. However, to work with the data after unmarshalling, the values must be known and casted into their real data types. https://www.alexedwards.net/blog/using-postgresql-jsonb

func (*JsonMap) Scan

func (a *JsonMap) Scan(value interface{}) error

func (JsonMap) Value

func (a JsonMap) Value() (driver.Value, error)

type Notifier

type Notifier struct {
	// contains filtered or unexported fields
}

Notifier allows to send a notification message to all current subscribers. Subscribers must subscribe *again*, if after each notification they received. In order to give them some time to subscribe again, the Notifier is initialized withe a certain broadcast interval. It will collect messages until the interval is triggered. Messages can be of any type.

func NewNotifier

func NewNotifier(broadcastInterval time.Duration, fnSkip func(interface{}, interface{}) bool) *Notifier

NewNotifier initializes a new notifier that can be subscribed to. 'fnSkip' is a function that can be used to decide whether a new value shall be added to the list of messages to be broadcast. E.g. if you want to filter duplicates.

func (*Notifier) Receive

func (b *Notifier) Receive() ([]interface{}, error)

func (*Notifier) Send

func (b *Notifier) Send(msg interface{})

func (*Notifier) Shutdown

func (b *Notifier) Shutdown()

Shutdown shuts down the notifier and waits until all final notifications are fully processed.

type Smtp

type Smtp struct {

	// SMTP settings
	Server     string         `json:"server"`
	Port       uint16         `json:"port"`
	Username   string         `json:"username"`
	Password   string         `json:"password"`
	Subject    string         `json:"subject"`
	Sender     mail.Address   `json:"sender"`
	Recipients []mail.Address `json:"recipients"`

	// Security settings
	OpensslPath         string   `json:"openssl_path"`
	SignatureCertPath   string   `json:"signature_cert"`  // Sender certificate for e-mail signature
	SignatureCert       []byte   `json:"-"`               // Loaded sender certificate for e-mail signature
	SignatureKeyPath    string   `json:"signature_key"`   // Sender private key for e-mail signature
	SignatureKey        []byte   `json:"-"`               // Loaded sender private key for e-mail signature
	EncryptionCertPaths []string `json:"recipient_certs"` // Encryption certificates for the recipients above
	EncryptionCerts     [][]byte `json:"-"`               // Loaded encryption certificates for the recipients above
	TempDir             string   `json:"temp_dir"`
}

func (*Smtp) UnmarshalJSON

func (s *Smtp) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a JSON file, validates values and populates the configuration struct

type SystemData

type SystemData struct {
	Platform        string  `json:"platform"`
	PlatformFamily  string  `json:"platform_family"`
	PlatformVersion string  `json:"platform_version"`
	CpuRate         float64 `json:"cpu_rate"`
	MemoryRate      float64 `json:"memory_rate"`
}

type SystemMonitor

type SystemMonitor struct {
	// contains filtered or unexported fields
}

func NewSystemMonitor

func NewSystemMonitor(ctxParent context.Context) *SystemMonitor

NewSystemMonitor initializes a new system resources monitor, regularly measuring the system utilization.

func (*SystemMonitor) Get

func (sm *SystemMonitor) Get() SystemData

Get retrieves the last known system usage data

func (*SystemMonitor) Run

func (sm *SystemMonitor) Run(interval time.Duration)

Run launches the system utilization monitor

func (*SystemMonitor) Shutdown

func (sm *SystemMonitor) Shutdown()

Shutdown terminates the system usage monitor

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL