Completed
Pull Request — master (#769)
by
unknown
11:57
created

scan.contentConvertVinfo   F

Complexity

Conditions 18

Size

Total Lines 60
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 41
dl 0
loc 60
rs 1.2
c 0
b 0
f 0
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like scan.contentConvertVinfo often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/* Vuls - Vulnerability Scanner
2
Copyright (C) 2016  Future Corporation , Japan.
3
4
This program is free software: you can redistribute it and/or modify
5
it under the terms of the GNU General Public License as published by
6
the Free Software Foundation, either version 3 of the License, or
7
(at your option) any later version.
8
9
This program is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
GNU General Public License for more details.
13
14
You should have received a copy of the GNU General Public License
15
along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
*/
17
18
package scan
19
20
import (
21
	"bufio"
22
	"encoding/json"
23
	"fmt"
24
	"net"
25
	"regexp"
26
	"strings"
27
	"time"
28
29
	"github.com/future-architect/vuls/config"
30
	"github.com/future-architect/vuls/models"
31
	"github.com/hashicorp/go-version"
32
	"github.com/k0kubun/pp"
33
	"github.com/sirupsen/logrus"
34
)
35
36
type base struct {
37
	ServerInfo config.ServerInfo
38
	Distro     config.Distro
39
	Platform   models.Platform
40
	osPackages
41
42
	log  *logrus.Entry
43
	errs []error
44
}
45
46
//Command is for check dependence
47
type Command struct {
48
	Command string
49
	Name    string
50
}
51
52
func (l *base) scanWp() (err error) {
53
	if len(l.ServerInfo.WpPath) == 0 && len(l.ServerInfo.WpToken) == 0 {
54
		return nil
55
	}
56
	if len(l.ServerInfo.WpPath) == 0 {
57
		return fmt.Errorf("not found : WpPath")
58
	}
59
	if len(l.ServerInfo.WpToken) == 0 {
60
		return fmt.Errorf("not found : WpToken")
61
	}
62
63
	cmd := []Command{{Command: "wp cli", Name: "wp"}, {Command: "curl --help", Name: "curl"}}
64
	for _, i := range cmd {
65
		if r := exec(l.ServerInfo, i.Command, noSudo); !r.isSuccess() {
66
			return fmt.Errorf("%s command not installed", i.Name)
67
		}
68
	}
69
70
	var vinfos []models.VulnInfo
71
	if vinfos, err = detectWp(l); err != nil {
72
		l.log.Errorf("Failed to scan wordpress: %s", err)
73
		return err
74
	}
75
	l.WpVulnInfos = map[string]models.VulnInfo{}
76
	for _, i := range vinfos {
77
		l.WpVulnInfos[i.CveID] = i
78
	}
79
80
	return
81
}
82
83
//WpCveInfos is for wpvulndb's json
84
type WpCveInfos struct {
85
	ReleaseDate     string      `json:"release_date"`
86
	ChangelogURL    string      `json:"changelog_url"`
87
	Status          string      `json:"status"`
88
	LatestVersion   string      `json:"latest_version"`
89
	LastUpdated     string      `json:"last_updated"`
90
	Popular         bool        `json:"popular"`
91
	Vulnerabilities []WpCveInfo `json:"vulnerabilities"`
92
	Error           string      `json:"error"`
93
}
94
95
//WpCveInfo is for wpvulndb's json
96
type WpCveInfo struct {
97
	ID            int        `json:"id"`
98
	Title         string     `json:"title"`
99
	CreatedAt     string     `json:"created_at"`
100
	UpdatedAt     string     `json:"updated_at"`
101
	PublishedDate string     `json:"published_date"`
102
	VulnType      string     `json:"vuln_type"`
103
	References    References `json:"references"`
104
	FixedIn       string     `json:"fixed_in"`
105
}
106
107
//References is for wpvulndb's json
108
type References struct {
109
	URL     []string `json:"url"`
110
	Cve     []string `json:"cve"`
111
	Secunia []string `json:"secunia"`
112
}
113
114
func detectWp(c *base) (vinfos []models.VulnInfo, err error) {
115
	var coreVulns []models.VulnInfo
116
	if coreVulns, err = detectWpCore(c); err != nil {
117
		return
118
	}
119
	vinfos = append(vinfos, coreVulns...)
120
121
	var themeVulns []models.VulnInfo
122
	if themeVulns, err = detectWpTheme(c); err != nil {
123
		return
124
	}
125
	vinfos = append(vinfos, themeVulns...)
126
127
	var pluginVulns []models.VulnInfo
128
	if pluginVulns, err = detectWpPlugin(c); err != nil {
129
		return
130
	}
131
	vinfos = append(vinfos, pluginVulns...)
132
133
	return
134
}
135
136
func detectWpCore(c *base) (vinfos []models.VulnInfo, err error) {
137
	cmd := fmt.Sprintf("wp core version --path=%s", c.ServerInfo.WpPath)
138
139
	var coreVersion string
140
	if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
141
		tmp := strings.Split(r.Stdout, ".")
142
		coreVersion = strings.Join(tmp, "")
143
		coreVersion = strings.TrimRight(coreVersion, "\r\n")
144
		if len(coreVersion) == 0 {
145
			return
146
		}
147
	}
148
	cmd = fmt.Sprintf("curl -k -H 'Authorization: Token token=%s' https://wpvulndb.com/api/v3/wordpresses/%s", c.ServerInfo.WpToken, coreVersion)
149
	if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
150
		coreConvertVinfo(r.Stdout)
151
	}
