utils

package
v0.0.0-...-8975b5b Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2025 License: MPL-2.0 Imports: 36 Imported by: 0

Documentation

Overview

* * (C) 2023 Ford Motor Company * (C) 2021 Geotab * * All files and artifacts in the repository at https://github.com/covesa/vissr * are licensed under the provisions of the license provided by the LICENSE file in this repository. * *

* * (C) 2021 Geotab * * All files and artifacts in the repository at https://github.com/covesa/vissr * are licensed under the provisions of the license provided by the LICENSE file in this repository. * *

Index

Constants

View Source
const (
	SENSOR    = "sensor"
	ACTUATOR  = "actuator"
	ATTRIBUTE = "attribute"
	BRANCH    = "branch"
	STRUCT    = "struct"
	PROPERTY  = "property"
	PROCEDURE = "procedure"
	IOSTRUCT  = "iostruct"
)
View Source
const IpEnvVarName = "GEN2MODULEIP"
View Source
const IpModel = 0 // IpModel = [0,1,2] = [localhost,extIP,envVarIP]
View Source
const MAXFOUNDNODES = 1500
View Source
const UIDLEN = 4

Variables

View Source
var (
	//    Trace   *log.Logger
	Info    *logrus.Logger
	Warning *logrus.Logger
	Error   *logrus.Logger
)
View Source
var ErrorInfoList [8]ErrorInformation = [8]ErrorInformation{
	{"400", "bad_request", "The request is malformed."},
	{"400", "invalid_data", "Data present in the request is invalid."},
	{"401", "expired_token", "Access token has expired."},
	{"401", "invalid_token", "Access token is invalid."},
	{"401", "missing_token", "Access token is missing."},
	{"403", "forbidden_request", "The server refuses to carry out the request."},
	{"404", "unavailable_data", "The requested data was not found."},
	{"503", "service_unavailable", "The server is temporarily unable to handle the request."}}
View Source
var HostIP string
View Source
var Logfile *os.File

const LOG_FILE = "servercore-log.txt"

View Source
var TrSecConfigPath string = "../transport_sec/" // relative path to the directory containing the transportSec.json file
View Source
var Upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}
View Source
var WsClientIndexList = []bool{
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
	true,
}

len of WsClientIndexList must match the number of select cases in wsMgr

Functions

func AddKeyValue

func AddKeyValue(message string, key string, value string) string

func AddRoutingForwardRequest

func AddRoutingForwardRequest(reqMessage string, mgrId int, clientId int, transportMgrChan chan string)

func CertOptToInt

func CertOptToInt(serverCertOpt string) int

func CloseLogFile

func CloseLogFile()

func CreatePathListFile

func CreatePathListFile(pListPath string)

func ExportKeyPair

func ExportKeyPair(privKey crypto.PrivateKey, privFileName string, pubFileName string) error

Export KeyPair to files named as given (ECDSA and RSA supported, pointers to privKey must be given)

func ExtractFromRequest

func ExtractFromRequest(request string, parameterKey string) string

func ExtractFromToken

func ExtractFromToken(token string, claim string) string

func ExtractRootName

func ExtractRootName(path string) string

func ExtractSubscriptionId

func ExtractSubscriptionId(jsonSubResponse string) string

func FileExists

func FileExists(filename string) bool

func FinalizeMessage

func FinalizeMessage(responseMap map[string]interface{}) string

func GenEcdsaKey

func GenEcdsaKey(curve elliptic.Curve, privKey **ecdsa.PrivateKey) error

Generates ECDSA private Key using given curve

func GenRsaKey

func GenRsaKey(size int, privKey **rsa.PrivateKey) error

********* KEY GENERATION *********** Generates RSA private key of given size

func GenerateHmac

func GenerateHmac(input string, key string) string

func GetFirstDotIndex

func GetFirstDotIndex(path string) int

func GetLastDotSegment

func GetLastDotSegment(path string) string

func GetMaxValidation

func GetMaxValidation(newValidation int, currentMaxValidation int) int

func GetModelIP

func GetModelIP(ipModel int) string

func GetRequestJsonToPb

func GetRequestJsonToPb(vssGetReq string) *pb.GetRequestMessage

func GetRequestPbToJson

func GetRequestPbToJson(pbGetReq *pb.GetRequestMessage) string

func GetResponseJsonToPb

func GetResponseJsonToPb(vssGetResp string) *pb.GetResponseMessage

func GetResponsePbToJson

func GetResponsePbToJson(pbGetResp *pb.GetResponseMessage) string

func GetRfcTime

func GetRfcTime() string

func GetServerIP

func GetServerIP() string

