ppforge/protocolctl/protocolctl.go

129 lines
2.7 KiB
Go

package protocolctl
import (
"encoding/json"
"io/fs"
"os"
"gitea.mmo.to/ProtocolPacketForger/ppf/protocol"
)
func NewProtocolStructure() *protocol.ProtocolStructure {
p := protocol.ProtocolStructure{}
return &p
}
func UpdateMetaData(
prot *protocol.ProtocolStructure,
name string,
version string,
tcpiplayer uint,
osilayer uint,
extensionTo string,
desc string,
requiredJSfunctions []string,
lowerLayerIdent map[string]string,
) {
prot.Metadata.Name = name
prot.Metadata.Description = desc
prot.Metadata.ExtensionTo = extensionTo
prot.Metadata.Version = version
prot.Metadata.OSILayer = osilayer
prot.Metadata.TCPIPLayer = tcpiplayer
prot.Metadata.RequiredJSFunctions = requiredJSfunctions
prot.Metadata.LowerLayerIdentification = lowerLayerIdent
}
func NewField(
name string,
desc string,
regex string,
size uint,
subfields []protocol.Field,
optional bool,
payload bool,
) *protocol.Field {
f := protocol.Field{
Name: name,
Desc: desc,
Regex: regex,
Size: size,
SubFields: subfields,
Optional: optional,
Payload: payload,
}
return &f
}
func AppendField(prot *protocol.ProtocolStructure, field *protocol.Field) {
prot.Structure = append(prot.Structure, *field)
}
func UpdateFieldByName(prot *protocol.ProtocolStructure, name string, field *protocol.Field) {
var fnd int = -1
for i, f := range prot.Structure {
if f.Name == name {
fnd = i
}
}
if fnd != -1 {
prot.Structure[fnd] = *field
}
}
func UpdateFieldByElement(prot *protocol.ProtocolStructure, element int, field *protocol.Field) {
prot.Structure[element] = *field
}
func RemoveFieldByName(prot *protocol.ProtocolStructure, name string) {
element := -1
for i, f := range prot.Structure {
if f.Name == name {
element = i
}
}
if element == -1 {
return
}
RemoveFieldByElement(prot, element)
}
func RemoveFieldByElement(prot *protocol.ProtocolStructure, field int) {
ret := make([]protocol.Field, 0)
ret = append(ret, prot.Structure[:field]...)
ret = append(ret, prot.Structure[field+1:]...)
prot.Structure = ret
}
func Load(prot *protocol.ProtocolStructure, path string) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
err = json.Unmarshal(data, prot)
return err
}
func LoadNew(path string) (*protocol.ProtocolStructure, error) {
prot := NewProtocolStructure()
err := Load(prot, path)
return prot, err
}
func ToJson(prot *protocol.ProtocolStructure) string {
data, err := json.Marshal(*prot)
if err != nil {
return ""
}
return string(data)
}
func Save(prot *protocol.ProtocolStructure, path string) error {
data, err := json.Marshal(*prot)
if err != nil {
return err
}
err = os.WriteFile(path, data, fs.ModeAppend)
return err
}