152
	return
153
}
154
155
func coreConvertVinfo(stdout string) (vinfos []models.VulnInfo, err error) {
156
	data := map[string]WpCveInfos{}
157
	if err = json.Unmarshal([]byte(stdout), &data); err != nil {
158
		return
159
	}
160
	for _, i := range data {
161
		if len(i.Vulnerabilities) == 0 {
162
			continue
163
		}
164
		for _, e := range i.Vulnerabilities {
165
			if len(e.References.Cve) == 0 {
166
				continue
167
			}
168
			NotFixedYet := false
169
			if len(e.FixedIn) == 0 {
170
				NotFixedYet = true
171
			}
172
			var cveIDs []string
173
			for _, k := range e.References.Cve {
174
				cveIDs = append(cveIDs, "CVE-"+k)
175
			}
176
177
			for _, cveID := range cveIDs {
178
				vinfos = append(vinfos, models.VulnInfo{
179
					CveID: cveID,
180
					CveContents: models.NewCveContents(
181
						models.CveContent{
182
							CveID: cveID,
183
							Title: e.Title,
184
						},
185
					),
186
					AffectedPackages: models.PackageStatuses{
187
						{
188
							NotFixedYet: NotFixedYet,
189
						},
190
					},
191
				})
192
			}
193
		}
194
	}
195
	return
196
}
197
198
//WpStatus is for wp command
199
type WpStatus struct {
200
	Name    string `json:"name"`
201
	Status  string `json:"status"`
202
	Update  string `json:"update"`
203
	Version string `json:"version"`
204
}
205
206
func detectWpTheme(c *base) (vinfos []models.VulnInfo, err error) {
207
	cmd := fmt.Sprintf("wp theme list --path=%s --format=json", c.ServerInfo.WpPath)
208
209
	var themes []WpStatus
210
	if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
211
		if err = json.Unmarshal([]byte(r.Stdout), &themes); err != nil {
212
			return
213
		}
214
	}
215
216
	for _, theme := range themes {
217
		cmd := fmt.Sprintf("curl -k -H 'Authorization: Token token=%s' https://wpvulndb.com/api/v3/themes/%s", c.ServerInfo.WpToken, theme.Name)
218
219
		if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
220
			pp.Print(r.Stdout)
221
			pp.Print(contentConvertVinfo(c, r.Stdout, theme))
222
		}
223
	}
224
	return
225
}
226
227
func detectWpPlugin(c *base) (vinfos []models.VulnInfo, err error) {
228
	cmd := fmt.Sprintf("wp plugin list --path=%s --format=json", c.ServerInfo.WpPath)
229
230
	var plugins []WpStatus
231
	if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
232
		if err = json.Unmarshal([]byte(r.Stdout), &plugins); err != nil {
233
			return
234
		}
235
	}
236
237
	for _, plugin := range plugins {
238
		cmd := fmt.Sprintf("curl -k -H 'Authorization: Token token=%s' https://wpvulndb.com/api/v3/plugins/%s", c.ServerInfo.WpToken, plugin.Name)
239
240
		if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
241
			contentConvertVinfo(c, r.Stdout, plugin)
242
		}
243
	}
244
	return