func GetTLSConfig

func GetTLSConfig(host string, caCertFile string, certOpt tls.ClientAuthType, serverCert *tls.Certificate) *tls.Config

Obtains a tls.Config struct, giving support to https.listenandservetls

func GetTimeInMilliSecs

func GetTimeInMilliSecs() string

func GetUdsConn

func GetUdsConn(path string, connectionName string) net.Conn

func GetUdsPath

func GetUdsPath(path string, connectionName string) string

func ImportEcdsaKey

func ImportEcdsaKey(filename string, privKey **ecdsa.PrivateKey) error

Gets ecdsa private key from pem file

func ImportRsaKey

func ImportRsaKey(filename string, privKey **rsa.PrivateKey) error

********* PEM KEY IMPORT / EXPORT *********** Gets rsa private key from pem file

func ImportRsaPubKey

func ImportRsaPubKey(filename string, pubKey **rsa.PublicKey) error

Gets rsa public key from pem file

func InitForest

func InitForest(himPath string) bool

func InitLog

func InitLog(filename string, logdir string, logFile bool, logLevel string)

func IsBoolean

func IsBoolean(value string) bool

func IsNumber

func IsNumber(value string) bool

func JsonRecursiveMarshall

func JsonRecursiveMarshall(key string, value string, jplain *string)

Gets Json string (or nothing) and adds received key and value, if it doesnt receive a value or key, it does nothing

func JsonSchemaInit

func JsonSchemaInit()

func JsonSchemaValidate

func JsonSchemaValidate(request string) string

func JsonToProtobuf

func JsonToProtobuf(jsonMessage string) []byte

func MapRequest

func MapRequest(request string, rMap *map[string]interface{}) int

func NextQuoteMark

func NextQuoteMark(message []byte, offset int) int

func PathToUrl

func PathToUrl(path string) string

func PemDecodeECDSA

func PemDecodeECDSA(pemKey string, privKey **ecdsa.PrivateKey) error

Gets ECDSA key in pem format and decodes it into ecdsa.PrivateKey

func PemDecodeRSA

func PemDecodeRSA(pemKey string, privKey **rsa.PrivateKey) error

********* KEY ENCODING / DECODING *********** Gets rsa key in pem format and decodes it into rsa.privatekey

func PemDecodeRSAPub

func PemDecodeRSAPub(pemKey string, pubKey **rsa.PublicKey) error

Gets rsa pub key in pem format and decodes it into rsa.publickey

func PemEncodeECDSA

func PemEncodeECDSA(privKey *ecdsa.PrivateKey) (strPrivKey string, strPubKey string, err error)

Returns ECDSA Keys as string in PEM format

func PemEncodeRSA

func PemEncodeRSA(privKey *rsa.PrivateKey) (strPrivKey string, strPubKey string, err error)

Returns RSA Keys as string in PEM format

func PopulateDefault

func PopulateDefault()

func ProtobufToJson

func ProtobufToJson(serialisedMessage []byte) string

func ReadTransportSecConfig

func ReadTransportSecConfig()

Initializes TransportSec Variables

func RemoveInternalData

func RemoveInternalData(response string) (string, int)

func ReturnWsClientIndex

func ReturnWsClientIndex(index int)

func SetErrorResponse

func SetErrorResponse(reqMap map[string]interface{}, errRespMap map[string]interface{}, errorListIndex int, altErrorMessage string)

func SetRequestJsonToPb

func SetRequestJsonToPb(vssSetReq string) *pb.SetRequestMessage

func SetRequestPbToJson

func SetRequestPbToJson(pbSetReq *pb.SetRequestMessage) string

func SetResponseJsonToPb

func SetResponseJsonToPb(vssSetResp string) *pb.SetResponseMessage

func SetResponsePbToJson

func SetResponsePbToJson(pbSetResp *pb.SetResponseMessage) string

func SubscribeRequestJsonToPb

func SubscribeRequestJsonToPb(vssSubscribeReq string) *pb.SubscribeRequestMessage

func SubscribeRequestPbToJson

func SubscribeRequestPbToJson(pbSubscribeReq *pb.SubscribeRequestMessage) string

func SubscribeStreamJsonToPb

func SubscribeStreamJsonToPb(vssSubscribeStream string) *pb.SubscribeStreamMessage

func SubscribeStreamPbToJson

func SubscribeStreamPbToJson(pbSubscribeResp *pb.SubscribeStreamMessage) string

func TrimLogFile

func TrimLogFile(logFile *os.File)

* * The log file is trimmed to 20% of its size when exceeding 10MB. *

func UnpackFilter

