From 10aaa35db54901699b6e377f8a0ea1e89f33686c Mon Sep 17 00:00:00 2001 From: "Johan T. Halseth" Date: Sun, 31 Oct 2021 19:16:10 +0100 Subject: [PATCH] kvdb: add loggableKeyName method Safely logs the bucket key name as hex if it includes special characters. Co-authored-by: Oliver Gugger --- kvdb/bolt_compact.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/kvdb/bolt_compact.go b/kvdb/bolt_compact.go index 7da51b3d3..e46c55f94 100644 --- a/kvdb/bolt_compact.go +++ b/kvdb/bolt_compact.go @@ -8,6 +8,7 @@ package kvdb import ( + "encoding/hex" "fmt" "os" "path" @@ -228,6 +229,30 @@ func (cmd *compacter) walk(db *bbolt.DB, walkFn walkFunc) error { }) } +// LoggableKeyName returns a printable name of the given key. +func LoggableKeyName(key []byte) string { + strKey := string(key) + if hasSpecialChars(strKey) { + return hex.EncodeToString(key) + } + + return strKey +} + +// hasSpecialChars returns true if any of the characters in the given string +// cannot be printed. +func hasSpecialChars(s string) bool { + for _, b := range s { + if !(b >= 'a' && b <= 'z') && !(b >= 'A' && b <= 'Z') && + !(b >= '0' && b <= '9') && b != '-' && b != '_' { + + return true + } + } + + return false +} + // walkBucket recursively walks through a bucket. func (cmd *compacter) walkBucket(b *bbolt.Bucket, keyPath [][]byte, k, v []byte, seq uint64, fn walkFunc) error {