1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
package cmd
import (
"errors"
"strings"
)
// systemdShell is not a real shell
type systemdShell struct{}
// Systemd is not really a shell but is useful to add support
// to systemd EnvironmentFile(https://0pointer.de/public/systemd-man/systemd.exec.html#EnvironmentFile=)
var Systemd Shell = systemdShell{}
func (sh systemdShell) Hook() (string, error) {
return "", errors.New("this feature is not supported")
}
func (sh systemdShell) Export(e ShellExport) (string, error) {
var out string
for key, value := range e {
if value != nil {
out += sh.export(key, *value)
}
}
return out, nil
}
func (sh systemdShell) Dump(env Env) (string, error) {
var out string
for key, value := range env {
out += sh.export(key, value)
}
return out, nil
}
func cutEncapsulated(valueToTest, encapsulatingValue string) (cutValue string, wasEncapsulated bool) {
withoutPrefix, startsWithEncapsulatingValue := strings.CutPrefix(valueToTest, encapsulatingValue)
if startsWithEncapsulatingValue {
withoutPrefixAndSuffix, endsWithEncapsulatingValue := strings.CutSuffix(withoutPrefix, encapsulatingValue)
if endsWithEncapsulatingValue {
return withoutPrefixAndSuffix, true
}
}
return valueToTest, false
}
func sanitizeValue(value string) string {
containSpecialChar := false
specialCharacterList := []string{"\n", "\\", `"`, `'`}
for _, specialChar := range specialCharacterList {
if strings.ContainsAny(value, specialChar) {
containSpecialChar = true
}
}
sanitizedValue := value
if containSpecialChar {
// Since the value contains special characters it needs to be quoted
valueWithoutEncapsulation, encapsulatedBySingleQuotes := cutEncapsulated(value, `'`)
if encapsulatedBySingleQuotes {
sanitizedValue = `'` + strings.ReplaceAll(valueWithoutEncapsulation, `'`, `\'`) + `'`
} else {
valueWithoutEncapsulation, encapsulatedByDoubleQuotes := cutEncapsulated(value, `"`)
logDebug("encapsulated by double quotes : %v", encapsulatedByDoubleQuotes)
sanitizedValue = `"` + strings.ReplaceAll(valueWithoutEncapsulation, `"`, `\"`) + `"`
}
}
// if the value doesn't contains special characters then we don't touch it
return sanitizedValue
}
func (sh systemdShell) export(key, value string) string {
return key + "=" + sanitizeValue(value) + "\n"
}
|