-
Notifications
You must be signed in to change notification settings - Fork 211
/
create.go
783 lines (626 loc) · 19.9 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
/*
* Copyright © 2019 – 2023 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/containers/toolbox/pkg/podman"
"github.com/containers/toolbox/pkg/shell"
"github.com/containers/toolbox/pkg/skopeo"
"github.com/containers/toolbox/pkg/utils"
"github.com/docker/go-units"
"github.com/godbus/dbus/v5"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/term"
)
const (
alpha = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
num = `0123456789`
alphanum = alpha + num
)
var (
createFlags struct {
authFile string
container string
distro string
image string
release string
}
createToolboxShMounts = []struct {
containerPath string
source string
}{
{"/etc/profile.d/toolbox.sh", "/etc/profile.d/toolbox.sh"},
{"/etc/profile.d/toolbox.sh", "/usr/share/profile.d/toolbox.sh"},
}
)
var createCmd = &cobra.Command{
Use: "create",
Short: "Create a new toolbox container",
RunE: create,
ValidArgsFunction: completionEmpty,
}
func init() {
flags := createCmd.Flags()
flags.StringVar(&createFlags.authFile,
"authfile",
"",
"Path to a file with credentials for authenticating to the registry for private images")
flags.StringVarP(&createFlags.container,
"container",
"c",
"",
"Assign a different name to the toolbox container")
flags.StringVarP(&createFlags.distro,
"distro",
"d",
"",
"Create a toolbox container for a different operating system distribution than the host")
flags.StringVarP(&createFlags.image,
"image",
"i",
"",
"Change the name of the base image used to create the toolbox container")
flags.StringVarP(&createFlags.release,
"release",
"r",
"",
"Create a toolbox container for a different operating system release than the host")
createCmd.SetHelpFunc(createHelp)
if err := createCmd.RegisterFlagCompletionFunc("distro", completionDistroNames); err != nil {
panicMsg := fmt.Sprintf("failed to register flag completion function: %v", err)
panic(panicMsg)
}
if err := createCmd.RegisterFlagCompletionFunc("image", completionImageNames); err != nil {
panicMsg := fmt.Sprintf("failed to register flag completion function: %v", err)
panic(panicMsg)
}
rootCmd.AddCommand(createCmd)
}
func create(cmd *cobra.Command, args []string) error {
if utils.IsInsideContainer() {
if !utils.IsInsideToolboxContainer() {
return errors.New("this is not a toolbox container")
}
if _, err := utils.ForwardToHost(); err != nil {
return err
}
return nil
}
if cmd.Flag("distro").Changed && cmd.Flag("image").Changed {
var builder strings.Builder
fmt.Fprintf(&builder, "options --distro and --image cannot be used together\n")
fmt.Fprintf(&builder, "Run '%s --help' for usage.", executableBase)
errMsg := builder.String()
return errors.New(errMsg)
}
if cmd.Flag("image").Changed && cmd.Flag("release").Changed {
var builder strings.Builder
fmt.Fprintf(&builder, "options --image and --release cannot be used together\n")
fmt.Fprintf(&builder, "Run '%s --help' for usage.", executableBase)
errMsg := builder.String()
return errors.New(errMsg)
}
if cmd.Flag("authfile").Changed {
if !utils.PathExists(createFlags.authFile) {
var builder strings.Builder
fmt.Fprintf(&builder, "file %s not found\n", createFlags.authFile)
fmt.Fprintf(&builder, "'podman login' can be used to create the file.\n")
fmt.Fprintf(&builder, "Run '%s --help' for usage.", executableBase)
errMsg := builder.String()
return errors.New(errMsg)
}
}
var container string
var containerArg string
if len(args) != 0 {
container = args[0]
containerArg = "CONTAINER"
} else if createFlags.container != "" {
container = createFlags.container
containerArg = "--container"
}
container, image, release, err := resolveContainerAndImageNames(container,
containerArg,
createFlags.distro,
createFlags.image,
createFlags.release)
if err != nil {
return err
}
if err := createContainer(container, image, release, createFlags.authFile, true); err != nil {
return err
}
return nil
}
func createContainer(container, image, release, authFile string, showCommandToEnter bool) error {
if container == "" {
panic("container not specified")
}
if image == "" {
panic("image not specified")
}
if release == "" {
panic("release not specified")
}
enterCommand := getEnterCommand(container)
logrus.Debugf("Checking if container %s already exists", container)
if exists, _ := podman.ContainerExists(container); exists {
var builder strings.Builder
fmt.Fprintf(&builder, "container %s already exists\n", container)
fmt.Fprintf(&builder, "Enter with: %s\n", enterCommand)
fmt.Fprintf(&builder, "Run '%s --help' for usage.", executableBase)
errMsg := builder.String()
return errors.New(errMsg)
}
pulled, err := pullImage(image, release, authFile)
if err != nil {
return err
}
if !pulled {
return nil
}
imageFull, err := getFullyQualifiedImageFromRepoTags(image)
if err != nil {
return err
}
toolboxPath := os.Getenv("TOOLBOX_PATH")
toolboxPathEnvArg := "TOOLBOX_PATH=" + toolboxPath
toolboxPathMountArg := toolboxPath + ":/usr/bin/toolbox:ro"
var runtimeDirectory string
var xdgRuntimeDirEnv []string
if currentUser.Uid == "0" {
runtimeDirectory, err = utils.GetRuntimeDirectory(currentUser)
if err != nil {
return err
}
} else {
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
xdgRuntimeDirEnvArg := "XDG_RUNTIME_DIR=" + xdgRuntimeDir
xdgRuntimeDirEnv = []string{"--env", xdgRuntimeDirEnvArg}
runtimeDirectory = xdgRuntimeDir
}
runtimeDirectoryMountArg := runtimeDirectory + ":" + runtimeDirectory
logrus.Debug("Checking if 'podman create' supports '--mount type=devpts'")
var devPtsMount []string
if podman.CheckVersion("2.1.0") {
logrus.Debug("'podman create' supports '--mount type=devpts'")
devPtsMount = []string{"--mount", "type=devpts,destination=/dev/pts"}
}
var usernsArg string
if currentUser.Uid == "0" {
usernsArg = "host"
} else {
usernsArg = "keep-id"
}
dbusSystemSocket, err := getDBusSystemSocket()
if err != nil {
return err
}
dbusSystemSocketMountArg := dbusSystemSocket + ":" + dbusSystemSocket
homeDirEvaled, err := filepath.EvalSymlinks(currentUser.HomeDir)
if err != nil {
return fmt.Errorf("failed to canonicalize %s", currentUser.HomeDir)
}
logrus.Debugf("%s canonicalized to %s", currentUser.HomeDir, homeDirEvaled)
homeDirMountArg := homeDirEvaled + ":" + homeDirEvaled + ":rslave"
var avahiSocketMount []string
avahiSocket, err := getServiceSocket("Avahi", "avahi-daemon.socket")
if err != nil {
logrus.Debug(err)
}
if avahiSocket != "" {
avahiSocketMountArg := avahiSocket + ":" + avahiSocket
avahiSocketMount = []string{"--volume", avahiSocketMountArg}
}
var kcmSocketMount []string
kcmSocket, err := getServiceSocket("KCM", "sssd-kcm.socket")
if err != nil {
logrus.Debug(err)
}
if kcmSocket != "" {
kcmSocketMountArg := kcmSocket + ":" + kcmSocket
kcmSocketMount = []string{"--volume", kcmSocketMountArg}
}
var pcscSocketMount []string
pcscSocket, err := getServiceSocket("pcsc", "pcscd.socket")
if err != nil {
logrus.Debug(err)
}
if pcscSocket != "" {
pcscSocketMountArg := pcscSocket + ":" + pcscSocket
pcscSocketMount = []string{"--volume", pcscSocketMountArg}
}
var mediaLink []string
var mediaMount []string
if utils.PathExists("/media") {
logrus.Debug("Checking if /media is a symbolic link to /run/media")
mediaPath, _ := filepath.EvalSymlinks("/media")
if mediaPath == "/run/media" {
logrus.Debug("/media is a symbolic link to /run/media")
mediaLink = []string{"--media-link"}
} else {
mediaMount = []string{"--volume", "/media:/media:rslave"}
}
}
var mntLink []string
var mntMount []string
if utils.PathExists("/mnt") {
logrus.Debug("Checking if /mnt is a symbolic link to /var/mnt")
mntPath, _ := filepath.EvalSymlinks("/mnt")
if mntPath == "/var/mnt" {
logrus.Debug("/mnt is a symbolic link to /var/mnt")
mntLink = []string{"--mnt-link"}
} else {
mntMount = []string{"--volume", "/mnt:/mnt:rslave"}
}
}
var runMediaMount []string
if utils.PathExists("/run/media") {
runMediaMount = []string{"--volume", "/run/media:/run/media:rslave"}
}
logrus.Debug("Looking up toolbox.sh")
var toolboxShMount []string
for _, mount := range createToolboxShMounts {
if utils.PathExists(mount.source) {
logrus.Debugf("Found %s", mount.source)
toolboxShMountArg := mount.source + ":" + mount.containerPath + ":ro"
toolboxShMount = []string{"--volume", toolboxShMountArg}
break
}
}
logrus.Debug("Checking if /home is a symbolic link to /var/home")
var slashHomeLink []string
slashHomeEvaled, _ := filepath.EvalSymlinks("/home")
if slashHomeEvaled == "/var/home" {
logrus.Debug("/home is a symbolic link to /var/home")
slashHomeLink = []string{"--home-link"}
}
logLevelString := podman.LogLevel.String()
userShell := os.Getenv("SHELL")
if userShell == "" {
return errors.New("failed to get the current user's default shell")
}
entryPoint := []string{
"toolbox", "--log-level", "debug",
"init-container",
"--gid", currentUser.Gid,
"--home", currentUser.HomeDir,
"--shell", userShell,
"--uid", currentUser.Uid,
"--user", currentUser.Username,
}
entryPoint = append(entryPoint, slashHomeLink...)
entryPoint = append(entryPoint, mediaLink...)
entryPoint = append(entryPoint, mntLink...)
createArgs := []string{
"--log-level", logLevelString,
"create",
"--cgroupns", "host",
"--dns", "none",
"--env", toolboxPathEnvArg,
}
createArgs = append(createArgs, xdgRuntimeDirEnv...)
createArgs = append(createArgs, []string{
"--hostname", "toolbox",
"--ipc", "host",
"--label", "com.github.containers.toolbox=true",
}...)
createArgs = append(createArgs, devPtsMount...)
createArgs = append(createArgs, []string{
"--name", container,
"--network", "host",
"--no-hosts",
"--pid", "host",
"--privileged",
"--security-opt", "label=disable",
"--ulimit", "host",
"--userns", usernsArg,
"--user", "root:root",
"--volume", "/:/run/host:rslave",
"--volume", "/dev:/dev:rslave",
"--volume", dbusSystemSocketMountArg,
"--volume", homeDirMountArg,
"--volume", toolboxPathMountArg,
"--volume", runtimeDirectoryMountArg,
}...)
createArgs = append(createArgs, avahiSocketMount...)
createArgs = append(createArgs, kcmSocketMount...)
createArgs = append(createArgs, mediaMount...)
createArgs = append(createArgs, mntMount...)
createArgs = append(createArgs, pcscSocketMount...)
createArgs = append(createArgs, runMediaMount...)
createArgs = append(createArgs, toolboxShMount...)
createArgs = append(createArgs, []string{
imageFull,
}...)
createArgs = append(createArgs, entryPoint...)
logrus.Debugf("Creating container %s:", container)
logrus.Debug("podman")
for _, arg := range createArgs {
logrus.Debugf("%s", arg)
}
s := spinner.New(spinner.CharSets[9], 500*time.Millisecond)
stdoutFd := os.Stdout.Fd()
stdoutFdInt := int(stdoutFd)
if logLevel := logrus.GetLevel(); logLevel < logrus.DebugLevel && term.IsTerminal(stdoutFdInt) {
s.Prefix = fmt.Sprintf("Creating container %s: ", container)
s.Writer = os.Stdout
s.Start()
defer s.Stop()
}
if err := shell.Run("podman", nil, nil, nil, createArgs...); err != nil {
return fmt.Errorf("failed to create container %s", container)
}
// The spinner must be stopped before showing the 'enter' hint below.
s.Stop()
if showCommandToEnter {
fmt.Printf("Created container: %s\n", container)
fmt.Printf("Enter with: %s\n", enterCommand)
}
return nil
}
func createHelp(cmd *cobra.Command, args []string) {
if utils.IsInsideContainer() {
if !utils.IsInsideToolboxContainer() {
fmt.Fprintf(os.Stderr, "Error: this is not a toolbox container\n")
return
}
if _, err := utils.ForwardToHost(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
return
}
if err := showManual("toolbox-create"); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
}
func getDBusSystemSocket() (string, error) {
logrus.Debug("Resolving path to the D-Bus system socket")
address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
if address == "" {
address = "unix:path=/var/run/dbus/system_bus_socket"
}
addressSplit := strings.Split(address, "=")
if len(addressSplit) != 2 {
return "", errors.New("failed to get the path to the D-Bus system socket")
}
path := addressSplit[1]
pathEvaled, err := filepath.EvalSymlinks(path)
if err != nil {
logrus.Debugf("Resolving path to the D-Bus system socket: failed to evaluate symbolic links in %s: %s",
path,
err)
return "", errors.New("failed to resolve the path to the D-Bus system socket")
}
return pathEvaled, nil
}
func getEnterCommand(container string) string {
var enterCommand string
switch container {
case utils.ContainerNameDefault:
enterCommand = fmt.Sprintf("%s enter", executableBase)
default:
enterCommand = fmt.Sprintf("%s enter %s", executableBase, container)
}
return enterCommand
}
func getFullyQualifiedImageFromRepoTags(image string) (string, error) {
logrus.Debugf("Resolving fully qualified name for image %s from RepoTags", image)
var imageFull string
if utils.ImageReferenceHasDomain(image) {
imageFull = image
} else {
info, err := podman.Inspect("image", image)
if err != nil {
return "", fmt.Errorf("failed to inspect image %s", image)
}
if info["RepoTags"] == nil {
return "", fmt.Errorf("missing RepoTag for image %s", image)
}
repoTags := info["RepoTags"].([]interface{})
if len(repoTags) == 0 {
return "", fmt.Errorf("empty RepoTag for image %s", image)
}
for _, repoTag := range repoTags {
repoTagString := repoTag.(string)
tag := utils.ImageReferenceGetTag(repoTagString)
if tag != "latest" {
imageFull = repoTagString
break
}
}
if imageFull == "" {
imageFull = repoTags[0].(string)
}
}
logrus.Debugf("Resolved image %s to %s", image, imageFull)
return imageFull, nil
}
func getImageSizeFromRegistry(imageFull string) (string, error) {
image, err := skopeo.Inspect(imageFull)
if err != nil {
return "", err
}
if image.LayersData == nil {
return "", errors.New("'skopeo inspect' did not have LayersData")
}
var imageSizeFloat float64
for _, layer := range image.LayersData {
if layerSize, err := layer.Size.Float64(); err != nil {
return "", err
} else {
imageSizeFloat += layerSize
}
}
imageSizeHuman := units.HumanSize(imageSizeFloat)
return imageSizeHuman, nil
}
func getServiceSocket(serviceName string, unitName string) (string, error) {
logrus.Debugf("Resolving path to the %s socket", serviceName)
connection, err := dbus.SystemBus()
if err != nil {
logrus.Debugf("Resolving path to the %s socket: failed to connect to the D-Bus system instance: %s",
serviceName,
err)
return "", errors.New("failed to connect to the D-Bus system instance")
}
unitNameEscaped := systemdPathBusEscape(unitName)
unitPath := dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + unitNameEscaped)
unit := connection.Object("org.freedesktop.systemd1", unitPath)
call := unit.Call("org.freedesktop.DBus.Properties.GetAll", 0, "")
var result map[string]dbus.Variant
err = call.Store(&result)
if err != nil {
logrus.Debugf("Resolving path to the %s socket: failed to get the properties of %s: %s",
serviceName,
unitName,
err)
return "", fmt.Errorf("failed to get the properties of %s", unitName)
}
listenVariant, listenFound := result["Listen"]
if !listenFound {
return "", fmt.Errorf("failed to find the Listen property of %s", unitName)
}
listenVariantSignature := listenVariant.Signature().String()
if listenVariantSignature != "aav" {
return "", errors.New("unknown reply from org.freedesktop.DBus.Properties.GetAll")
}
listenValue := listenVariant.Value()
sockets := listenValue.([][]interface{})
for _, socket := range sockets {
if socket[0] == "Stream" {
path := socket[1].(string)
if !strings.HasPrefix(path, "/") {
continue
}
pathEvaled, err := filepath.EvalSymlinks(path)
if err != nil {
continue
}
return pathEvaled, nil
}
}
return "", fmt.Errorf("failed to find a SOCK_STREAM socket for %s", unitName)
}
func pullImage(image, release, authFile string) (bool, error) {
if ok := utils.ImageReferenceCanBeID(image); ok {
logrus.Debugf("Looking up image %s", image)
if _, err := podman.ImageExists(image); err == nil {
return true, nil
}
}
hasDomain := utils.ImageReferenceHasDomain(image)
if !hasDomain {
imageLocal := "localhost/" + image
logrus.Debugf("Looking up image %s", imageLocal)
if _, err := podman.ImageExists(imageLocal); err == nil {
return true, nil
}
}
var imageFull string
if hasDomain {
imageFull = image
} else {
var err error
imageFull, err = utils.GetFullyQualifiedImageFromDistros(image, release)
if err != nil {
return false, fmt.Errorf("image %s not found in local storage and known registries", image)
}
}
logrus.Debugf("Looking up image %s", imageFull)
if _, err := podman.ImageExists(imageFull); err == nil {
return true, nil
}
domain := utils.ImageReferenceGetDomain(imageFull)
if domain == "" {
panicMsg := fmt.Sprintf("failed to get domain from %s", imageFull)
panic(panicMsg)
}
promptForDownload := true
var shouldPullImage bool
if rootFlags.assumeYes || domain == "localhost" {
promptForDownload = false
shouldPullImage = true
}
if promptForDownload {
fmt.Println("Image required to create toolbox container.")
var prompt string
if imageSize, err := getImageSizeFromRegistry(imageFull); err != nil {
logrus.Debugf("Getting image size failed: %s", err)
prompt = fmt.Sprintf("Download %s? [y/N]:", imageFull)
} else {
prompt = fmt.Sprintf("Download %s (%s)? [y/N]:", imageFull, imageSize)
}
shouldPullImage = askForConfirmation(prompt)
}
if !shouldPullImage {
return false, nil
}
logrus.Debugf("Pulling image %s", imageFull)
stdoutFd := os.Stdout.Fd()
stdoutFdInt := int(stdoutFd)
if logLevel := logrus.GetLevel(); logLevel < logrus.DebugLevel && term.IsTerminal(stdoutFdInt) {
s := spinner.New(spinner.CharSets[9], 500*time.Millisecond)
s.Prefix = fmt.Sprintf("Pulling %s: ", imageFull)
s.Writer = os.Stdout
s.Start()
defer s.Stop()
}
if err := podman.Pull(imageFull, authFile); err != nil {
var builder strings.Builder
fmt.Fprintf(&builder, "failed to pull image %s\n", imageFull)
fmt.Fprintf(&builder, "If it was a private image, log in with: podman login %s\n", domain)
fmt.Fprintf(&builder, "Use '%s --verbose ...' for further details.", executableBase)
errMsg := builder.String()
return false, errors.New(errMsg)
}
return true, nil
}
// systemdNeedsEscape checks whether a byte in a potential dbus ObjectPath needs to be escaped
func systemdNeedsEscape(i int, b byte) bool {
// Escape everything that is not a-z-A-Z-0-9
// Also escape 0-9 if it's the first character
return strings.IndexByte(alphanum, b) == -1 ||
(i == 0 && strings.IndexByte(num, b) != -1)
}
// systemdPathBusEscape sanitizes a constituent string of a dbus ObjectPath using the
// rules that systemd uses for serializing special characters.
func systemdPathBusEscape(path string) string {
// Special case the empty string
if len(path) == 0 {
return "_"
}
n := []byte{}
for i := 0; i < len(path); i++ {
c := path[i]
if systemdNeedsEscape(i, c) {
e := fmt.Sprintf("_%x", c)
n = append(n, []byte(e)...)
} else {
n = append(n, c)
}
}
return string(n)
}