Skip to content

Commit 8a3514a

Browse files
committed
Code refactoring
1 parent 2677ff7 commit 8a3514a

6 files changed

Lines changed: 105 additions & 86 deletions

File tree

cli/cli.go

Lines changed: 41 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,8 @@ package cli
1010
import (
1111
"errors"
1212
"fmt"
13-
"io/ioutil"
1413
"os"
1514
"runtime"
16-
"strconv"
1715
"strings"
1816
"time"
1917

@@ -23,6 +21,7 @@ import (
2321
"github.com/essentialkaos/ek/v12/options"
2422
"github.com/essentialkaos/ek/v12/pager"
2523
"github.com/essentialkaos/ek/v12/strutil"
24+
"github.com/essentialkaos/ek/v12/timeutil"
2625
"github.com/essentialkaos/ek/v12/usage"
2726
"github.com/essentialkaos/ek/v12/usage/completion/bash"
2827
"github.com/essentialkaos/ek/v12/usage/completion/fish"
@@ -129,7 +128,7 @@ var gradeNumMap = map[string]float64{
129128
}
130129

131130
var api *sslscan.API
132-
var maxLeftToExpiry int64
131+
var maxLeftToExpiry time.Duration
133132
var serverMessageShown bool
134133

135134
var colorTagApp, colorTagVer string
@@ -148,7 +147,6 @@ func Run(gitRev string, gomod []byte) {
148147
}
149148

150149
configureUI()
151-
prepare()
152150

153151
switch {
154152
case options.Has(OPT_COMPLETION):
@@ -167,7 +165,22 @@ func Run(gitRev string, gomod []byte) {
167165
os.Exit(0)
168166
}
169167

170-
process(args)
168+
err := prepare()
169+
170+
if err != nil {
171+
printError(err.Error())
172+
os.Exit(1)
173+
}
174+
175+
err, ok := process(args)
176+
177+
if err != nil {
178+
printError(err.Error())
179+
}
180+
181+
if !ok {
182+
os.Exit(1)
183+
}
171184
}
172185

173186
// configureUI configures user interface
@@ -185,28 +198,29 @@ func configureUI() {
185198
case fmtc.Is256ColorsSupported():
186199
colorTagApp, colorTagVer = "{*}{#99}", "{#99}"
187200
default:
188-
colorTagApp, colorTagVer = "{*}{b}", "{c}"
201+
colorTagApp, colorTagVer = "{*}{b}", "{b}"
189202
}
190203
}
191204

192205
// prepare prepares utility for processing data
193-
func prepare() {
206+
func prepare() error {
194207
if !options.Has(OPT_MAX_LEFT) {
195-
return
208+
return nil
196209
}
197210

198211
var err error
199212

200-
maxLeftToExpiry, err = parseMaxLeft(options.GetS(OPT_MAX_LEFT))
213+
maxLeftToExpiry, err = timeutil.ParseDuration(options.GetS(OPT_MAX_LEFT), 'd')
201214

202215
if err != nil {
203-
printError(err.Error())
204-
os.Exit(1)
216+
return err
205217
}
218+
219+
return nil
206220
}
207221

208222
// process starting request processing
209-
func process(args options.Arguments) {
223+
func process(args options.Arguments) (error, bool) {
210224
var ok bool
211225
var err error
212226
var hosts []string
@@ -215,20 +229,23 @@ func process(args options.Arguments) {
215229

216230
if err != nil {
217231
if !options.GetB(OPT_FORMAT) {
218-
printError(err.Error())
232+
return err, false
219233
}
220234

221-
os.Exit(1)
235+
return nil, false
222236
}
223237

224238
ok = true // By default everything is fine
225239

226240
if fsutil.CheckPerms("FR", args.Get(0).String()) {
227241
hosts, err = readHostList(args.Get(0).String())
228242

229-
if err != nil && options.GetB(OPT_FORMAT) {
230-
printError(err.Error())
231-
os.Exit(1)
243+
if err != nil {
244+
if !options.GetB(OPT_FORMAT) {
245+
return err, false
246+
}
247+
248+
return nil, false
232249
}
233250
} else {
234251
hosts = args.Strings()
@@ -268,8 +285,10 @@ func process(args options.Arguments) {
268285
}
269286

270287
if !ok {
271-
os.Exit(1)
288+
return nil, false
272289
}
290+
291+
return nil, true
273292
}
274293

275294
// check check some host
@@ -528,25 +547,17 @@ func getStatusInProgress(endpoints []*sslscan.EndpointInfo) string {
528547
return ""
529548
}
530549

531-
// readHostList read file with hosts
550+
// readHostList reads file with hosts
532551
func readHostList(file string) ([]string, error) {
533552
var result []string
534553

535-
fd, err := os.OpenFile(file, os.O_RDONLY, 0)
536-
537-
if err != nil {
538-
return result, err
539-
}
540-
541-
defer fd.Close()
542-
543-
listData, err := ioutil.ReadAll(fd)
554+
listData, err := os.ReadFile(file)
544555

545556
if err != nil {
546-
return result, err
557+
return nil, err
547558
}
548559

549-
list := strings.Split(string(listData[:]), "\n")
560+
list := strings.Split(string(listData), "\n")
550561

551562
for _, host := range list {
552563
if host != "" {
@@ -574,28 +585,6 @@ func appendEndpointsInfo(checkInfo *HostCheckInfo, endpoints []*sslscan.Endpoint
574585
}
575586
}
576587

577-
// parseMaxLeft parses max left option value
578-
func parseMaxLeft(dur string) (int64, error) {
579-
tm := strutil.Tail(dur, 1)
580-
t := strings.Trim(dur, "dwmy")
581-
ti, err := strconv.ParseInt(t, 10, 64)
582-
583-
if err != nil {
584-
return -1, fmt.Errorf("Invalid value for --max-left option: %s", dur)
585-
}
586-
587-
switch strings.ToLower(tm) {
588-
case "w":
589-
return ti * 604800, nil
590-
case "m":
591-
return ti * 2592000, nil
592-
case "y":
593-
return ti * 31536000, nil
594-
default:
595-
return ti * 86400, nil
596-
}
597-
}
598-
599588
// getNormGrade return grade or error
600589
func getNormGrade(grade string) string {
601590
switch grade {

cli/details.go

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ func printCertificateInfo(certs []*sslscan.Cert, endpoints []*sslscan.EndpointIn
8686

8787
printCategoryHeader("Server Key and Certificate")
8888

89+
if len(certs) == 0 {
90+
fmtc.Println("\n {r}No valid certificates and keys{!}\n")
91+
fmtutil.Separator(true)
92+
return
93+
}
94+
8995
cert := certs[0]
9096

9197
fmtc.Printf(" %-24s {s}|{!} %s\n", "Subject", extractSubject(cert.Subject))
@@ -1025,11 +1031,12 @@ func printEndpointHPKPInfo(details *sslscan.EndpointDetails) {
10251031
func printEndpointHandshakeInfo(details *sslscan.EndpointDetails) {
10261032
fmtc.Printf(" %-40s {s}|{!} ", "Long handshake intolerance")
10271033

1028-
if details.MiscIntolerance&2 == 2 {
1034+
switch {
1035+
case details.MiscIntolerance&2 == 2:
10291036
fmtc.Println("{y}Yes{!}")
1030-
} else if details.MiscIntolerance&4 == 4 {
1037+
case details.MiscIntolerance&4 == 4:
10311038
fmtc.Println("{y}Yes{!} {s-}(workaround success){!}")
1032-
} else {
1039+
default:
10331040
fmtc.Println("No")
10341041
}
10351042
}
@@ -1386,7 +1393,7 @@ func getPinsFromPolicy(policy *sslscan.HPKPPolicy) []string {
13861393

13871394
for _, pin := range strings.Split(policy.Header, ";") {
13881395
pin = strings.TrimSpace(pin)
1389-
pin = strings.Replace(pin, "\"", "", -1)
1396+
pin = strings.ReplaceAll(pin, "\"", "")
13901397
pin = strings.Replace(pin, "=", ": ", 1)
13911398

13921399
if strings.HasPrefix(pin, "pin-") {
@@ -1460,8 +1467,8 @@ func isWeakSuite(suite *sslscan.Suite) bool {
14601467
// extractSubject extracts subject name from certificate subject
14611468
func extractSubject(data string) string {
14621469
subject := strutil.ReadField(data, 0, false, ",")
1463-
subject = strings.Replace(subject, "CN=", "", -1)
1464-
subject = strings.Replace(subject, "OU=", "", -1)
1470+
subject = strings.ReplaceAll(subject, "CN=", "")
1471+
subject = strings.ReplaceAll(subject, "OU=", "")
14651472

14661473
return subject
14671474
}
@@ -1502,7 +1509,7 @@ func getTrustInfo(certID string, endpoints []*sslscan.EndpointInfo) (map[string]
15021509
}
15031510

15041511
// getExpiryMessage returns message if cert is expired in given period
1505-
func getExpiryMessage(ap *sslscan.AnalyzeProgress, dur int64) string {
1512+
func getExpiryMessage(ap *sslscan.AnalyzeProgress, dur time.Duration) string {
15061513
if dur <= 0 {
15071514
return ""
15081515
}
@@ -1516,7 +1523,7 @@ func getExpiryMessage(ap *sslscan.AnalyzeProgress, dur int64) string {
15161523
cert := info.Certs[0]
15171524
validUntilDate := time.Unix(cert.NotAfter/1000, 0)
15181525

1519-
if validUntilDate.Unix()-time.Now().Unix() > dur {
1526+
if time.Until(validUntilDate) > dur {
15201527
return ""
15211528
}
15221529

cli/encoder.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func encodeAsJSON(checksInfo []*HostCheckInfo) {
3838
os.Exit(1)
3939
}
4040

41-
fmt.Println(string(jsonData[:]))
41+
fmt.Println(string(jsonData))
4242
}
4343

4444
// encodeAsXML print check info in XML format

cli/support/support.go

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,15 @@ import (
1111
"fmt"
1212
"os"
1313
"runtime"
14+
"runtime/debug"
1415
"strings"
1516

1617
"github.com/essentialkaos/ek/v12/fmtc"
1718
"github.com/essentialkaos/ek/v12/fmtutil"
18-
"github.com/essentialkaos/ek/v12/fsutil"
1919
"github.com/essentialkaos/ek/v12/hash"
2020
"github.com/essentialkaos/ek/v12/strutil"
2121
"github.com/essentialkaos/ek/v12/system"
22+
"github.com/essentialkaos/ek/v12/system/container"
2223

2324
"github.com/essentialkaos/depsy"
2425
)
@@ -55,6 +56,10 @@ func showApplicationInfo(app, ver, gitRev string) {
5556
runtime.GOOS, runtime.GOARCH,
5657
))
5758

59+
if gitRev == "" {
60+
gitRev = extractGitRevFromBuildInfo()
61+
}
62+
5863
if gitRev != "" {
5964
if !fmtc.DisableColors && fmtc.IsTrueColorSupported() {
6065
printInfo(7, "Git SHA", gitRev+getHashColorBullet(gitRev))
@@ -83,37 +88,38 @@ func showOSInfo() {
8388
if err == nil {
8489
fmtutil.Separator(false, "OS INFO")
8590

86-
printInfo(12, "Name", osInfo.Name)
87-
printInfo(12, "Pretty Name", osInfo.PrettyName)
88-
printInfo(12, "Version", osInfo.VersionID)
91+
printInfo(12, "Name", osInfo.ColoredName())
92+
printInfo(12, "Pretty Name", osInfo.ColoredPrettyName())
93+
printInfo(12, "Version", osInfo.Version)
8994
printInfo(12, "ID", osInfo.ID)
9095
printInfo(12, "ID Like", osInfo.IDLike)
9196
printInfo(12, "Version ID", osInfo.VersionID)
9297
printInfo(12, "Version Code", osInfo.VersionCodename)
98+
printInfo(12, "Platform ID", osInfo.PlatformID)
9399
printInfo(12, "CPE", osInfo.CPEName)
94100
}
95101

96102
systemInfo, err := system.GetSystemInfo()
97103

98104
if err != nil {
99105
return
100-
} else {
101-
if osInfo == nil {
102-
fmtutil.Separator(false, "SYSTEM INFO")
103-
printInfo(12, "Name", systemInfo.OS)
104-
}
106+
} else if osInfo == nil {
107+
fmtutil.Separator(false, "SYSTEM INFO")
108+
printInfo(12, "Name", systemInfo.OS)
105109
}
106110

107111
printInfo(12, "Arch", systemInfo.Arch)
108112
printInfo(12, "Kernel", systemInfo.Kernel)
109113

110114
containerEngine := "No"
111115

112-
switch {
113-
case fsutil.IsExist("/.dockerenv"):
116+
switch container.GetEngine() {
117+
case container.DOCKER:
114118
containerEngine = "Yes (Docker)"
115-
case fsutil.IsExist("/run/.containerenv"):
119+
case container.PODMAN:
116120
containerEngine = "Yes (Podman)"
121+
case container.LXC:
122+
containerEngine = "Yes (LXC)"
117123
}
118124

119125
fmtc.NewLine()
@@ -140,6 +146,23 @@ func showDepsInfo(gomod []byte) {
140146
}
141147
}
142148

149+
// extractGitRevFromBuildInfo extracts git SHA from embedded build info
150+
func extractGitRevFromBuildInfo() string {
151+
info, ok := debug.ReadBuildInfo()
152+
153+
if !ok {
154+
return ""
155+
}
156+
157+
for _, s := range info.Settings {
158+
if s.Key == "vcs.revision" && len(s.Value) > 7 {
159+
return s.Value[:7]
160+
}
161+
}
162+
163+
return ""
164+
}
165+
143166
// getHashColorBullet return bullet with color from hash
144167
func getHashColorBullet(v string) string {
145168
if len(v) > 6 {
@@ -151,7 +174,7 @@ func getHashColorBullet(v string) string {
151174

152175
// printInfo formats and prints info record
153176
func printInfo(size int, name, value string) {
154-
name = name + ":"
177+
name += ":"
155178
size++
156179

157180
if value == "" {

0 commit comments

Comments
 (0)