forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfo.go
More file actions
2206 lines (1893 loc) · 68.8 KB
/
Copy pathinfo.go
File metadata and controls
2206 lines (1893 loc) · 68.8 KB
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package snap
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/snapcore/snapd/desktop/desktopentry"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/metautil"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/sys"
"github.com/snapcore/snapd/snap/integrity"
"github.com/snapcore/snapd/snap/naming"
"github.com/snapcore/snapd/snapdtool"
"github.com/snapcore/snapd/strutil"
"github.com/snapcore/snapd/timeout"
)
// ContainerPlaceInfo offers all the information about where a container (which
// can be a snap or a component) and its data are located and exposed in the
// filesystem.
type ContainerPlaceInfo interface {
// ContainerName returns the name of the container, which is part of the
// name of the backing file (for snaps this is the instance name).
ContainerName() string
// Filename returns the name of the container with the revision
// number, as used on the filesystem.
Filename() string
// MountDir returns the base directory of the container.
MountDir() string
// MountFile returns the path where the container file that is mounted is
// installed.
MountFile() string
// MountDescription is the value for the mount unit Description field.
MountDescription() string
// DmVerityFile returns the name of the dm-verity hash file computed by the container's name
// and the digest.
// If the container doesn't contain integrity data or contains integrity data but not of type
// "dm-verity", this will return an error.
DmVerityFile() (string, error)
// DmVerityDigest returns the dm-verity digest of the integrity data associated with the container.
// If the container doesn't contain integrity data or contains integrity data but not of type
// "dm-verity", this will return an error.
DmVerityDigest() (string, error)
}
// PlaceInfo offers all the information about where a snap and its data are
// located and exposed in the filesystem.
type PlaceInfo interface {
// InstanceName returns the name of the snap decorated with instance
// key, if any.
InstanceName() string
// SnapName returns the name of the snap.
SnapName() string
// SnapRevision returns the revision of the snap.
SnapRevision() Revision
// Filename returns the name of the snap with the revision
// number, as used on the filesystem.
Filename() string
// MountDir returns the base directory of the snap.
MountDir() string
// MountFile returns the path where the snap file that is mounted is
// installed.
MountFile() string
// HooksDir returns the directory containing the snap's hooks.
HooksDir() string
// DataDir returns the data directory of the snap.
DataDir() string
// UserDataDir returns the per user data directory of the snap.
UserDataDir(home string, opts *dirs.SnapDirOptions) string
// CommonDataDir returns the data directory common across revisions of the
// snap.
CommonDataDir() string
// CommonDataSaveDir returns the save data directory common across revisions
// of the snap.
CommonDataSaveDir() string
// UserCommonDataDir returns the per user data directory common across
// revisions of the snap.
UserCommonDataDir(home string, opts *dirs.SnapDirOptions) string
// UserXdgRuntimeDir returns the per user XDG_RUNTIME_DIR directory
UserXdgRuntimeDir(userID sys.UserID) string
// DataHomeDirs returns a slice of globs that match all per user data directories
// of a snap.
DataHomeDirs(opts *dirs.SnapDirOptions) []string
// CommonDataHomeDirs returns a slice of globs that match all per user data
// directories common across revisions of the snap.
CommonDataHomeDirs(opts *dirs.SnapDirOptions) []string
// XdgRuntimeDirs returns a glob that matches all XDG_RUNTIME_DIR
// directories for all users of the snap.
XdgRuntimeDirs() string
// UserExposedHomeDir returns the snap's new home directory under ~/Snap.
UserExposedHomeDir(home string) string
// BinaryNameGlobs returns base name globs that matches all snap binaries.
BinaryNameGlobs() []string
}
// MinimalPlaceInfo returns a PlaceInfo with just the location information for a
// snap of the given instance name and revision.
func MinimalPlaceInfo(instanceName string, revision Revision) PlaceInfo {
storeName, instanceKey := SplitInstanceName(instanceName)
return &Info{SideInfo: SideInfo{RealName: storeName, Revision: revision}, InstanceKey: instanceKey}
}
// MinimalSnapContainerPlaceInfo returns a ContainerPlaceInfo with just the location
// information for a snap of the given instance name and revision.
func MinimalSnapContainerPlaceInfo(instanceName string, revision Revision) ContainerPlaceInfo {
storeName, instanceKey := SplitInstanceName(instanceName)
return &Info{SideInfo: SideInfo{RealName: storeName, Revision: revision}, InstanceKey: instanceKey}
}
// ParsePlaceInfoFromSnapFileName returns a PlaceInfo with just the location
// information for a snap of file name, failing if the snap file name is invalid
// This explicitly does not support filenames with instance names in them
func ParsePlaceInfoFromSnapFileName(sn string) (PlaceInfo, error) {
if sn == "" {
return nil, fmt.Errorf("empty snap file name")
}
if strings.Count(sn, "_") > 1 {
// too many "_", probably has an instance key in the filename like in
// snap-name_key_23.snap
return nil, fmt.Errorf("too many '_' in snap file name")
}
idx := strings.IndexByte(sn, '_')
switch {
case idx < 0:
return nil, fmt.Errorf("snap file name %q has invalid format (missing '_')", sn)
case idx == 0:
return nil, fmt.Errorf("snap file name %q has invalid format (no snap name before '_')", sn)
}
// ensure that _ is not the last element
name := sn[:idx]
revnoNSuffix := sn[idx+1:]
rev, err := ParseRevision(strings.TrimSuffix(revnoNSuffix, ".snap"))
if err != nil {
return nil, fmt.Errorf("cannot parse revision in snap file name %q: %v", sn, err)
}
return &Info{SideInfo: SideInfo{RealName: name, Revision: rev}}, nil
}
// BaseDir returns the system level directory of given snap.
func BaseDir(name string) string {
return filepath.Join(dirs.SnapMountDir, name)
}
// MountDir returns the base directory where it gets mounted of the snap with
// the given name and revision.
func MountDir(name string, revision Revision) string {
return filepath.Join(BaseDir(name), revision.String())
}
// ComponentMountDir returns the directory where a component gets mounted, which
// will be of the form:
// /snaps/<snap_instance>/components/mnt/<component_name>/<component_revision>
func ComponentMountDir(componentName string, compRevision Revision, snapInstance string) string {
return filepath.Join(ComponentsBaseDir(snapInstance), "mnt", componentName, compRevision.String())
}
// MountFile returns the path where the snap file that is mounted is installed,
// using the default blob directory (dirs.SnapBlobDir).
func MountFile(name string, revision Revision) string {
return MountFileInDir(dirs.SnapBlobDir, name, revision)
}
// MountFileInDir returns the path where the snap file that is mounted is
// installed in a given directory.
func MountFileInDir(dir, name string, revision Revision) string {
return filepath.Join(dir, fmt.Sprintf("%s_%s.snap", name, revision))
}
// ScopedSecurityTag returns the snap-specific, scope specific, security tag.
func ScopedSecurityTag(snapName, scopeName, suffix string) string {
return fmt.Sprintf("snap.%s.%s.%s", snapName, scopeName, suffix)
}
// SecurityTag returns the snap-specific security tag.
func SecurityTag(snapName string) string {
return fmt.Sprintf("snap.%s", snapName)
}
// AppSecurityTag returns the application-specific security tag.
func AppSecurityTag(snapName, appName string) string {
return fmt.Sprintf("%s.%s", SecurityTag(snapName), appName)
}
// ComponentSecurityTag returns a snap component's hook-specific security tag.
func ComponentHookSecurityTag(snapInstance, componentName, hookName string) string {
return ScopedSecurityTag(fmt.Sprintf("%s+%s", snapInstance, componentName), "hook", hookName)
}
// HookSecurityTag returns the hook-specific security tag.
func HookSecurityTag(snapName, hookName string) string {
return ScopedSecurityTag(snapName, "hook", hookName)
}
// NoneSecurityTag returns the security tag for interfaces that
// are not associated to an app or hook in the snap.
func NoneSecurityTag(snapName, uniqueName string) string {
return ScopedSecurityTag(snapName, "none", uniqueName)
}
// BaseDataDir returns the base directory for snap data locations.
func BaseDataDir(name string) string {
return filepath.Join(dirs.SnapDataDir, name)
}
// DataDir returns the data directory for given snap name and revision. The name
// can be
// either a snap name or snap instance name.
func DataDir(name string, revision Revision) string {
return filepath.Join(BaseDataDir(name), revision.String())
}
// CommonDataSaveDir returns a core-specific save directory meant to provide access
// to a per-snap storage that is preserved across factory reset.
func CommonDataSaveDir(name string) string {
return filepath.Join(dirs.SnapDataSaveDir, name)
}
// CommonDataDir returns the common data directory for given snap name. The name
// can be either a snap name or snap instance name.
func CommonDataDir(name string) string {
return filepath.Join(dirs.SnapDataDir, name, "common")
}
// HooksDir returns the directory containing the snap's hooks for given snap
// name. The name can be either a snap name or snap instance name.
func HooksDir(name string, revision Revision) string {
return filepath.Join(MountDir(name, revision), "meta", "hooks")
}
// ComponentHooksDir returns the directory containing the component's hooks for
// the given component hook name. The provided snap name can be either a snap
// name or snap instance name.
func ComponentHooksDir(componentName string, compRevision Revision, snapInstance string) string {
return filepath.Join(ComponentMountDir(componentName, compRevision, snapInstance), "meta", "hooks")
}
func snapDataDir(opts *dirs.SnapDirOptions) string {
if opts == nil {
opts = &dirs.SnapDirOptions{}
}
if opts.HiddenSnapDataDir {
return dirs.HiddenSnapDataHomeDir
}
return dirs.UserHomeSnapDir
}
// BaseDataHomeDirs returns the per user base data directories of the snap across multiple
// home directories.
func BaseDataHomeDirs(name string, opts *dirs.SnapDirOptions) []string {
var dataHomeGlob []string
for _, glob := range dirs.DataHomeGlobs(opts) {
dataHomeGlob = append(dataHomeGlob, filepath.Join(glob, name))
}
return dataHomeGlob
}
// UserDataDir returns the user-specific data directory for given snap name. The
// name can be either a snap name or snap instance name.
func UserDataDir(home string, name string, revision Revision, opts *dirs.SnapDirOptions) string {
return filepath.Join(home, snapDataDir(opts), name, revision.String())
}
// UserCommonDataDir returns the user-specific common data directory for given
// snap name. The name can be either a snap name or snap instance name.
func UserCommonDataDir(home string, name string, opts *dirs.SnapDirOptions) string {
return filepath.Join(home, snapDataDir(opts), name, "common")
}
// UserSnapDir returns the user-specific directory for given
// snap name. The name can be either a snap name or snap instance name.
func UserSnapDir(home string, name string, opts *dirs.SnapDirOptions) string {
return filepath.Join(home, snapDataDir(opts), name)
}
// UserExposedHomeDir returns the snap's directory in the exposed home dir.
func UserExposedHomeDir(home string, snapName string) string {
return filepath.Join(home, dirs.ExposedSnapHomeDir, snapName)
}
// UserXdgRuntimeDir returns the user-specific XDG_RUNTIME_DIR directory for
// given snap name. The name can be either a snap name or snap instance name.
func UserXdgRuntimeDir(euid sys.UserID, name string) string {
return filepath.Join(dirs.XdgRuntimeDirBase, fmt.Sprintf("%d/snap.%s", euid, name))
}
// SnapDir returns the user-specific snap directory.
func SnapDir(home string, opts *dirs.SnapDirOptions) string {
return filepath.Join(home, snapDataDir(opts))
}
// SideInfo holds snap metadata that is crucial for the tracking of
// snaps and for the working of the system offline and which is not
// included in snap.yaml or for which the store is the canonical
// source overriding snap.yaml content.
//
// It can be marshalled and will be stored in the system state for
// each currently installed snap revision so it needs to be evolved
// carefully.
//
// Information that can be taken directly from snap.yaml or that comes
// from the store but is not required for working offline should not
// end up in SideInfo.
type SideInfo struct {
RealName string `json:"name,omitempty"`
SnapID string `json:"snap-id"`
Revision Revision `json:"revision"`
Channel string `json:"channel,omitempty"`
EditedLinks map[string][]string `json:"links,omitempty"`
// subsumed by EditedLinks, by need to set for if we revert
// to old snapd
LegacyEditedContact string `json:"contact,omitempty"`
EditedTitle string `json:"title,omitempty"`
EditedSummary string `json:"summary,omitempty"`
EditedDescription string `json:"description,omitempty"`
Private bool `json:"private,omitempty"`
Paid bool `json:"paid,omitempty"`
}
// Info provides information about snaps.
type Info struct {
SuggestedName string
InstanceKey string
Version string
SnapType Type
Architectures []string
Assumes []string
OriginalTitle string
OriginalSummary string
OriginalDescription string
SnapProvenance string
Environment strutil.OrderedMap
LicenseAgreement string
LicenseVersion string
License string
Epoch Epoch
Base string
Confinement ConfinementType
Grade GradeType
Apps map[string]*AppInfo
LegacyAliases map[string]*AppInfo // FIXME: eventually drop this
Hooks map[string]*HookInfo
Plugs map[string]*PlugInfo
Slots map[string]*SlotInfo
Components map[string]*Component
// Plugs or slots with issues (they are not included in Plugs or Slots)
BadInterfaces map[string]string // slot or plug => message
// The information in all the remaining fields is not sourced from the snap
// blob itself.
SideInfo
// Broken marks whether the snap is broken and the reason.
Broken string
// The information in these fields is ephemeral, available only from the
// store or when read from a snap file.
DownloadInfo
Prices map[string]float64
MustBuy bool
Publisher StoreAccount
Media MediaInfos
// subsumed by EditedLinks but needed to handle information
// stored by old snapd
LegacyWebsite string
StoreURL string
// The flattended channel map with $track/$risk
Channels map[string]*ChannelSnapInfo
// The ordered list of tracks that contain channels
Tracks []string
Layout map[string]*Layout
// The list of common-ids from all apps of the snap
CommonIDs []string
// List of system users (usernames) this snap may use. The group of the same
// name must also exist.
SystemUsernames map[string]*SystemUsernameInfo
// OriginalLinks is a map links keys to link lists
OriginalLinks map[string][]string
// Categories this snap is in.
Categories []CategoryInfo
// IntegrityData available for this snap
IntegrityData *IntegrityDataInfo
}
// StoreAccount holds information about a store account, for example of snap
// publisher.
type StoreAccount struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display-name"`
Validation string `json:"validation,omitempty"`
}
// Layout describes a single element of the layout section.
type Layout struct {
Snap *Info
Path string `json:"path"`
Bind string `json:"bind,omitempty"`
BindFile string `json:"bind-file,omitempty"`
Type string `json:"type,omitempty"`
User string `json:"user,omitempty"`
Group string `json:"group,omitempty"`
Mode os.FileMode `json:"mode,omitempty"`
Symlink string `json:"symlink,omitempty"`
}
// String returns a simple textual representation of a layout.
func (l *Layout) String() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s: ", l.Path)
switch {
case l.Bind != "":
fmt.Fprintf(&buf, "bind %s", l.Bind)
case l.BindFile != "":
fmt.Fprintf(&buf, "bind-file %s", l.BindFile)
case l.Symlink != "":
fmt.Fprintf(&buf, "symlink %s", l.Symlink)
case l.Type != "":
fmt.Fprintf(&buf, "type %s", l.Type)
default:
fmt.Fprintf(&buf, "???")
}
if l.User != "root" && l.User != "" {
fmt.Fprintf(&buf, ", user: %s", l.User)
}
if l.Group != "root" && l.Group != "" {
fmt.Fprintf(&buf, ", group: %s", l.Group)
}
if l.Mode != 0755 {
fmt.Fprintf(&buf, ", mode: %#o", l.Mode)
}
return buf.String()
}
// ChannelSnapInfo is the minimum information that can be used to clearly
// distinguish different revisions of the same snap.
type ChannelSnapInfo struct {
Revision Revision `json:"revision"`
Confinement ConfinementType `json:"confinement"`
Version string `json:"version"`
Channel string `json:"channel"`
Epoch Epoch `json:"epoch"`
Size int64 `json:"size"`
ReleasedAt time.Time `json:"released-at"`
}
// Provenance returns the provenance of the snap, this is a label set
// e.g to distinguish snaps that are not expected to be processed by the global
// store. Constraints on this value are used to allow for delegated
// snap-revision signing.
// This returns naming.DefaultProvenance if no value is set explicitly
// in the snap metadata.
func (s *Info) Provenance() string {
if s.SnapProvenance == "" {
return naming.DefaultProvenance
}
return s.SnapProvenance
}
// InstanceName returns the blessed name of the snap decorated with instance
// key, if any.
func (s *Info) InstanceName() string {
return InstanceName(s.SnapName(), s.InstanceKey)
}
// ContainerName returns the name of the container, which is the instance name
// for snaps.
func (s *Info) ContainerName() string {
return s.InstanceName()
}
// SnapName returns the global blessed name of the snap.
func (s *Info) SnapName() string {
if s.RealName != "" {
return s.RealName
}
return s.SuggestedName
}
// Filename returns the name of the snap with the revision number,
// as used on the filesystem. This is the equivalent of
// filepath.Base(s.MountFile()).
func (s *Info) Filename() string {
return filepath.Base(s.MountFile())
}
// SnapRevision returns the revision of the snap.
func (s *Info) SnapRevision() Revision {
return s.Revision
}
// ID implements naming.SnapRef.
func (s *Info) ID() string {
return s.SnapID
}
var _ naming.SnapRef = (*Info)(nil)
// Title returns the blessed title for the snap.
func (s *Info) Title() string {
if s.EditedTitle != "" {
return s.EditedTitle
}
return s.OriginalTitle
}
// Summary returns the blessed summary for the snap.
func (s *Info) Summary() string {
if s.EditedSummary != "" {
return s.EditedSummary
}
return s.OriginalSummary
}
// Description returns the blessed description for the snap.
func (s *Info) Description() string {
if s.EditedDescription != "" {
return s.EditedDescription
}
return s.OriginalDescription
}
// Links returns the blessed set of snap-related links.
func (s *Info) Links() map[string][]string {
if s.EditedLinks != nil {
// the store used to send empty links, normalization
// is required to filter out persisted invalid links
return s.normalizedEditedLinks()
}
return s.normalizedOriginalLinks()
}
// addLink adds a link if it passes validation to ensure it will not contribute to
// ValidateLinks errors. It also attempts to convert a link with URL scheme "" to
// "mailto" and avoids duplicate links.
func addLink(links map[string][]string, key, link string) {
if key == "" || !isValidLinksKey(key) {
return
}
if link == "" {
return
}
u, err := url.Parse(link)
if err != nil {
return
}
if u.Scheme == "" {
link = "mailto:" + link
u.Scheme = "mailto"
}
if u.Scheme == "mailto" {
// minimal check
if !strings.Contains(link, "@") {
return
}
} else if !strutil.ListContains(validLinkSchemes, u.Scheme) {
return
}
if strutil.ListContains(links[key], link) {
return
}
links[key] = append(links[key], link)
}
func (s *Info) normalizedEditedLinks() map[string][]string {
normalizedLinks := make(map[string][]string, len(s.EditedLinks))
for key, links := range s.EditedLinks {
for _, link := range links {
addLink(normalizedLinks, key, link)
}
}
if len(normalizedLinks) == 0 {
return nil
}
return normalizedLinks
}
func (s *Info) normalizedOriginalLinks() map[string][]string {
normalizedLinks := make(map[string][]string, len(s.OriginalLinks))
addLink(normalizedLinks, "contact", s.LegacyEditedContact)
addLink(normalizedLinks, "website", s.LegacyWebsite)
for key, links := range s.OriginalLinks {
for _, link := range links {
addLink(normalizedLinks, key, link)
}
}
if len(normalizedLinks) == 0 {
return nil
}
return normalizedLinks
}
// Contact returns the blessed contact information for the snap.
func (s *Info) Contact() string {
contacts := s.Links()["contact"]
if len(contacts) > 0 {
return contacts[0]
}
return ""
}
// Website returns the blessed website information for the snap.
func (s *Info) Website() string {
websites := s.Links()["website"]
if len(websites) > 0 {
return websites[0]
}
return ""
}
// Type returns the type of the snap, including additional snap ID check
// for the legacy snapd snap definitions.
func (s *Info) Type() Type {
if s.SnapType == TypeApp && IsSnapd(s.SnapID) {
return TypeSnapd
}
return s.SnapType
}
// MountDir returns the base directory of the snap where it gets mounted.
func (s *Info) MountDir() string {
return MountDir(s.InstanceName(), s.Revision)
}
// MountFile returns the path where the snap file that is mounted is installed.
func (s *Info) MountFile() string {
return MountFile(s.InstanceName(), s.Revision)
}
// MountDescription returns the mount unit Description field.
func (s *Info) MountDescription() string {
return fmt.Sprintf("Mount unit for %s, revision %s", s.InstanceName(), s.Revision)
}
// HooksDir returns the directory containing the snap's hooks.
func (s *Info) HooksDir() string {
return HooksDir(s.InstanceName(), s.Revision)
}
// DataDir returns the data directory of the snap.
func (s *Info) DataDir() string {
return DataDir(s.InstanceName(), s.Revision)
}
// UserDataDir returns the user-specific data directory of the snap.
func (s *Info) UserDataDir(home string, opts *dirs.SnapDirOptions) string {
return UserDataDir(home, s.InstanceName(), s.Revision, opts)
}
// UserCommonDataDir returns the user-specific data directory common across
// revision of the snap.
func (s *Info) UserCommonDataDir(home string, opts *dirs.SnapDirOptions) string {
return UserCommonDataDir(home, s.InstanceName(), opts)
}
// UserExposedHomeDir returns the new upper-case snap directory in the user home.
func (s *Info) UserExposedHomeDir(home string) string {
return filepath.Join(home, dirs.ExposedSnapHomeDir, s.InstanceName())
}
// CommonDataDir returns the data directory common across revisions of the snap.
func (s *Info) CommonDataDir() string {
return CommonDataDir(s.InstanceName())
}
// CommonDataSaveDir returns the save data directory common across revisions of the snap.
func (s *Info) CommonDataSaveDir() string {
return CommonDataSaveDir(s.InstanceName())
}
// DataHomeDirs returns the per user data directories of the snap across multiple
// home directories.
func (s *Info) DataHomeDirs(opts *dirs.SnapDirOptions) []string {
var dataHomeGlob []string
for _, glob := range dirs.DataHomeGlobs(opts) {
dataHomeGlob = append(dataHomeGlob, filepath.Join(glob, s.InstanceName(), s.Revision.String()))
}
return dataHomeGlob
}
// CommonDataHomeDirs returns the per user data directories common across revisions
// of the snap in all defined home directories.
func (s *Info) CommonDataHomeDirs(opts *dirs.SnapDirOptions) []string {
var comDataHomeGlob []string
for _, glob := range dirs.DataHomeGlobs(opts) {
comDataHomeGlob = append(comDataHomeGlob, filepath.Join(glob, s.InstanceName(), "common"))
}
return comDataHomeGlob
}
// UserXdgRuntimeDir returns the XDG_RUNTIME_DIR directory of the snap for a
// particular user.
func (s *Info) UserXdgRuntimeDir(euid sys.UserID) string {
return UserXdgRuntimeDir(euid, s.InstanceName())
}
// XdgRuntimeDirs returns the XDG_RUNTIME_DIR directories for all users of the
// snap.
func (s *Info) XdgRuntimeDirs() string {
return filepath.Join(dirs.XdgRuntimeDirGlob, fmt.Sprintf("snap.%s", s.InstanceName()))
}
func (s *Info) BinaryNameGlobs() []string {
return []string{s.InstanceName(), fmt.Sprintf("%s.*", s.InstanceName())}
}
// NeedsDevMode returns whether the snap needs devmode.
func (s *Info) NeedsDevMode() bool {
return s.Confinement == DevModeConfinement
}
// NeedsClassic returns whether the snap needs classic confinement consent.
func (s *Info) NeedsClassic() bool {
return s.Confinement == ClassicConfinement
}
// Services returns a list of the apps that have "daemon" set.
func (s *Info) Services() []*AppInfo {
svcs := make([]*AppInfo, 0, len(s.Apps))
for _, app := range s.Apps {
if !app.IsService() {
continue
}
svcs = append(svcs, app)
}
return svcs
}
// ExpandSnapVariables resolves $SNAP, $SNAP_DATA and $SNAP_COMMON in path for this snap.
func (s *Info) ExpandSnapVariables(path string) string {
// NOTE: We use dirs.CoreSnapMountDir here as the path used will be
// always inside the mount namespace snap-confine creates and there
// we will always have a /snap directory available regardless if the
// system we're running on supports this or not.
return s.ExpandSnapVariablesSetSnapMountDir(path, dirs.CoreSnapMountDir)
}
// ExpandSnapVariablesSetSnapMountDir resolves $SNAP, $SNAP_DATA and
// $SNAP_COMMON in path for this snap using snapMountDir as root directory.
func (s *Info) ExpandSnapVariablesSetSnapMountDir(path, snapMountDir string) string {
return os.Expand(path, func(v string) string {
switch v {
case "SNAP":
return filepath.Join(snapMountDir, s.SnapName(), s.Revision.String())
case "SNAP_DATA":
return DataDir(s.SnapName(), s.Revision)
case "SNAP_COMMON":
return CommonDataDir(s.SnapName())
}
return ""
})
}
// InstallDate returns the "install date" of the snap.
//
// If the snap is not active, it'll return nil; otherwise
// it'll return the modtime of the "current" symlink. Sneaky.
func (s *Info) InstallDate() *time.Time {
dir, rev := filepath.Split(s.MountDir())
cur := filepath.Join(dir, "current")
tag, err := os.Readlink(cur)
if err == nil && tag == rev {
if st, err := os.Lstat(cur); err == nil {
modTime := st.ModTime()
return &modTime
}
}
return nil
}
// IsActive returns whether this snap revision is active.
func (s *Info) IsActive() bool {
dir, rev := filepath.Split(s.MountDir())
cur := filepath.Join(dir, "current")
tag, err := os.Readlink(cur)
return err == nil && tag == rev
}
// AppsForPlug returns the list of apps that are associated with the given plug.
// If the plug is unscoped, then all apps are returned.
// TODO: implement this without using the Apps field in PlugInfo
func (s *Info) AppsForPlug(plug *PlugInfo) []*AppInfo {
apps := make([]*AppInfo, 0, len(plug.Apps))
for _, app := range plug.Apps {
apps = append(apps, app)
}
return apps
}
// AppsForSlot returns the list of apps that are associated with the given slot.
// If the slot is unscoped, then all apps are returned.
// TODO: implement this without using the Apps field in SlotInfo
func (s *Info) AppsForSlot(slot *SlotInfo) []*AppInfo {
apps := make([]*AppInfo, 0, len(slot.Apps))
for _, app := range slot.Apps {
apps = append(apps, app)
}
return apps
}
// HooksForPlug returns the list of hooks that are associated with the given
// plug. If the plug is unscoped, then all hooks are returned.
func (s *Info) HooksForPlug(plug *PlugInfo) []*HookInfo {
return hooksForPlug(plug, s.Hooks)
}
func hooksForPlug(plug *PlugInfo, hooks map[string]*HookInfo) []*HookInfo {
if plug.Unscoped {
plugHooks := make([]*HookInfo, 0, len(hooks))
for _, hook := range hooks {
plugHooks = append(plugHooks, hook)
}
return plugHooks
}
var plugHooks []*HookInfo
for _, hook := range hooks {
if _, ok := hook.Plugs[plug.Name]; ok {
plugHooks = append(plugHooks, hook)
}
}
return plugHooks
}
// HooksForSlot returns the list of hooks that are associated with the given
// slot. If the slot is unscoped, then all hooks are returned.
func (s *Info) HooksForSlot(slot *SlotInfo) []*HookInfo {
if slot.Unscoped {
hooks := make([]*HookInfo, 0, len(s.Hooks))
for _, hook := range s.Hooks {
hooks = append(hooks, hook)
}
return hooks
}
var hooks []*HookInfo
for _, hook := range s.Hooks {
if _, ok := hook.Slots[slot.Name]; ok {
hooks = append(hooks, hook)
}
}
return hooks
}
// BadInterfacesSummary returns a summary of the problems of bad plugs
// and slots in the snap.
func BadInterfacesSummary(snapInfo *Info) string {
inverted := make(map[string][]string)
for name, reason := range snapInfo.BadInterfaces {
inverted[reason] = append(inverted[reason], name)
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "snap %q has bad plugs or slots: ", snapInfo.InstanceName())
reasons := make([]string, 0, len(inverted))
for reason := range inverted {
reasons = append(reasons, reason)
}
sort.Strings(reasons)
for _, reason := range reasons {
names := inverted[reason]
sort.Strings(names)
for i, name := range names {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(name)
}
fmt.Fprintf(&buf, " (%s); ", reason)
}
return strings.TrimSuffix(buf.String(), "; ")
}
// DesktopPrefix returns the prefix string for the desktop files that
// belongs to the given snapInstance. We need to do something custom
// here because a) we need to be compatible with the world before we had
// parallel installs b) we can't just use the usual "_" parallel installs
// separator because that is already used as the separator between snap
// and desktop filename.
func (s *Info) DesktopPrefix() string {
if s.InstanceKey == "" {
return s.SnapName()
}
// we cannot use the usual "_" separator because that is also used
// to separate "$snap_$desktopfile"
return fmt.Sprintf("%s+%s", s.SnapName(), s.InstanceKey)
}
// DesktopPlugFileIDs returns desktop-file-ids desktop plug attribute entries.
// The desktop-file-ids attribute is optional so an empty list is returned if
// the it is not found.
//
// Note: DesktopPlugFileIDs doesn't check if the desktop plug is connected because
// the desktop-file-ids attribute is controlled by an allow-installation rule.
func (s *Info) DesktopPlugFileIDs() ([]string, error) {
desktopPlugNames := make([]string, 0, len(s.Plugs))
for name, plug := range s.Plugs {
if plug.Interface == "desktop" {
desktopPlugNames = append(desktopPlugNames, name)
}
}
if len(desktopPlugNames) == 0 {
return nil, nil
}
sort.Strings(desktopPlugNames)
// TODO: The internal errors below should never happen due to validation
// in the desktop interface. It would be a good candidate for telemetry
// error reporting.
desktopFileIDs := make([]string, 0)
seenDesktopFileIDs := make(map[string]bool)
for _, plugName := range desktopPlugNames {
desktopPlug := s.Plugs[plugName]
attrVal, exists := desktopPlug.Lookup("desktop-file-ids")
if !exists {
// desktop-file-ids attribute is optional
continue
}
// desktop-file-ids must be a list of strings
attrList, ok := attrVal.([]any)
if !ok {
return nil, errors.New(`internal error: "desktop-file-ids" must be a list of strings`)