Files
2023-07-25 10:09:51 +02:00

104 lines
1.9 KiB
Go

// de-LDIF'y LDAP query result
// join breaked lines, and decode base64
//
// Copyright (c) 2023 yo000 <johan@nosd.in>
//
package main
import (
"os"
"fmt"
"flag"
"bufio"
"regexp"
"strings"
"encoding/base64"
)
var (
gVersion = "0.2"
Usage = func() {
fmt.Printf("deldify v%s\n", gVersion)
fmt.Printf("Usage: deldify [-h|--help] [filename]\n")
fmt.Printf(" read stdin if filename is empty or '-'\n")
fmt.Printf("Flags:\n")
fmt.Printf(" -h|--help: Display help\n")
os.Exit(1)
}
)
func main() {
var input string
flag.Usage = Usage
flag.Parse()
if len(flag.Args()) == 0 {
input = "-"
}
// open file or stdin
var f *os.File
if !strings.EqualFold(input, "-") {
f, err := os.Open(input)
if err != nil {
fmt.Errorf("%v\n", err)
}
// remember to close the file at the end of the program
defer f.Close()
} else {
f = os.Stdin
}
// read the file line by line using scanner
scanner := bufio.NewScanner(f)
// Make 2 pass:
// First concatenate space starting lines, put result into ram
// Second to decode base64 lines
// Then print result
// 1st pass
var res1 []string
var cl string
for scanner.Scan() {
cl = scanner.Text()
if strings.HasPrefix(cl, " ") {
res1[len(res1)-1] = fmt.Sprintf("%s%s", res1[len(res1)-1], cl[1:])
} else {
res1 = append(res1, fmt.Sprintf("%s", cl))
}
}
// 2nd pass
var res2 []string
re := regexp.MustCompile("(\\w+)::\\s(.*)")
for _, l := range res1 {
m := re.FindStringSubmatch(l)
if len(m) > 0 {
dec, err := base64.StdEncoding.DecodeString(m[2])
if err != nil {
fmt.Printf("Error decoding base64: %s: %v\n", m[2], err)
continue
}
res2 = append(res2, fmt.Sprintf("%s: %s", m[1], dec))
} else {
res2 = append(res2, l)
}
}
for _, l := range res2 {
fmt.Printf("%s\n", l)
}
if err := scanner.Err(); err != nil {
fmt.Errorf("%v\n", err)
}
}