245
}
246
247
func contentConvertVinfo(c *base, stdout string, content WpStatus) (vinfos []models.VulnInfo, err error) {
248
	data := map[string]WpCveInfos{}
249
	if err = json.Unmarshal([]byte(stdout), &data); err != nil {
250
		var jsonError WpCveInfos
251
		if err = json.Unmarshal([]byte(stdout), &jsonError); err != nil {
252
			return
253
		}
254
		c.log.Errorf("wordpress: %s not found", content.Name)
255
	}
256
	for _, i := range data {
257
		if len(i.Vulnerabilities) == 0 {
258
			continue
259
		}
260
		for _, e := range i.Vulnerabilities {
261
			if len(e.References.Cve) == 0 {
262
				continue
263
			}
264
			notFixedYet := false
265
			if len(e.FixedIn) == 0 {
266
				notFixedYet = true
267
			}
268
			if len(e.FixedIn) == 0 {
269
				e.FixedIn = "0"
270
			}
271
			var v1 *version.Version
272
			v1, err = version.NewVersion(content.Version)
273
			if err != nil {
274
				return
275
			}
276
			var v2 *version.Version
277
			v2, err = version.NewVersion(e.FixedIn)
278
			if err != nil {
279
				return
280
			}
281
			if v1.LessThan(v2) {
282
				var cveIDs []string
283
				for _, k := range e.References.Cve {
284
					cveIDs = append(cveIDs, "CVE-"+k)
285
				}
286
287
				for _, cveID := range cveIDs {
288
					vinfos = append(vinfos, models.VulnInfo{
289
						CveID: cveID,
290
						CveContents: models.NewCveContents(
291
							models.CveContent{
292
								CveID: cveID,
293
								Title: e.Title,
294
							},
295
						),
296
						AffectedPackages: models.PackageStatuses{
297
							{
298
								NotFixedYet: notFixedYet,
299
							},
300
						},
301
					})
302
				}
303
			}
304
		}
305
	}
306
	return
307
}
308
309
func (l *base) wpConvertToModel() models.VulnInfos {
310
	return l.WpVulnInfos
311
}
312
313
func (l *base) exec(cmd string, sudo bool) execResult {
314
	return exec(l.ServerInfo, cmd, sudo, l.log)
315
}
316
317
func (l *base) setServerInfo(c config.ServerInfo) {
318
	l.ServerInfo = c
319
}
320
321
func (l *base) getServerInfo() config.ServerInfo {
322
	return l.ServerInfo
323
}
324
325
func (l *base) setDistro(fam, rel string) {
326
	d := config.Distro{
327
		Family:  fam,
328
		Release: rel,
329
	}
330
	l.Distro = d
331
332
	s := l.getServerInfo()
333
	s.Distro = d
334
	l.setServerInfo(s)
335
}
336
337
func (l *base) getDistro() config.Distro {
338
	return l.Distro
339
}
340
341
func (l *base) setPlatform(p models.Platform) {
342
	l.Platform = p
343
}
344
345
func (l *base) getPlatform() models.Platform {
346
	return l.Platform
347
}
348
349
func (l *base) runningKernel() (release, version string, err error) {
350
	r := l.exec("uname -r", noSudo)
351
	if !r.isSuccess() {
352
		return "", "", fmt.Errorf("Failed to SSH: %s", r)
353
	}
354
	release = strings.TrimSpace(r.Stdout)
355
356
	switch l.Distro.Family {
357
	case config.Debian:
358
		r := l.exec("uname -a", noSudo)
359
		if !r.isSuccess() {
360
			return "", "", fmt.Errorf("Failed to SSH: %s", r)
361
		}
362
		ss := strings.Fields(r.Stdout)
363
		if 6 < len(ss) {
364
			version = ss[6]
365
		}
366
	}
367
	return
368
}
369
370
func (l *base) allContainers() (containers []config.Container, err error) {
371
	switch l.ServerInfo.ContainerType {
372
	case "", "docker":
373
		stdout, err := l.dockerPs("-a --format '{{.ID}} {{.Names}} {{.Image}}'")
374
		if err != nil {
375
			return containers, err
376
		}
377
		return l.parseDockerPs(stdout)
378
	case "lxd":
379
		stdout, err := l.lxdPs("-c n")
380
		if err != nil {
381
			return containers, err
382
		}
383
		return l.parseLxdPs(stdout)
384
	case "lxc":
385
		stdout, err := l.lxcPs("-1")
386
		if err != nil {
387
			return containers, err
388
		}
389
		return l.parseLxcPs(stdout)
390
	default:
391
		return containers, fmt.Errorf(
392
			"Not supported yet: %s", l.ServerInfo.ContainerType)
393
	}
394
}
395
396
func (l *base) runningContainers() (containers []config.Container, err error) {
397
	switch l.ServerInfo.ContainerType {
398
	case "", "docker":
399
		stdout, err := l.dockerPs("--format '{{.ID}} {{.Names}} {{.Image}}'")
400
		if err != nil {
401
			return containers, err
402
		}
403
		return l.parseDockerPs(stdout)
404
	case "lxd":
405
		stdout, err := l.lxdPs("volatile.last_state.power=RUNNING -c n")
406
		if err != nil {
407
			return containers, err
408
		}
409
		return l.parseLxdPs(stdout)
410
	case "lxc":
411
		stdout, err := l.lxcPs("-1 --running")
412
		if err != nil {
413
			return containers, err
414
		}
415
		return l.parseLxcPs(stdout)
416
	default:
417
		return containers, fmt.Errorf(
418
			"Not supported yet: %s", l.ServerInfo.ContainerType)
419
	}
420
}
421
422
func (l *base) exitedContainers() (containers []config.Container, err error) {
423
	switch l.ServerInfo.ContainerType {
424
	case "", "docker":
425
		stdout, err := l.dockerPs("--filter 'status=exited' --format '{{.ID}} {{.Names}} {{.Image}}'")
426
		if err != nil {
427
			return containers, err
428
		}
429
		return l.parseDockerPs(stdout)
430
	case "lxd":
431
		stdout, err := l.lxdPs("volatile.last_state.power=STOPPED -c n")
432
		if err != nil {
433
			return containers, err
434
		}
435
		return l.parseLxdPs(stdout)
436
	case "lxc":
437
		stdout, err := l.lxcPs("-1 --stopped")
438
		if err != nil {
439
			return containers, err
440
		}
441
		return l.parseLxcPs(stdout)
442
	default:
443
		return containers, fmt.Errorf(
444
			"Not supported yet: %s", l.ServerInfo.ContainerType)
445
	}
446
}
447
448
func (l *base) dockerPs(option string) (string, error) {
449
	cmd := fmt.Sprintf("docker ps %s", option)
450
	r := l.exec(cmd, noSudo)
451
	if !r.isSuccess() {
452
		return "", fmt.Errorf("Failed to SSH: %s", r)
453
	}
454
	return r.Stdout, nil
455
}
456
457
func (l *base) lxdPs(option string) (string, error) {
458
	cmd := fmt.Sprintf("lxc list %s", option)
459
	r := l.exec(cmd, noSudo)
460
	if !r.isSuccess() {
461
		return "", fmt.Errorf("failed to SSH: %s", r)
462
	}
463
	return r.Stdout, nil
464
}
465
466
func (l *base) lxcPs(option string) (string, error) {
467
	cmd := fmt.Sprintf("lxc-ls %s 2>/dev/null", option)
468
	r := l.exec(cmd, sudo)
469
	if !r.isSuccess() {
470
		return "", fmt.Errorf("failed to SSH: %s", r)
471
	}
472
	return r.Stdout, nil
473
}
474
475
func (l *base) parseDockerPs(stdout string) (containers []config.Container, err error) {
476
	lines := strings.Split(stdout, "\n")
477
	for _, line := range lines {
478
		fields := strings.Fields(line)
479
		if len(fields) == 0 {
480
			break
481
		}
482
		if len(fields) != 3 {
483
			return containers, fmt.Errorf("Unknown format: %s", line)
484
		}
485
		containers = append(containers, config.Container{
486
			ContainerID: fields[0],
487
			Name:        fields[1],
488
			Image:       fields[2],
489
		})
490
	}
491
	return
492
}
493
494
func (l *base) parseLxdPs(stdout string) (containers []config.Container, err error) {
495
	lines := strings.Split(stdout, "\n")
496
	for i, line := range lines[3:] {
497
		if i%2 == 1 {
498
			continue
499
		}
500
		fields := strings.Fields(strings.Replace(line, "|", " ", -1))
501
		if len(fields) == 0 {
502
			break
503
		}
504
		if len(fields) != 1 {
505
			return containers, fmt.Errorf("Unknown format: %s", line)
506
		}
507
		containers = append(containers, config.Container{
508
			ContainerID: fields[0],
509
			Name:        fields[0],
510
		})
511
	}
512
	return
513
}
514
515
func (l *base) parseLxcPs(stdout string) (containers []config.Container, err error) {
516
	lines := strings.Split(stdout, "\n")
517
	for _, line := range lines {
518
		fields := strings.Fields(line)
519
		if len(fields) == 0 {
520
			break
521
		}
522
		containers = append(containers, config.Container{
523
			ContainerID: fields[0],
524
			Name:        fields[0],
525
		})
526
	}
527
	return
528
}
529
530
// ip executes ip command and returns IP addresses
531
func (l *base) ip() ([]string, []string, error) {
532
	// e.g.
533
	// 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000\    link/ether 52:54:00:2a:86:4c brd ff:ff:ff:ff:ff:ff
534
	// 2: eth0    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
535
	// 2: eth0    inet6 fe80::5054:ff:fe2a:864c/64 scope link \       valid_lft forever preferred_lft forever
536
	r := l.exec("/sbin/ip -o addr", noSudo)
537
	if !r.isSuccess() {
538
		return nil, nil, fmt.Errorf("Failed to detect IP address: %v", r)
539
	}
540
	ipv4Addrs, ipv6Addrs := l.parseIP(r.Stdout)
541
	return ipv4Addrs, ipv6Addrs, nil
542
}
543
544
// parseIP parses the results of ip command
545
func (l *base) parseIP(stdout string) (ipv4Addrs []string, ipv6Addrs []string) {
546
	lines := strings.Split(stdout, "\n")
547
	for _, line := range lines {
548
		fields := strings.Fields(line)
549
		if len(fields) < 4 {
550
			continue
551
		}
552
		ip, _, err := net.ParseCIDR(fields[3])
553
		if err != nil {
554
			continue
555
		}
556
		if !ip.IsGlobalUnicast() {
557
			continue
558
		}
559
		if ipv4 := ip.To4(); ipv4 != nil {
560
			ipv4Addrs = append(ipv4Addrs, ipv4.String())
561
		} else {
562
			ipv6Addrs = append(ipv6Addrs, ip.String())
563
		}
564
	}
565
	return
566
}
567
568
func (l *base) detectPlatform() {
569
	if l.getServerInfo().Mode.IsOffline() {
570
		l.setPlatform(models.Platform{Name: "unknown"})
571
		return
572
	}
573
	ok, instanceID, err := l.detectRunningOnAws()
574
	if err != nil {
575
		l.setPlatform(models.Platform{Name: "other"})
576
		return
577
	}
578
	if ok {
579
		l.setPlatform(models.Platform{
580
			Name:       "aws",
581
			InstanceID: instanceID,
582
		})
583
		return
584
	}
585
586
	//TODO Azure, GCP...
587
	l.setPlatform(models.Platform{Name: "other"})
588
	return
589
}
590
591
func (l *base) detectRunningOnAws() (ok bool, instanceID string, err error) {
592
	if r := l.exec("type curl", noSudo); r.isSuccess() {
593
		cmd := "curl --max-time 1 --noproxy 169.254.169.254 http://169.254.169.254/latest/meta-data/instance-id"
594
		r := l.exec(cmd, noSudo)
595
		if r.isSuccess() {
596
			id := strings.TrimSpace(r.Stdout)
597
			if !l.isAwsInstanceID(id) {
598
				return false, "", nil
599
			}
600
			return true, id, nil
601
		}
602
603
		switch r.ExitStatus {
604
		case 28, 7:
605
			// Not running on AWS
606
			//  7   Failed to connect to host.
607
			// 28  operation timeout.
608
			return false, "", nil
609
		}
610
	}
611
612
	if r := l.exec("type wget", noSudo); r.isSuccess() {
613
		cmd := "wget --tries=3 --timeout=1 --no-proxy -q -O - http://169.254.169.254/latest/meta-data/instance-id"
614
		r := l.exec(cmd, noSudo)
615
		if r.isSuccess() {
616
			id := strings.TrimSpace(r.Stdout)
617
			if !l.isAwsInstanceID(id) {
618
				return false, "", nil
619
			}
620
			return true, id, nil
621
		}
622
623
		switch r.ExitStatus {
624
		case 4, 8:
625
			// Not running on AWS
626
			// 4   Network failure
627
			// 8   Server issued an error response.
628
			return false, "", nil
629
		}
630
	}
631
	return false, "", fmt.Errorf(
632
		"Failed to curl or wget to AWS instance metadata on %s. container: %s",
633
		l.ServerInfo.ServerName, l.ServerInfo.Container.Name)
634
}
635
636
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html
637
var awsInstanceIDPattern = regexp.MustCompile(`^i-[0-9a-f]+$`)
638
639
func (l *base) isAwsInstanceID(str string) bool {
640
	return awsInstanceIDPattern.MatchString(str)
641
}
642
643
func (l *base) convertToModel() models.ScanResult {
644
	ctype := l.ServerInfo.ContainerType
645
	if l.ServerInfo.Container.ContainerID != "" && ctype == "" {
646
		ctype = "docker"
647
	}
648
	container := models.Container{
649
		ContainerID: l.ServerInfo.Container.ContainerID,
650
		Name:        l.ServerInfo.Container.Name,
651
		Image:       l.ServerInfo.Container.Image,
652
		Type:        ctype,
653
	}
654
655
	errs := []string{}
656
	for _, e := range l.errs {
657
		errs = append(errs, fmt.Sprintf("%s", e))
658
	}
659
660
	return models.ScanResult{
661
		JSONVersion:   models.JSONVersion,
662
		ServerName:    l.ServerInfo.ServerName,
663
		ScannedAt:     time.Now(),
664
		ScanMode:      l.ServerInfo.Mode.String(),
665
		Family:        l.Distro.Family,
666
		Release:       l.Distro.Release,
667
		Container:     container,
668
		Platform:      l.Platform,
669
		IPv4Addrs:     l.ServerInfo.IPv4Addrs,
670
		IPv6Addrs:     l.ServerInfo.IPv6Addrs,
671
		ScannedCves:   l.VulnInfos,
672
		RunningKernel: l.Kernel,
673
		Packages:      l.Packages,
674
		SrcPackages:   l.SrcPackages,
675
		Optional:      l.ServerInfo.Optional,
676
		Errors:        errs,
677
	}
678
}
679
680
func (l *base) setErrs(errs []error) {
681
	l.errs = errs
682
}
683
684
func (l *base) getErrs() []error {
685
	return l.errs
686
}
687
688
const (
689
	systemd  = "systemd"
690
	upstart  = "upstart"
691
	sysVinit = "init"
692
)
693
694
// https://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
695
func (l *base) detectInitSystem() (string, error) {
696
	var f func(string) (string, error)
697
	f = func(cmd string) (string, error) {
698
		r := l.exec(cmd, sudo)
699
		if !r.isSuccess() {
700
			return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
701
		}
702
		scanner := bufio.NewScanner(strings.NewReader(r.Stdout))
703
		scanner.Scan()
704
		line := strings.TrimSpace(scanner.Text())
705
		if strings.Contains(line, "systemd") {
706
			return systemd, nil
707
		} else if strings.Contains(line, "upstart") {
708
			return upstart, nil
709
		} else if strings.Contains(line, "File: ‘/proc/1/exe’ -> ‘/sbin/init’") ||
710
			strings.Contains(line, "File: `/proc/1/exe' -> `/sbin/init'") {
711
			return f("stat /sbin/init")
712
		} else if line == "File: ‘/sbin/init’" ||
713
			line == "File: `/sbin/init'" {
714
			r := l.exec("/sbin/init --version", noSudo)
715
			if r.isSuccess() {
716
				if strings.Contains(r.Stdout, "upstart") {
717
					return upstart, nil
718
				}
719
			}
720
			return sysVinit, nil
721
		}
722
		return "", fmt.Errorf("Failed to detect a init system: %s", line)
723
	}
724
	return f("stat /proc/1/exe")
725
}
726
727
func (l *base) detectServiceName(pid string) (string, error) {
728
	cmd := fmt.Sprintf("systemctl status --quiet --no-pager %s", pid)
729
	r := l.exec(cmd, noSudo)
730
	if !r.isSuccess() {
731
		return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
732
	}
733
	return l.parseSystemctlStatus(r.Stdout), nil
734
}
735
736
func (l *base) parseSystemctlStatus(stdout string) string {
737
	scanner := bufio.NewScanner(strings.NewReader(stdout))
738
	scanner.Scan()
739
	line := scanner.Text()
740
	ss := strings.Fields(line)
741
	if len(ss) < 2 || strings.HasPrefix(line, "Failed to get unit for PID") {
742
		return ""
743
	}
744
	return ss[1]
745
}
746