func UnpackFilter(filter interface{}, fList *[]FilterObject)

func UnsubscribeRequestJsonToPb

func UnsubscribeRequestJsonToPb(vssUnsubscribeReq string) *pb.UnsubscribeRequestMessage

func UnsubscribeRequestPbToJson

func UnsubscribeRequestPbToJson(pbUnsubscribeReq *pb.UnsubscribeRequestMessage) string

func UnsubscribeResponseJsonToPb

func UnsubscribeResponseJsonToPb(vssUnsubscribeResp string) *pb.UnsubscribeResponseMessage

func UnsubscribeResponsePbToJson

func UnsubscribeResponsePbToJson(pbUnsubscribeResp *pb.UnsubscribeResponseMessage) string

func UrlToPath

func UrlToPath(url string) string

func VSSGetDefaultList

func VSSGetDefaultList(rootNode *Node_t, rootNodeName string, listFname string) int

func VSSGetLeafNodesList

func VSSGetLeafNodesList(rootNode *Node_t, rootNodeName string, listFname string) int

func VSSWriteTree

func VSSWriteTree(fname string, root *Node_t)

func VSSgetAllowedElement

func VSSgetAllowedElement(nodeHandle *Node_t, index int) string

func VSSgetDatatype

func VSSgetDatatype(nodeHandle *Node_t) string

func VSSgetDefault

func VSSgetDefault(nodeHandle *Node_t) string

func VSSgetDescr

func VSSgetDescr(nodeHandle *Node_t) string

func VSSgetName

func VSSgetName(nodeHandle *Node_t) string

func VSSgetNumOfAllowedElements

func VSSgetNumOfAllowedElements(nodeHandle *Node_t) int

func VSSgetNumOfChildren

func VSSgetNumOfChildren(nodeHandle *Node_t) int

func VSSgetType

func VSSgetType(nodeHandle *Node_t) string

func VSSgetUUID

func VSSgetUUID(nodeHandle *Node_t) string

func VSSgetUnit

func VSSgetUnit(nodeHandle *Node_t) string

func VSSgetValidation

func VSSgetValidation(nodeHandle *Node_t) int

func ValidateToInt

func ValidateToInt(validate string) uint8

func ValidateToString

func ValidateToString(validate uint8) string

func VerifyTokenSignature

func VerifyTokenSignature(token string, key string) error

Types

type ClientHandler

type ClientHandler interface {
	// contains filtered or unexported methods
}

*********** Client response handlers *******************************************************************************

type ClientServer

type ClientServer interface {
	InitClientServer(muxServer *http.ServeMux)
}

type Encoding

type Encoding int
const (
	NONE     Encoding = 0
	PROTOBUF          = 1
)

type ErrorInformation

type ErrorInformation struct {
	Number  string
	Reason  string
	Message string
}

type ExtendedJwt

type ExtendedJwt struct {
	Token         JsonWebToken
	HeaderClaims  map[string]string
	PayloadClaims map[string]string
}

********* EXTENDED JSON WEB TOKEN *********** ********* Extends the JsonWebToken type, including a map with the claims in header ********* and a map with the claims in payload

func (*ExtendedJwt) DecodeFromFull

func (ext *ExtendedJwt) DecodeFromFull(input string) error

type FileTransferCache

type FileTransferCache struct {
	Uid               [UIDLEN]byte
	UploadTransfer    bool   //true=upload, false=download
	Path              string // from statestorage
	Name              string // incl file ext. Download from client, upload from statestorage.
	FileDescriptor    *os.File
	FileOffset        int
	ChunkSize         int
	Hash              string // hex format. SHA-1 ger 20 bytes output vilet i hex blir 40 chars + 2 för 0x
	MessageNo         int32
	PreviousChunksize int32
	Timestamp         uint64 //time of creation
	Status            int    //zero=ok, non-zero=nok
}

type FilterObject

type FilterObject struct {
	Type      string
	Parameter string
}

type HimTree

type HimTree struct {
	RootName    string
	Handle      *Node_t
	TreeType    string
	Domain      string
	Version     string
	FileName    string
	Description string
}

type HttpChannel

type HttpChannel struct {
}

type HttpServer

type HttpServer struct {
}

func (HttpServer) InitClientServer

func (server HttpServer) InitClientServer(muxServer *http.ServeMux, httpClientChan []chan string)

Launches the HTTP Manager

type JsonWebKey

