2022-01-06 06:40:23 -05:00
|
|
|
package files
|
|
|
|
|
|
|
|
|
|
import (
|
2022-08-24 17:48:45 +00:00
|
|
|
"fmt"
|
2022-01-06 06:40:23 -05:00
|
|
|
"io"
|
|
|
|
|
"os"
|
2022-01-19 00:38:04 +00:00
|
|
|
"strings"
|
2022-08-24 17:48:45 +00:00
|
|
|
|
|
|
|
|
"github.com/qdm12/gluetun/internal/openvpn/extract"
|
2022-01-06 06:40:23 -05:00
|
|
|
)
|
|
|
|
|
|
2024-03-25 19:14:20 +00:00
|
|
|
// ReadFromFile reads the content of the file as a string,
|
|
|
|
|
// and returns if the file was present or not with isSet.
|
|
|
|
|
func ReadFromFile(filepath string) (content string, isSet bool, err error) {
|
2022-01-06 06:40:23 -05:00
|
|
|
file, err := os.Open(filepath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if os.IsNotExist(err) {
|
2024-03-25 19:14:20 +00:00
|
|
|
return "", false, nil
|
2022-01-06 06:40:23 -05:00
|
|
|
}
|
2024-03-25 19:14:20 +00:00
|
|
|
return "", false, fmt.Errorf("opening file: %w", err)
|
2022-01-06 06:40:23 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
b, err := io.ReadAll(file)
|
|
|
|
|
if err != nil {
|
|
|
|
|
_ = file.Close()
|
2024-03-25 19:14:20 +00:00
|
|
|
return "", false, fmt.Errorf("reading file: %w", err)
|
2022-01-06 06:40:23 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := file.Close(); err != nil {
|
2024-03-25 19:14:20 +00:00
|
|
|
return "", false, fmt.Errorf("closing file: %w", err)
|
2022-01-06 06:40:23 -05:00
|
|
|
}
|
|
|
|
|
|
2024-03-25 19:14:20 +00:00
|
|
|
content = string(b)
|
2022-01-19 00:38:04 +00:00
|
|
|
content = strings.TrimSuffix(content, "\r\n")
|
|
|
|
|
content = strings.TrimSuffix(content, "\n")
|
2024-03-25 19:14:20 +00:00
|
|
|
return content, true, nil
|
2022-01-06 06:40:23 -05:00
|
|
|
}
|
2022-08-24 17:48:45 +00:00
|
|
|
|
2024-03-25 19:14:20 +00:00
|
|
|
func ReadPEMFile(filepath string) (base64Str string, isSet bool, err error) {
|
|
|
|
|
pemData, isSet, err := ReadFromFile(filepath)
|
2022-08-24 17:48:45 +00:00
|
|
|
if err != nil {
|
2024-03-25 19:14:20 +00:00
|
|
|
return "", false, fmt.Errorf("reading file: %w", err)
|
|
|
|
|
} else if !isSet {
|
|
|
|
|
return "", false, nil
|
2022-08-24 17:48:45 +00:00
|
|
|
}
|
|
|
|
|
|
2024-03-25 19:14:20 +00:00
|
|
|
base64Str, err = extract.PEM([]byte(pemData))
|
2022-08-24 17:48:45 +00:00
|
|
|
if err != nil {
|
2024-03-25 19:14:20 +00:00
|
|
|
return "", false, fmt.Errorf("extracting base64 encoded data from PEM content: %w", err)
|
2022-08-24 17:48:45 +00:00
|
|
|
}
|
|
|
|
|
|
2024-03-25 19:14:20 +00:00
|
|
|
return base64Str, true, nil
|
2022-08-24 17:48:45 +00:00
|
|
|
}
|