-
Notifications
You must be signed in to change notification settings - Fork 582
/
handlers.go
2032 lines (1754 loc) · 63.6 KB
/
handlers.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
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) 2016-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 ifacestate
import (
"errors"
"fmt"
"path"
"reflect"
"sort"
"strings"
"time"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/interfaces/hotplug"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/hookstate"
"github.com/snapcore/snapd/overlord/ifacestate/schema"
"github.com/snapcore/snapd/overlord/servicestate"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/quota"
"github.com/snapcore/snapd/timings"
)
var snapstateFinishRestart = snapstate.FinishRestart
// journalQuotaLayout returns the necessary journal quota mount layouts
// to mimick what systemd does for services with log namespaces.
func journalQuotaLayout(quotaGroup *quota.Group) []snap.Layout {
if quotaGroup.JournalLimit == nil {
return nil
}
// bind mount the journal namespace folder on top of the journal folder
// /run/systemd/journal.<ns> -> /run/systemd/journal
layouts := []snap.Layout{{
Bind: path.Join(dirs.SnapSystemdRunDir, fmt.Sprintf("journal.%s", quotaGroup.JournalNamespaceName())),
Path: path.Join(dirs.SnapSystemdRunDir, "journal"),
Mode: 0755,
}}
return layouts
}
// getExtraLayouts helper function to dynamically calculate the extra mount layouts for
// a snap instance. These are the layouts which can change during the lifetime of a snap
// like for instance mimicking systemd journal namespace mount layouts.
func getExtraLayouts(st *state.State, snapInfo *snap.Info) ([]snap.Layout, error) {
snapOpts, err := servicestate.SnapServiceOptions(st, snapInfo, nil)
if err != nil {
return nil, err
}
var extraLayouts []snap.Layout
if snapOpts.QuotaGroup != nil {
extraLayouts = append(extraLayouts, journalQuotaLayout(snapOpts.QuotaGroup)...)
}
return extraLayouts, nil
}
func (m *InterfaceManager) buildConfinementOptions(st *state.State, snapInfo *snap.Info, flags snapstate.Flags) (interfaces.ConfinementOptions, error) {
extraLayouts, err := getExtraLayouts(st, snapInfo)
if err != nil {
return interfaces.ConfinementOptions{}, fmt.Errorf("cannot get extra mount layouts of snap %q: %s", snapInfo.InstanceName(), err)
}
return interfaces.ConfinementOptions{
DevMode: flags.DevMode,
JailMode: flags.JailMode,
Classic: flags.Classic,
ExtraLayouts: extraLayouts,
AppArmorPrompting: m.useAppArmorPrompting,
}, nil
}
func (m *InterfaceManager) setupAffectedSnaps(task *state.Task, affectingSnap string, affectedSnaps []string, tm timings.Measurer) error {
st := task.State()
// Setup security of the affected snaps.
for _, affectedInstanceName := range affectedSnaps {
// the snap that triggered the change needs to be skipped
if affectedInstanceName == affectingSnap {
continue
}
var snapst snapstate.SnapState
if err := snapstate.Get(st, affectedInstanceName, &snapst); err != nil {
task.Errorf("skipping security profiles setup for snap %q when handling snap %q: %v", affectedInstanceName, affectingSnap, err)
continue
}
affectedSnapInfo, err := snapst.CurrentInfo()
if err != nil {
return err
}
if err := addImplicitSlots(st, affectedSnapInfo); err != nil {
return err
}
affectedAppSet, err := appSetForSnapRevision(st, affectedSnapInfo)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", affectingSnap, err)
}
opts, err := m.buildConfinementOptions(st, affectedSnapInfo, snapst.Flags)
if err != nil {
return err
}
if err := m.setupSnapSecurity(task, affectedAppSet, opts, tm); err != nil {
return err
}
}
return nil
}
func (m *InterfaceManager) doSetupProfiles(task *state.Task, tomb *tomb.Tomb) error {
task.State().Lock()
defer task.State().Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(task.State())
// Get snap.Info from bits handed by the snap manager.
snapsup, err := snapstate.TaskSnapSetup(task)
if err != nil {
return err
}
snapInfo, err := snap.ReadInfo(snapsup.InstanceName(), snapsup.SideInfo)
if err != nil {
return err
}
if len(snapInfo.BadInterfaces) > 0 {
task.State().Warnf("%s", snap.BadInterfacesSummary(snapInfo))
}
// We no longer do/need core-phase-2, see
// https://github.com/snapcore/snapd/pull/5301
// This code is just here to deal with old state that may still
// have the 2nd setup-profiles with this flag set.
var corePhase2 bool
if err := task.Get("core-phase-2", &corePhase2); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if corePhase2 {
// nothing to do
return nil
}
opts, err := m.buildConfinementOptions(task.State(), snapInfo, snapsup.Flags)
if err != nil {
return err
}
if err := addImplicitSlots(task.State(), snapInfo); err != nil {
return err
}
// this app set is derived from the current task, which will include any
// components that are already installed, with the addition of any new
// components that are getting setup up by this task
appSet, err := appSetForTask(task, snapInfo)
if err != nil {
return err
}
if err := m.setupProfilesForAppSet(task, appSet, opts, perfTimings); err != nil {
return err
}
return setPendingProfilesSideInfo(task.State(), snapsup.InstanceName(), appSet)
}
// setupPendingProfilesSideInfo helps updating information about any
// revision for which security profiles are set up while the snap is
// not yet active.
func setPendingProfilesSideInfo(st *state.State, instanceName string, appSet *interfaces.SnapAppSet) error {
var snapst snapstate.SnapState
if err := snapstate.Get(st, instanceName, &snapst); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if !snapst.IsInstalled() {
// not yet visible to the rest of the system, nothing to do here
return nil
}
if snapst.Active {
// nothing is pending
return nil
}
if appSet != nil {
csis := make([]*snap.ComponentSideInfo, 0, len(appSet.Components()))
for _, ci := range appSet.Components() {
csis = append(csis, &ci.ComponentSideInfo)
}
snapst.PendingSecurity = &snapstate.PendingSecurityState{
SideInfo: &appSet.Info().SideInfo,
Components: csis,
}
} else {
snapst.PendingSecurity = &snapstate.PendingSecurityState{}
}
snapstate.Set(st, instanceName, &snapst)
return nil
}
func (m *InterfaceManager) setupProfilesForAppSet(task *state.Task, appSet *interfaces.SnapAppSet, opts interfaces.ConfinementOptions, tm timings.Measurer) error {
st := task.State()
snapInfo := appSet.Info()
snapName := appSet.InstanceName()
// The snap may have been updated so perform the following operation to
// ensure that we are always working on the correct state:
//
// - disconnect all connections to/from the given snap
// - remembering the snaps that were affected by this operation
// - remove the (old) snap from the interfaces repository
// - add the (new) snap to the interfaces repository
// - restore connections based on what is kept in the state
// - if a connection cannot be restored then remove it from the state
// - setup the security of all the affected snaps
disconnectedSnaps, err := m.repo.DisconnectSnap(snapName)
if err != nil {
return err
}
// XXX: what about snap renames? We should remove the old name (or switch
// to IDs in the interfaces repository)
if err := m.repo.RemoveSnap(snapName); err != nil {
return err
}
if err := m.repo.AddAppSet(appSet); err != nil {
return err
}
if len(snapInfo.BadInterfaces) > 0 {
task.Logf("%s", snap.BadInterfacesSummary(snapInfo))
}
// Reload the connections and compute the set of affected snaps. The set
// affectedSet set contains name of all the affected snap instances. The
// arrays affectedNames and affectedSnaps contain, arrays of snap names and
// snapInfo's, respectively. The arrays are sorted by name with the special
// exception that the snap being setup is always first. The affectedSnaps
// array may be shorter than the set of affected snaps in case any of the
// snaps cannot be found in the state.
reconnectedSnaps, err := m.reloadConnections(snapName)
if err != nil {
return err
}
affectedSet := make(map[string]bool)
for _, name := range disconnectedSnaps {
affectedSet[name] = true
}
for _, name := range reconnectedSnaps {
affectedSet[name] = true
}
// Sort the set of affected names, ensuring that the snap being setup
// is first regardless of the name it has.
affectedNames := make([]string, 0, len(affectedSet))
for name := range affectedSet {
if name != snapName {
affectedNames = append(affectedNames, name)
}
}
sort.Strings(affectedNames)
affectedNames = append([]string{snapName}, affectedNames...)
// Obtain interfaces.SnapAppSet for each affected snap, skipping those that
// cannot be found and compute the confinement options that apply to it.
affectedSnapSets := make([]*interfaces.SnapAppSet, 0, len(affectedSet))
confinementOpts := make([]interfaces.ConfinementOptions, 0, len(affectedSet))
// For the snap being setup we know exactly what was requested.
affectedSnapSets = append(affectedSnapSets, appSet)
confinementOpts = append(confinementOpts, opts)
// For remaining snaps we need to interrogate the state.
for _, name := range affectedNames[1:] {
var snapst snapstate.SnapState
if err := snapstate.Get(st, name, &snapst); err != nil {
task.Errorf("cannot obtain state of snap %s: %s", name, err)
continue
}
snapInfo, err := snapst.CurrentInfo()
if err != nil {
return err
}
if err := addImplicitSlots(st, snapInfo); err != nil {
return err
}
appSet, err := appSetForSnapRevision(st, snapInfo)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", name, err)
}
opts, err := m.buildConfinementOptions(st, snapInfo, snapst.Flags)
if err != nil {
return err
}
affectedSnapSets = append(affectedSnapSets, appSet)
confinementOpts = append(confinementOpts, opts)
}
return m.setupSecurityByBackend(task, affectedSnapSets, confinementOpts, tm)
}
func (m *InterfaceManager) doRemoveProfiles(task *state.Task, tomb *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(st)
// Get SnapSetup for this snap. This is gives us the name of the snap.
snapSetup, err := snapstate.TaskSnapSetup(task)
if err != nil {
return err
}
snapName := snapSetup.InstanceName()
if err := m.removeProfilesForSnap(task, tomb, snapName, perfTimings); err != nil {
return err
}
// no pending profiles on disk
return setPendingProfilesSideInfo(task.State(), snapName, nil)
}
func (m *InterfaceManager) removeProfilesForSnap(task *state.Task, _ *tomb.Tomb, snapName string, tm timings.Measurer) error {
// Disconnect the snap entirely.
// This is required to remove the snap from the interface repository.
// The returned list of affected snaps will need to have its security setup
// to reflect the change.
affectedSnaps, err := m.repo.DisconnectSnap(snapName)
if err != nil {
return err
}
if err := m.setupAffectedSnaps(task, snapName, affectedSnaps, tm); err != nil {
return err
}
// Remove the snap from the interface repository.
// This discards all the plugs and slots belonging to that snap.
if err := m.repo.RemoveSnap(snapName); err != nil {
return err
}
// Remove security artefacts of the snap.
if err := m.removeSnapSecurity(task, snapName); err != nil {
return err
}
return nil
}
func (m *InterfaceManager) undoSetupProfiles(task *state.Task, tomb *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(st)
var corePhase2 bool
if err := task.Get("core-phase-2", &corePhase2); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if corePhase2 {
// let the first setup-profiles deal with this
return nil
}
snapsup, err := snapstate.TaskSnapSetup(task)
if err != nil {
return err
}
snapName := snapsup.InstanceName()
// Get the name from SnapSetup and use it to find the current SideInfo
// about the snap, if there is one.
var snapst snapstate.SnapState
err = snapstate.Get(st, snapName, &snapst)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
sideInfo := snapst.CurrentSideInfo()
if sideInfo == nil {
// The snap was not installed before so undo should remove security profiles.
return m.removeProfilesForSnap(task, tomb, snapName, perfTimings)
} else {
// The snap was installed before so undo should setup the old security profiles.
snapInfo, err := snap.ReadInfo(snapName, sideInfo)
if err != nil {
return err
}
opts, err := m.buildConfinementOptions(task.State(), snapInfo, snapst.Flags)
if err != nil {
return err
}
if err := addImplicitSlots(st, snapInfo); err != nil {
return err
}
// this app set is derived from the currently installed revision of the
// snap (not the revision that we are reverting from). it only includes
// components that were installed with that revision.
appSet, err := appSetForSnapRevision(st, snapInfo)
if err != nil {
return err
}
if err := m.setupProfilesForAppSet(task, appSet, opts, perfTimings); err != nil {
return err
}
return setPendingProfilesSideInfo(task.State(), snapName, appSet)
}
}
func (m *InterfaceManager) doDiscardConns(task *state.Task, _ *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
snapSetup, err := snapstate.TaskSnapSetup(task)
if err != nil {
return err
}
instanceName := snapSetup.InstanceName()
var snapst snapstate.SnapState
err = snapstate.Get(st, instanceName, &snapst)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if err == nil && len(snapst.Sequence.Revisions) != 0 {
return fmt.Errorf("cannot discard connections for snap %q while it is present", instanceName)
}
conns, err := getConns(st)
if err != nil {
return err
}
removed := make(map[string]*schema.ConnState)
for id := range conns {
connRef, err := interfaces.ParseConnRef(id)
if err != nil {
return err
}
if connRef.PlugRef.Snap == instanceName || connRef.SlotRef.Snap == instanceName {
removed[id] = conns[id]
delete(conns, id)
}
}
task.Set("removed", removed)
setConns(st, conns)
return nil
}
func (m *InterfaceManager) undoDiscardConns(task *state.Task, _ *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
var removed map[string]*schema.ConnState
err := task.Get("removed", &removed)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
conns, err := getConns(st)
if err != nil {
return err
}
for id, connState := range removed {
conns[id] = connState
}
setConns(st, conns)
task.Set("removed", nil)
return nil
}
func getDynamicHookAttributes(task *state.Task) (plugAttrs, slotAttrs map[string]interface{}, err error) {
if err = task.Get("plug-dynamic", &plugAttrs); err != nil && !errors.Is(err, state.ErrNoState) {
return nil, nil, err
}
if err = task.Get("slot-dynamic", &slotAttrs); err != nil && !errors.Is(err, state.ErrNoState) {
return nil, nil, err
}
if plugAttrs == nil {
plugAttrs = make(map[string]interface{})
}
if slotAttrs == nil {
slotAttrs = make(map[string]interface{})
}
return plugAttrs, slotAttrs, nil
}
func setDynamicHookAttributes(task *state.Task, plugAttrs, slotAttrs map[string]interface{}) {
task.Set("plug-dynamic", plugAttrs)
task.Set("slot-dynamic", slotAttrs)
}
func (m *InterfaceManager) doConnect(task *state.Task, _ *tomb.Tomb) (err error) {
st := task.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(st)
plugRef, slotRef, err := getPlugAndSlotRefs(task)
if err != nil {
return err
}
var autoConnect bool
if err := task.Get("auto", &autoConnect); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
var byGadget bool
if err := task.Get("by-gadget", &byGadget); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
var delayedSetupProfiles bool
if err := task.Get("delayed-setup-profiles", &delayedSetupProfiles); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
deviceCtx, err := snapstate.DeviceCtx(st, task, nil)
if err != nil {
return err
}
conns, err := getConns(st)
if err != nil {
return err
}
connRef := &interfaces.ConnRef{PlugRef: plugRef, SlotRef: slotRef}
var plugSnapst snapstate.SnapState
if err := snapstate.Get(st, plugRef.Snap, &plugSnapst); err != nil {
if autoConnect && errors.Is(err, state.ErrNoState) {
// conflict logic should prevent this
return fmt.Errorf("internal error: snap %q is no longer available for auto-connecting", plugRef.Snap)
}
return err
}
var slotSnapst snapstate.SnapState
if err := snapstate.Get(st, slotRef.Snap, &slotSnapst); err != nil {
if autoConnect && errors.Is(err, state.ErrNoState) {
// conflict logic should prevent this
return fmt.Errorf("internal error: snap %q is no longer available for auto-connecting", slotRef.Snap)
}
return err
}
plug := m.repo.Plug(connRef.PlugRef.Snap, connRef.PlugRef.Name)
if plug == nil {
// conflict logic should prevent this
return fmt.Errorf("snap %q has no %q plug", connRef.PlugRef.Snap, connRef.PlugRef.Name)
}
plugAppSet, err := appSetForSnapRevision(st, plug.Snap)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", plug.Snap.InstanceName(), err)
}
slot := m.repo.Slot(connRef.SlotRef.Snap, connRef.SlotRef.Name)
if slot == nil {
// conflict logic should prevent this
return fmt.Errorf("snap %q has no %q slot", connRef.SlotRef.Snap, connRef.SlotRef.Name)
}
slotAppSet, err := appSetForSnapRevision(st, slot.Snap)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", slot.Snap.InstanceName(), err)
}
// attributes are always present, even if there are no hooks (they're initialized by Connect).
plugDynamicAttrs, slotDynamicAttrs, err := getDynamicHookAttributes(task)
if err != nil {
return fmt.Errorf("failed to get hook attributes: %s", err)
}
var policyChecker interfaces.PolicyFunc
// manual connections and connections by the gadget obey the
// policy "connection" rules, other auto-connections obey the
// "auto-connection" rules
if autoConnect && !byGadget {
autochecker, err := newAutoConnectChecker(st, m.repo, deviceCtx)
if err != nil {
return err
}
policyChecker = func(plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) (bool, error) {
ok, _, err := autochecker.check(plug, slot)
return ok, err
}
} else {
policyCheck, err := newConnectChecker(st, deviceCtx)
if err != nil {
return err
}
policyChecker = policyCheck.check
}
// static attributes of the plug and slot not provided, the ones from snap infos will be used
conn, err := m.repo.Connect(connRef, nil, plugDynamicAttrs, nil, slotDynamicAttrs, policyChecker)
if err != nil || conn == nil {
return err
}
defer func() {
if err != nil {
if err := m.repo.Disconnect(plugRef.Snap, plugRef.Name, slotRef.Snap, slotRef.Name); err != nil {
logger.Noticef("cannot undo failed connection: %v", err)
}
}
}()
if !delayedSetupProfiles {
slotSnapInfo, err := slotSnapst.CurrentInfo()
if err != nil {
return err
}
slotOpts, err := m.buildConfinementOptions(st, slotSnapInfo, slotSnapst.Flags)
if err != nil {
return err
}
if err := m.setupSnapSecurity(task, slotAppSet, slotOpts, perfTimings); err != nil {
return err
}
plugSnapInfo, err := plugSnapst.CurrentInfo()
if err != nil {
return err
}
plugOpts, err := m.buildConfinementOptions(st, plugSnapInfo, plugSnapst.Flags)
if err != nil {
return err
}
if err := m.setupSnapSecurity(task, plugAppSet, plugOpts, perfTimings); err != nil {
return err
}
} else {
logger.Debugf("Connect handler: skipping setupSnapSecurity for snaps %q and %q", plug.Snap.InstanceName(), slot.Snap.InstanceName())
}
// For undo handler. We need to remember old state of the connection only
// if undesired flag is set because that means there was a remembered
// inactive connection already and we should restore its properties
// in case of undo. Otherwise we don't have to keep old-conn because undo
// can simply delete any trace of the connection.
if old, ok := conns[connRef.ID()]; ok && old.Undesired {
task.Set("old-conn", old)
}
conns[connRef.ID()] = &schema.ConnState{
Interface: conn.Interface(),
StaticPlugAttrs: conn.Plug.StaticAttrs(),
DynamicPlugAttrs: conn.Plug.DynamicAttrs(),
StaticSlotAttrs: conn.Slot.StaticAttrs(),
DynamicSlotAttrs: conn.Slot.DynamicAttrs(),
Auto: autoConnect,
ByGadget: byGadget,
HotplugKey: slot.HotplugKey,
}
setConns(st, conns)
// the dynamic attributes might have been updated by the interface's BeforeConnectPlug/Slot code,
// so we need to update the task for connect-plug- and connect-slot- hooks to see new values.
setDynamicHookAttributes(task, conn.Plug.DynamicAttrs(), conn.Slot.DynamicAttrs())
return nil
}
func (m *InterfaceManager) doDisconnect(task *state.Task, _ *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(st)
plugRef, slotRef, err := getPlugAndSlotRefs(task)
if err != nil {
return err
}
cref := interfaces.ConnRef{PlugRef: plugRef, SlotRef: slotRef}
conns, err := getConns(st)
if err != nil {
return err
}
// forget flag can be passed with snap disconnect --forget
var forget bool
if err := task.Get("forget", &forget); err != nil && !errors.Is(err, state.ErrNoState) {
return fmt.Errorf("internal error: cannot read 'forget' flag: %s", err)
}
var snapStates []snapstate.SnapState
for _, instanceName := range []string{plugRef.Snap, slotRef.Snap} {
var snapst snapstate.SnapState
if err := snapstate.Get(st, instanceName, &snapst); err != nil {
if errors.Is(err, state.ErrNoState) {
task.Logf("skipping disconnect operation for connection %s %s, snap %q doesn't exist", plugRef, slotRef, instanceName)
return nil
}
task.Errorf("skipping security profiles setup for snap %q when disconnecting %s from %s: %v", instanceName, plugRef, slotRef, err)
} else {
snapStates = append(snapStates, snapst)
}
}
conn, ok := conns[cref.ID()]
if !ok {
return fmt.Errorf("internal error: connection %q not found in state", cref.ID())
}
// store old connection for undo
task.Set("old-conn", conn)
err = m.repo.Disconnect(plugRef.Snap, plugRef.Name, slotRef.Snap, slotRef.Name)
if err != nil {
_, notConnected := err.(*interfaces.NotConnectedError)
_, noPlugOrSlot := err.(*interfaces.NoPlugOrSlotError)
// not connected, just forget it.
if forget && (notConnected || noPlugOrSlot) {
delete(conns, cref.ID())
setConns(st, conns)
return nil
}
return fmt.Errorf("snapd changed, please retry the operation: %v", err)
}
for _, snapst := range snapStates {
snapInfo, err := snapst.CurrentInfo()
if err != nil {
return err
}
appSet, err := appSetForSnapRevision(st, snapInfo)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", snapInfo.InstanceName(), err)
}
opts, err := m.buildConfinementOptions(st, snapInfo, snapst.Flags)
if err != nil {
return err
}
if err := m.setupSnapSecurity(task, appSet, opts, perfTimings); err != nil {
return err
}
}
// "auto-disconnect" flag indicates it's a disconnect triggered automatically as part of snap removal;
// such disconnects should not set undesired flag and instead just remove the connection.
var autoDisconnect bool
if err := task.Get("auto-disconnect", &autoDisconnect); err != nil && !errors.Is(err, state.ErrNoState) {
return fmt.Errorf("internal error: failed to read 'auto-disconnect' flag: %s", err)
}
// "by-hotplug" flag indicates it's a disconnect triggered by hotplug remove event;
// we want to keep information of the connection and just mark it as hotplug-gone.
var byHotplug bool
if err := task.Get("by-hotplug", &byHotplug); err != nil && !errors.Is(err, state.ErrNoState) {
return fmt.Errorf("internal error: cannot read 'by-hotplug' flag: %s", err)
}
switch {
case forget:
delete(conns, cref.ID())
case byHotplug:
conn.HotplugGone = true
conns[cref.ID()] = conn
case conn.Auto && !autoDisconnect:
conn.Undesired = true
conn.DynamicPlugAttrs = nil
conn.DynamicSlotAttrs = nil
conn.StaticPlugAttrs = nil
conn.StaticSlotAttrs = nil
conns[cref.ID()] = conn
default:
delete(conns, cref.ID())
}
setConns(st, conns)
return nil
}
func (m *InterfaceManager) undoDisconnect(task *state.Task, _ *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(st)
var oldconn schema.ConnState
err := task.Get("old-conn", &oldconn)
if errors.Is(err, state.ErrNoState) {
return nil
}
if err != nil {
return err
}
var forget bool
if err := task.Get("forget", &forget); err != nil && !errors.Is(err, state.ErrNoState) {
return fmt.Errorf("internal error: cannot read 'forget' flag: %s", err)
}
plugRef, slotRef, err := getPlugAndSlotRefs(task)
if err != nil {
return err
}
conns, err := getConns(st)
if err != nil {
return err
}
var plugSnapst snapstate.SnapState
if err := snapstate.Get(st, plugRef.Snap, &plugSnapst); err != nil {
return err
}
var slotSnapst snapstate.SnapState
if err := snapstate.Get(st, slotRef.Snap, &slotSnapst); err != nil {
return err
}
connRef := &interfaces.ConnRef{PlugRef: plugRef, SlotRef: slotRef}
plug := m.repo.Plug(connRef.PlugRef.Snap, connRef.PlugRef.Name)
slot := m.repo.Slot(connRef.SlotRef.Snap, connRef.SlotRef.Name)
if forget && (plug == nil || slot == nil) {
// we were trying to forget an inactive connection that was
// referring to a non-existing plug or slot; just restore it
// in the conns state but do not reconnect via repository.
conns[connRef.ID()] = &oldconn
setConns(st, conns)
return nil
}
if plug == nil {
return fmt.Errorf("snap %q has no %q plug", connRef.PlugRef.Snap, connRef.PlugRef.Name)
}
if slot == nil {
return fmt.Errorf("snap %q has no %q slot", connRef.SlotRef.Snap, connRef.SlotRef.Name)
}
plugAppSet, err := appSetForSnapRevision(st, plug.Snap)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", plug.Snap.InstanceName(), err)
}
slotAppSet, err := appSetForSnapRevision(st, slot.Snap)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", slot.Snap.InstanceName(), err)
}
_, err = m.repo.Connect(connRef, nil, oldconn.DynamicPlugAttrs, nil, oldconn.DynamicSlotAttrs, nil)
if err != nil {
return err
}
slotSnapInfo, err := slotSnapst.CurrentInfo()
if err != nil {
return err
}
slotOpts, err := m.buildConfinementOptions(st, slotSnapInfo, slotSnapst.Flags)
if err != nil {
return err
}
if err := m.setupSnapSecurity(task, slotAppSet, slotOpts, perfTimings); err != nil {
return err
}
plugSnapInfo, err := plugSnapst.CurrentInfo()
if err != nil {
return err
}
plugOpts, err := m.buildConfinementOptions(st, plugSnapInfo, plugSnapst.Flags)
if err != nil {
return err
}
if err := m.setupSnapSecurity(task, plugAppSet, plugOpts, perfTimings); err != nil {
return err
}
conns[connRef.ID()] = &oldconn
setConns(st, conns)
return nil
}
func (m *InterfaceManager) undoConnect(task *state.Task, _ *tomb.Tomb) error {
st := task.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(task)
defer perfTimings.Save(st)
plugRef, slotRef, err := getPlugAndSlotRefs(task)
if err != nil {
return err
}
connRef := interfaces.ConnRef{PlugRef: plugRef, SlotRef: slotRef}
conns, err := getConns(st)
if err != nil {
return err
}
var old schema.ConnState
err = task.Get("old-conn", &old)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if err == nil {
conns[connRef.ID()] = &old
} else {
delete(conns, connRef.ID())
}
setConns(st, conns)
if err := m.repo.Disconnect(connRef.PlugRef.Snap, connRef.PlugRef.Name, connRef.SlotRef.Snap, connRef.SlotRef.Name); err != nil {
return err
}
var delayedSetupProfiles bool
if err := task.Get("delayed-setup-profiles", &delayedSetupProfiles); err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if delayedSetupProfiles {
logger.Debugf("Connect undo handler: skipping setupSnapSecurity for snaps %q and %q", connRef.PlugRef.Snap, connRef.SlotRef.Snap)
return nil
}
plug := m.repo.Plug(connRef.PlugRef.Snap, connRef.PlugRef.Name)
if plug == nil {
return fmt.Errorf("internal error: snap %q has no %q plug", connRef.PlugRef.Snap, connRef.PlugRef.Name)
}
plugAppSet, err := appSetForSnapRevision(st, plug.Snap)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", plug.Snap.InstanceName(), err)
}
slot := m.repo.Slot(connRef.SlotRef.Snap, connRef.SlotRef.Name)
if slot == nil {
return fmt.Errorf("internal error: snap %q has no %q slot", connRef.SlotRef.Snap, connRef.SlotRef.Name)
}
slotAppSet, err := appSetForSnapRevision(st, slot.Snap)
if err != nil {
return fmt.Errorf("building app set for snap %q: %v", slot.Snap.InstanceName(), err)
}
var plugSnapst snapstate.SnapState
err = snapstate.Get(st, plugRef.Snap, &plugSnapst)
if errors.Is(err, state.ErrNoState) {
return fmt.Errorf("internal error: snap %q is no longer available", plugRef.Snap)
}
if err != nil {
return err