type JsonWebKey struct {
	Thumb  string `json:"-"`
	Type   string `json:"kty"`
	Use    string `json:"use,omitempty"`
	PubMod string `json:"n,omitempty"`   // RSA
	PubExp string `json:"e,omitempty"`   // RSA
	Curve  string `json:"crv,omitempty"` //ECDSA
	Xcoord string `json:"x,omitempty"`   //ECDSA
	Ycoord string `json:"y,omitempty"`   //ECDSA
}

********* JSON WEB KEY ENCODING *********** ********* Contained in PoP, follows RFC7517 standard. Support for RSA and ECDSA keys

func (*JsonWebKey) GenThumbprint

func (jkey *JsonWebKey) GenThumbprint() string

Generates thumbprint of the JWK

func (*JsonWebKey) Initialize

func (jkey *JsonWebKey) Initialize(pubKey crypto.PublicKey, use string) error

Initializes json web key from public key

func (*JsonWebKey) Marshal

func (jkey *JsonWebKey) Marshal() string

From JsonWebKey struct, returns marshalled text

func (*JsonWebKey) Unmarshall

func (jkey *JsonWebKey) Unmarshall(rcv string) error

Gets the received JWK and unmarshalls it, returns error if fails to unmarshall

type JsonWebToken

type JsonWebToken struct {
	Header           string
	Payload          string
	EncodedHeader    string
	EncodedPayload   string
	EncodedSignature string
}

********* JSON WEB TOKEN *********** ********* Basic JWT including Header, Payload and encoded parts. ********* Methods for decoding and signature check avaliable

func (*JsonWebToken) AddClaim

func (token *JsonWebToken) AddClaim(key string, value string)

Adds a claim to the payload

func (*JsonWebToken) AddHeader

func (token *JsonWebToken) AddHeader(key string, value string)

Adds a claim to the header

func (*JsonWebToken) AssymSign

func (token *JsonWebToken) AssymSign(privKey crypto.PrivateKey) error

Signs the token using an assymetric key

func (JsonWebToken) CheckAssymSignature

func (token JsonWebToken) CheckAssymSignature(key crypto.PublicKey) (err error)

Checks the assymetric signature of the token

func (JsonWebToken) CheckSignature

func (token JsonWebToken) CheckSignature(key interface{}) error

Checks if the token is signed correctly. In case of symm sign, key as string must be passed. In case of assym, a crypto.PublicKey must be passed

func (*JsonWebToken) DecodeFromFull

func (token *JsonWebToken) DecodeFromFull(input string) error

From a signed jwt received, gets header and payload

func (*JsonWebToken) Encode

func (token *JsonWebToken) Encode()

Encodes the Token

func (JsonWebToken) GetFullToken

func (token JsonWebToken) GetFullToken() string

Returns the full token

func (JsonWebToken) GetHeader

func (token JsonWebToken) GetHeader() string

Returns the header of the token

func (JsonWebToken) GetPayload

func (token JsonWebToken) GetPayload() string

Returns the payload of the token

func (*JsonWebToken) SetHeader

func (token *JsonWebToken) SetHeader(algorithm string)

Sets the algorithm used

func (*JsonWebToken) SymmSign

func (token *JsonWebToken) SymmSign(key string)

Signs the token using a symmetric key

type LeafPathList

type LeafPathList struct {
	LeafPaths []string
}

type Node_t

type Node_t struct {
	Name         string
	NodeType     string
	Uuid         string
	Description  string
	Datatype     string
	Min          string
	Max          string
	Unit         string
	Allowed      uint8
	AllowedDef   []string
	DefaultValue string
	Validate     uint8
	Children     uint8
	Parent       *Node_t
	Child        []*Node_t
}

func SetRootNodePointer

func SetRootNodePointer(rootPath string) *Node_t

func VSSReadTree

func VSSReadTree(fname string) *Node_t

func VSSgetChild

func VSSgetChild(nodeHandle *Node_t, childNo int) *Node_t

func VSSgetParent

func VSSgetParent(nodeHandle *Node_t) *Node_t

type PopToken

type PopToken struct {
	HeaderClaims  map[string]string // TYP, ALG, JWK
	PayloadClaims map[string]string // IAT, JTI
	Jwk           JsonWebKey
	Jwt           JsonWebToken
}

********* POP TOKEN *********** ********* POP Token is used by the client to attest its possession of a private key ********* More info in the README of the repo

func (*PopToken) CheckAud

func (popToken *PopToken) CheckAud(aud string) (bool, string)

func (PopToken) CheckExp

func (popToken PopToken) CheckExp() (bool, string)

Check exp time

func (PopToken) CheckIat

func (popToken PopToken) CheckIat(gap int, lifetime int) (bool, string)

Check iats. Gap is the possible error between clocks. lifetime is the maximum time after is creation that the token can be used

func (*PopToken) CheckSignature

func (popToken *PopToken) CheckSignature() error

Checks signature, checks that alg used to sign is the same as in key (to avoid exploits)

func (PopToken) CheckThumb

func (popToken PopToken) CheckThumb(thumprint string) (bool, string)

Validates keys: same alg, same thumprint...

func (*PopToken) GenerateToken

func (popToken *PopToken) GenerateToken(privKey crypto.PrivateKey) (token string, err error)

Generates popToken using a PrivateKey, can be used even if popToken is not initialized (claims are auto-fulfilled)

func (PopToken) GetPubEcdsa

func (popToken PopToken) GetPubEcdsa() (*ecdsa.PublicKey, error)

Obtains ECDSA public ket in the PoP token. Returns nil + error if fails

func (PopToken) GetPubRsa

func (popToken PopToken) GetPubRsa() (*rsa.PublicKey, error)

Obtains Rsa public key included in the PoP token. Returns nil + error if fails

func (*PopToken) Initialize

func (popToken *PopToken) Initialize(headerMap, payloadMap map[string]string, pubKey crypto.PublicKey) error

Initializes popToken from claims and public key. Make sure the private key used to sign is the same used to initialize

func (*PopToken) Unmarshal

func (popToken *PopToken) Unmarshal(token string) error

Gets the received PoP token as string, and unmarshalls it. JWK, JWT and claims fields are all filled

func (*PopToken) Validate

func (popToken *PopToken) Validate(thumbprint, aud string, gap, lifetime int) (valid bool, info string)

Returns a bool that tells if the pop token is valid.

type ReadTreeMetadata_t

type ReadTreeMetadata_t struct {
	CurrentDepth int
	MaxTreeDepth int
	TotalNodes   int
}

type SearchContext_t

type SearchContext_t struct {
	RootNode           *Node_t
	SwitchName         bool
	RootNodeName       string
	MaxFound           int
	LeafNodesOnly      bool
	MaxDepth           int
	SearchPath         string
	MatchPath          string
	CurrentDepth       int     // depth in tree from rootNode, and also depth (in segments) in searchPath
	SpeculationIndex   int     // inc/dec when pathsegment in focus is wildcard
	SpeculativeMatches [20]int // inc when matching node is saved
	MaxValidation      int
	NumOfMatches       int
	SearchData         []SearchData_t
	ListSize           int
	NoScopeList        []string
	ListFp             *os.File
}

type SearchData_t

type SearchData_t struct {
	NodePath   string
	NodeHandle *Node_t
}

func VSSsearchNodes

func VSSsearchNodes(searchPath string, rootNode *Node_t, maxFound int, anyDepth bool, leafNodesOnly bool, listSize int, noScopeList []string, validation *int) ([]SearchData_t, int)

type SecConfig

type SecConfig struct {
	TransportSec  string `json:"transportSec"`  // "yes" or "no"
	HttpSecPort   string `json:"httpSecPort"`   // HTTPS port number
	WsSecPort     string `json:"wsSecPort"`     // WSS port number
	MqttSecPort   string `json:"mqttSecPort"`   // MQTTS port number
	GrpcSecPort   string `json:"grpcSecPort"`   // MQTTS port number
	AgtsSecPort   string `json:"agtsSecPort"`   // AGTS port number
	AtsSecPort    string `json:"atsSecPort"`    // ATS port number
	CaSecPath     string `json:"caSecPath"`     // relative path from the directory containing the transportSec.json file
	ServerSecPath string `json:"serverSecPath"` // relative path from the directory containing the transportSec.json file
	ServerCertOpt string `json:"serverCertOpt"` // one of  "NoClientCert"/"ClientCertNoVerification"/"ClientCertVerification"
	ClientSecPath string `json:"clientSecPath"` // relative path from the directory containing the transportSec.json file
}
var SecureConfiguration SecConfig // name change to caps allowing to export outside utils

type UdsReg

type UdsReg struct {
	RootName     string `json:"root"`
	ServerFeeder string `json:"serverFeeder"`
	Redis        string `json:"redis"`
	Memcache     string `json:"memcache"`
	History      string `json:"history"`
}

func ReadUdsRegistrations

func ReadUdsRegistrations(sockFile string) []UdsReg

type WsChannel

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

type WsServer

type WsServer struct {
	ClientBackendChannel []chan string
}

func (WsServer) InitClientServer

func (server WsServer) InitClientServer(muxServer *http.ServeMux, wsClientChan []chan string, mgrIndex int, clientIndex *int)

Launches the WebSocket Manager

Jump to

Keyboard shortcuts

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