-
-
Notifications
You must be signed in to change notification settings - Fork 338
/
Volume.cpp
1327 lines (1094 loc) · 31.7 KB
/
Volume.cpp
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
/*
* Copyright 2013-2014, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Ingo Weinhold <ingo_weinhold@gmx.de>
*/
#include "Volume.h"
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <Looper.h>
#include <MessageRunner.h>
#include <NodeMonitor.h>
#include <Path.h>
#include <package/solver/Solver.h>
#include <package/solver/SolverPackage.h>
#include <package/solver/SolverProblem.h>
#include <package/solver/SolverProblemSolution.h>
#include <package/solver/SolverRepository.h>
#include <package/solver/SolverResult.h>
#include <AutoDeleter.h>
#include <AutoLocker.h>
#include <NotOwningEntryRef.h>
#include <package/DaemonDefs.h>
#include "CommitTransactionHandler.h"
#include "Constants.h"
#include "DebugSupport.h"
#include "Exception.h"
#include "PackageFileManager.h"
#include "VolumeState.h"
using namespace BPackageKit::BPrivate;
// #pragma mark - Listener
Volume::Listener::~Listener()
{
}
// #pragma mark - NodeMonitorEvent
struct Volume::NodeMonitorEvent
: public DoublyLinkedListLinkImpl<NodeMonitorEvent> {
public:
NodeMonitorEvent(const BString& entryName, bool created)
:
fEntryName(entryName),
fCreated(created)
{
}
const BString& EntryName() const
{
return fEntryName;
}
bool WasCreated() const
{
return fCreated;
}
private:
BString fEntryName;
bool fCreated;
};
// #pragma mark - PackagesDirectory
struct Volume::PackagesDirectory {
public:
PackagesDirectory()
:
fNodeRef(),
fName()
{
}
void Init(const node_ref& nodeRef, bool isPackagesDir)
{
fNodeRef = nodeRef;
if (isPackagesDir)
return;
BDirectory directory;
BEntry entry;
if (directory.SetTo(&fNodeRef) == B_OK
&& directory.GetEntry(&entry) == B_OK) {
fName = entry.Name();
}
if (fName.IsEmpty())
fName = "unknown state";
}
const node_ref& NodeRef() const
{
return fNodeRef;
}
const BString& Name() const
{
return fName;
}
private:
node_ref fNodeRef;
BString fName;
};
// #pragma mark - Volume
Volume::Volume(BLooper* looper)
:
BHandler(),
fPath(),
fMountType(PACKAGE_FS_MOUNT_TYPE_CUSTOM),
fRootDirectoryRef(),
fPackagesDirectories(NULL),
fPackagesDirectoryCount(0),
fRoot(NULL),
fListener(NULL),
fPackageFileManager(NULL),
fLatestState(NULL),
fActiveState(NULL),
fChangeCount(0),
fLock("volume"),
fPendingNodeMonitorEventsLock("pending node monitor events"),
fPendingNodeMonitorEvents(),
fNodeMonitorEventHandleTime(0),
fPackagesToBeActivated(),
fPackagesToBeDeactivated(),
fLocationInfoReply(B_MESSAGE_GET_INSTALLATION_LOCATION_INFO_REPLY),
fPendingPackageJobCount(0)
{
looper->AddHandler(this);
}
Volume::~Volume()
{
Unmounted();
// need for error case in InitPackages()
delete[] fPackagesDirectories;
delete fPackageFileManager;
_SetLatestState(NULL, true);
}
status_t
Volume::Init(const node_ref& rootDirectoryRef, node_ref& _packageRootRef)
{
status_t error = fLock.InitCheck();
if (error != B_OK)
return error;
error = fPendingNodeMonitorEventsLock.InitCheck();
if (error != B_OK)
return error;
fLatestState = new(std::nothrow) VolumeState;
if (fLatestState == NULL || !fLatestState->Init())
RETURN_ERROR(B_NO_MEMORY);
fPackageFileManager = new(std::nothrow) PackageFileManager(fLock);
if (fPackageFileManager == NULL)
RETURN_ERROR(B_NO_MEMORY);
error = fPackageFileManager->Init();
if (error != B_OK)
RETURN_ERROR(error);
fRootDirectoryRef = rootDirectoryRef;
// open the root directory
BDirectory directory;
error = directory.SetTo(&fRootDirectoryRef);
if (error != B_OK) {
ERROR("Volume::Init(): failed to open root directory: %s\n",
strerror(error));
RETURN_ERROR(error);
}
// get the directory path
BEntry entry;
error = directory.GetEntry(&entry);
BPath path;
if (error == B_OK)
error = entry.GetPath(&path);
if (error != B_OK) {
ERROR("Volume::Init(): failed to get root directory path: %s\n",
strerror(error));
RETURN_ERROR(error);
}
fPath = path.Path();
if (fPath.IsEmpty())
RETURN_ERROR(B_NO_MEMORY);
// get a volume info from the FS
int fd = directory.Dup();
if (fd < 0) {
ERROR("Volume::Init(): failed to get root directory FD: %s\n",
strerror(fd));
RETURN_ERROR(fd);
}
FileDescriptorCloser fdCloser(fd);
// get the volume info from packagefs
uint32 maxPackagesDirCount = 16;
PackageFSVolumeInfo* info = NULL;
MemoryDeleter infoDeleter;
size_t bufferSize;
for (;;) {
bufferSize = sizeof(PackageFSVolumeInfo)
+ (maxPackagesDirCount - 1) * sizeof(PackageFSDirectoryInfo);
info = (PackageFSVolumeInfo*)malloc(bufferSize);
if (info == NULL)
RETURN_ERROR(B_NO_MEMORY);
infoDeleter.SetTo(info);
if (ioctl(fd, PACKAGE_FS_OPERATION_GET_VOLUME_INFO, info,
bufferSize) != 0) {
ERROR("Volume::Init(): failed to get volume info: %s\n",
strerror(errno));
RETURN_ERROR(errno);
}
if (info->packagesDirectoryCount <= maxPackagesDirCount)
break;
maxPackagesDirCount = info->packagesDirectoryCount;
infoDeleter.Unset();
}
if (info->packagesDirectoryCount < 1) {
ERROR("Volume::Init(): got invalid volume info from packagefs\n");
RETURN_ERROR(B_BAD_VALUE);
}
fMountType = info->mountType;
fPackagesDirectories = new(std::nothrow) PackagesDirectory[
info->packagesDirectoryCount];
if (fPackagesDirectories == NULL)
RETURN_ERROR(B_NO_MEMORY);
fPackagesDirectoryCount = info->packagesDirectoryCount;
for (uint32 i = 0; i < info->packagesDirectoryCount; i++) {
fPackagesDirectories[i].Init(
node_ref(info->packagesDirectoryInfos[i].deviceID,
info->packagesDirectoryInfos[i].nodeID),
i == 0);
}
_packageRootRef.device = info->rootDeviceID;
_packageRootRef.node = info->rootDirectoryID;
return B_OK;
}
status_t
Volume::InitPackages(Listener* listener)
{
// node-monitor the volume's packages directory
status_t error = watch_node(&PackagesDirectoryRef(), B_WATCH_DIRECTORY,
BMessenger(this));
if (error == B_OK) {
fListener = listener;
} else {
ERROR("Volume::InitPackages(): failed to start watching the packages "
"directory of the volume at \"%s\": %s\n",
fPath.String(), strerror(error));
// Not good, but not fatal. Only the manual package operations in the
// packages directory won't work correctly.
}
// read the packages directory and get the active packages
int fd = OpenRootDirectory();
if (fd < 0) {
ERROR("Volume::InitPackages(): failed to open root directory: %s\n",
strerror(fd));
RETURN_ERROR(fd);
}
FileDescriptorCloser fdCloser(fd);
error = _ReadPackagesDirectory();
if (error != B_OK)
RETURN_ERROR(error);
error = _InitLatestState();
if (error != B_OK)
RETURN_ERROR(error);
error = _GetActivePackages(fd);
if (error != B_OK)
RETURN_ERROR(error);
// create the admin directory, if it doesn't exist yet
BDirectory packagesDirectory;
if (packagesDirectory.SetTo(&PackagesDirectoryRef()) == B_OK) {
if (!BEntry(&packagesDirectory, kAdminDirectoryName).Exists())
packagesDirectory.CreateDirectory(kAdminDirectoryName, NULL);
}
return B_OK;
}
status_t
Volume::AddPackagesToRepository(BSolverRepository& repository, bool activeOnly)
{
for (PackageFileNameHashTable::Iterator it
= fLatestState->ByFileNameIterator(); it.HasNext();) {
Package* package = it.Next();
if (activeOnly && !package->IsActive())
continue;
status_t error = repository.AddPackage(package->Info());
if (error != B_OK) {
ERROR("Volume::AddPackagesToRepository(): failed to add package %s "
"to repository: %s\n", package->FileName().String(),
strerror(error));
return error;
}
}
return B_OK;
}
void
Volume::InitialVerify(Volume* nextVolume, Volume* nextNextVolume)
{
INFORM("Volume::InitialVerify(%p, %p)\n", nextVolume, nextNextVolume);
// create the solver
BSolver* solver;
status_t error = BSolver::Create(solver);
if (error != B_OK) {
ERROR("Volume::InitialVerify(): failed to create solver: %s\n",
strerror(error));
return;
}
ObjectDeleter<BSolver> solverDeleter(solver);
// add a repository with all active packages
BSolverRepository repository;
error = _AddRepository(solver, repository, true, true);
if (error != B_OK) {
ERROR("Volume::InitialVerify(): failed to add repository: %s\n",
strerror(error));
return;
}
// add a repository for the next volume
BSolverRepository nextRepository;
if (nextVolume != NULL) {
nextRepository.SetPriority(1);
error = nextVolume->_AddRepository(solver, nextRepository, true, false);
if (error != B_OK) {
ERROR("Volume::InitialVerify(): failed to add repository: %s\n",
strerror(error));
return;
}
}
// add a repository for the next next volume
BSolverRepository nextNextRepository;
if (nextNextVolume != NULL) {
nextNextRepository.SetPriority(2);
error = nextNextVolume->_AddRepository(solver, nextNextRepository, true,
false);
if (error != B_OK) {
ERROR("Volume::InitialVerify(): failed to add repository: %s\n",
strerror(error));
return;
}
}
// verify
error = solver->VerifyInstallation();
if (error != B_OK) {
ERROR("Volume::InitialVerify(): failed to verify: %s\n",
strerror(error));
return;
}
if (!solver->HasProblems()) {
INFORM("Volume::InitialVerify(): volume at \"%s\" is consistent\n",
Path().String());
return;
}
// print the problems
// TODO: Notify the user ...
INFORM("Volume::InitialVerify(): volume at \"%s\" has problems:\n",
Path().String());
int32 problemCount = solver->CountProblems();
for (int32 i = 0; i < problemCount; i++) {
BSolverProblem* problem = solver->ProblemAt(i);
INFORM(" %" B_PRId32 ": %s\n", i + 1, problem->ToString().String());
int32 solutionCount = problem->CountSolutions();
for (int32 k = 0; k < solutionCount; k++) {
const BSolverProblemSolution* solution = problem->SolutionAt(k);
INFORM(" solution %" B_PRId32 ":\n", k + 1);
int32 elementCount = solution->CountElements();
for (int32 l = 0; l < elementCount; l++) {
const BSolverProblemSolutionElement* element
= solution->ElementAt(l);
INFORM(" - %s\n", element->ToString().String());
}
}
}
}
void
Volume::HandleGetLocationInfoRequest(BMessage* message)
{
AutoLocker<BLocker> locker(fLock);
// If the cached reply message is up-to-date, just send it.
int64 changeCount;
if (fLocationInfoReply.FindInt64("change count", &changeCount) == B_OK
&& changeCount == fChangeCount) {
locker.Unlock();
message->SendReply(&fLocationInfoReply, (BHandler*)NULL,
kCommunicationTimeout);
return;
}
// rebuild the reply message
fLocationInfoReply.MakeEmpty();
if (fLocationInfoReply.AddInt32("base directory device",
fRootDirectoryRef.device) != B_OK
|| fLocationInfoReply.AddInt64("base directory node",
fRootDirectoryRef.node) != B_OK
|| fLocationInfoReply.AddInt32("packages directory device",
PackagesDeviceID()) != B_OK
|| fLocationInfoReply.AddInt64("packages directory node",
PackagesDirectoryID()) != B_OK) {
return;
}
for (PackageFileNameHashTable::Iterator it
= fLatestState->ByFileNameIterator(); it.HasNext();) {
Package* package = it.Next();
const char* fieldName = package->IsActive()
? "latest active packages" : "latest inactive packages";
BMessage packageArchive;
if (package->Info().Archive(&packageArchive) != B_OK
|| fLocationInfoReply.AddMessage(fieldName, &packageArchive)
!= B_OK) {
return;
}
}
if (fActiveState != fLatestState) {
if (fPackagesDirectoryCount > 1) {
fLocationInfoReply.AddString("old state",
fPackagesDirectories[fPackagesDirectoryCount - 1].Name());
}
for (PackageFileNameHashTable::Iterator it
= fActiveState->ByFileNameIterator(); it.HasNext();) {
Package* package = it.Next();
if (!package->IsActive())
continue;
BMessage packageArchive;
if (package->Info().Archive(&packageArchive) != B_OK
|| fLocationInfoReply.AddMessage("currently active packages",
&packageArchive) != B_OK) {
return;
}
}
}
if (fLocationInfoReply.AddInt64("change count", fChangeCount) != B_OK)
return;
locker.Unlock();
message->SendReply(&fLocationInfoReply, (BHandler*)NULL,
kCommunicationTimeout);
}
void
Volume::HandleCommitTransactionRequest(BMessage* message)
{
// Prepare the reply in so far that we can at least set the error code
// without risk of failure.
BMessage reply(B_MESSAGE_COMMIT_TRANSACTION_REPLY);
if (reply.AddInt32("error", B_ERROR) != B_OK)
return;
// perform the request
PackageSet dummy;
CommitTransactionHandler handler(this, fPackageFileManager, fLatestState,
fLatestState == fActiveState, dummy, dummy);
int32 error;
try {
handler.HandleRequest(message, &reply);
_SetLatestState(handler.DetachVolumeState(),
handler.IsActiveVolumeState());
error = B_DAEMON_OK;
} catch (Exception& exception) {
error = exception.Error();
if (!exception.ErrorMessage().IsEmpty())
reply.AddString("error message", exception.ErrorMessage());
if (!exception.PackageName().IsEmpty())
reply.AddString("error package", exception.PackageName());
} catch (std::bad_alloc& exception) {
error = B_NO_MEMORY;
}
// revert on error
if (error != B_DAEMON_OK)
handler.Revert();
// send the reply
reply.ReplaceInt32("error", error);
message->SendReply(&reply, (BHandler*)NULL, kCommunicationTimeout);
}
void
Volume::PackageJobPending()
{
atomic_add(&fPendingPackageJobCount, 1);
}
void
Volume::PackageJobFinished()
{
atomic_add(&fPendingPackageJobCount, -1);
}
bool
Volume::IsPackageJobPending() const
{
return fPendingPackageJobCount != 0;
}
void
Volume::Unmounted()
{
if (fListener != NULL) {
stop_watching(BMessenger(this));
fListener = NULL;
}
if (BLooper* looper = Looper())
looper->RemoveHandler(this);
}
void
Volume::MessageReceived(BMessage* message)
{
switch (message->what) {
case B_NODE_MONITOR:
{
int32 opcode;
if (message->FindInt32("opcode", &opcode) != B_OK)
break;
switch (opcode) {
case B_ENTRY_CREATED:
_HandleEntryCreatedOrRemoved(message, true);
break;
case B_ENTRY_REMOVED:
_HandleEntryCreatedOrRemoved(message, false);
break;
case B_ENTRY_MOVED:
_HandleEntryMoved(message);
break;
default:
break;
}
break;
}
case kHandleNodeMonitorEvents:
if (fListener != NULL) {
if (system_time() >= fNodeMonitorEventHandleTime)
fListener->VolumeNodeMonitorEventOccurred(this);
}
break;
default:
BHandler::MessageReceived(message);
break;
}
}
BPackageInstallationLocation
Volume::Location() const
{
switch (fMountType) {
case PACKAGE_FS_MOUNT_TYPE_SYSTEM:
return B_PACKAGE_INSTALLATION_LOCATION_SYSTEM;
case PACKAGE_FS_MOUNT_TYPE_HOME:
return B_PACKAGE_INSTALLATION_LOCATION_HOME;
case PACKAGE_FS_MOUNT_TYPE_CUSTOM:
default:
return B_PACKAGE_INSTALLATION_LOCATION_ENUM_COUNT;
}
}
const node_ref&
Volume::PackagesDirectoryRef() const
{
return fPackagesDirectories[0].NodeRef();
}
PackageFileNameHashTable::Iterator
Volume::PackagesByFileNameIterator() const
{
return fLatestState->ByFileNameIterator();
}
int
Volume::OpenRootDirectory() const
{
BDirectory directory;
status_t error = directory.SetTo(&fRootDirectoryRef);
if (error != B_OK) {
ERROR("Volume::OpenRootDirectory(): failed to open root directory: "
"%s\n", strerror(error));
RETURN_ERROR(error);
}
return directory.Dup();
}
void
Volume::ProcessPendingNodeMonitorEvents()
{
// get the events
NodeMonitorEventList events;
{
AutoLocker<BLocker> eventsLock(fPendingNodeMonitorEventsLock);
events.MoveFrom(&fPendingNodeMonitorEvents);
}
// process them
while (NodeMonitorEvent* event = events.RemoveHead()) {
ObjectDeleter<NodeMonitorEvent> eventDeleter(event);
if (event->WasCreated())
_PackagesEntryCreated(event->EntryName());
else
_PackagesEntryRemoved(event->EntryName());
}
}
bool
Volume::HasPendingPackageActivationChanges() const
{
return !fPackagesToBeActivated.empty() || !fPackagesToBeDeactivated.empty();
}
void
Volume::ProcessPendingPackageActivationChanges()
{
if (!HasPendingPackageActivationChanges())
return;
// perform the request
CommitTransactionHandler handler(this, fPackageFileManager, fLatestState,
fLatestState == fActiveState, fPackagesToBeActivated,
fPackagesToBeDeactivated);
int32 error;
try {
handler.HandleRequest(fPackagesToBeActivated, fPackagesToBeDeactivated);
_SetLatestState(handler.DetachVolumeState(),
handler.IsActiveVolumeState());
error = B_DAEMON_OK;
} catch (Exception& exception) {
error = exception.Error();
ERROR("Volume::ProcessPendingPackageActivationChanges(): package "
"activation failed: %s\n", exception.ToString().String());
// TODO: Notify the user!
} catch (std::bad_alloc& exception) {
error = B_NO_MEMORY;
ERROR("Volume::ProcessPendingPackageActivationChanges(): package "
"activation failed: out of memory\n");
// TODO: Notify the user!
}
// revert on error
if (error != B_DAEMON_OK)
handler.Revert();
// clear the activation/deactivation sets in any event
fPackagesToBeActivated.clear();
fPackagesToBeDeactivated.clear();
}
void
Volume::ClearPackageActivationChanges()
{
fPackagesToBeActivated.clear();
fPackagesToBeDeactivated.clear();
}
status_t
Volume::CreateTransaction(BPackageInstallationLocation location,
BActivationTransaction& _transaction, BDirectory& _transactionDirectory)
{
// open admin directory
BDirectory adminDirectory;
status_t error = _OpenPackagesSubDirectory(
RelativePath(kAdminDirectoryName), true, adminDirectory);
if (error != B_OK)
return error;
// create a transaction directory
int uniqueId = 1;
BString directoryName;
for (;; uniqueId++) {
directoryName.SetToFormat("transaction-%d", uniqueId);
if (directoryName.IsEmpty())
return B_NO_MEMORY;
error = adminDirectory.CreateDirectory(directoryName,
&_transactionDirectory);
if (error == B_OK)
break;
if (error != B_FILE_EXISTS)
return error;
}
// init the transaction
error = _transaction.SetTo(location, fChangeCount, directoryName);
if (error != B_OK) {
BEntry entry;
_transactionDirectory.GetEntry(&entry);
_transactionDirectory.Unset();
if (entry.InitCheck() == B_OK)
entry.Remove();
return error;
}
return B_OK;
}
void
Volume::CommitTransaction(const BActivationTransaction& transaction,
const PackageSet& packagesAlreadyAdded,
const PackageSet& packagesAlreadyRemoved,
BDaemonClient::BCommitTransactionResult& _result)
{
// perform the request
CommitTransactionHandler handler(this, fPackageFileManager, fLatestState,
fLatestState == fActiveState, packagesAlreadyAdded,
packagesAlreadyRemoved);
int32 error;
try {
handler.HandleRequest(transaction, NULL);
_SetLatestState(handler.DetachVolumeState(),
handler.IsActiveVolumeState());
error = B_DAEMON_OK;
_result.SetTo(error, BString(), BString(),
handler.OldStateDirectoryName());
} catch (Exception& exception) {
error = exception.Error();
_result.SetTo(error, exception.ErrorMessage(), exception.PackageName(),
BString());
} catch (std::bad_alloc& exception) {
error = B_NO_MEMORY;
_result.SetTo(error, BString(), BString(), BString());
}
// revert on error
if (error != B_DAEMON_OK)
handler.Revert();
}
void
Volume::_HandleEntryCreatedOrRemoved(const BMessage* message, bool created)
{
// only moves to or from our packages directory are interesting
int32 deviceID;
int64 directoryID;
const char* name;
if (message->FindInt32("device", &deviceID) != B_OK
|| message->FindInt64("directory", &directoryID) != B_OK
|| message->FindString("name", &name) != B_OK
|| node_ref(deviceID, directoryID) != PackagesDirectoryRef()) {
return;
}
_QueueNodeMonitorEvent(name, created);
}
void
Volume::_HandleEntryMoved(const BMessage* message)
{
int32 deviceID;
int64 fromDirectoryID;
int64 toDirectoryID;
const char* fromName;
const char* toName;
if (message->FindInt32("device", &deviceID) != B_OK
|| message->FindInt64("from directory", &fromDirectoryID) != B_OK
|| message->FindInt64("to directory", &toDirectoryID) != B_OK
|| message->FindString("from name", &fromName) != B_OK
|| message->FindString("name", &toName) != B_OK
|| deviceID != PackagesDeviceID()
|| (fromDirectoryID != PackagesDirectoryID()
&& toDirectoryID != PackagesDirectoryID())) {
return;
}
AutoLocker<BLocker> eventsLock(fPendingNodeMonitorEventsLock);
// make sure for a move the two events cannot get split
if (fromDirectoryID == PackagesDirectoryID())
_QueueNodeMonitorEvent(fromName, false);
if (toDirectoryID == PackagesDirectoryID())
_QueueNodeMonitorEvent(toName, true);
}
void
Volume::_QueueNodeMonitorEvent(const BString& name, bool wasCreated)
{
if (name.IsEmpty()) {
ERROR("Volume::_QueueNodeMonitorEvent(): got empty name.\n");
return;
}
// ignore entries that don't have the ".hpkg" extension
if (!name.EndsWith(kPackageFileNameExtension))
return;
NodeMonitorEvent* event
= new(std::nothrow) NodeMonitorEvent(name, wasCreated);
if (event == NULL) {
ERROR("Volume::_QueueNodeMonitorEvent(): out of memory.\n");
return;
}
AutoLocker<BLocker> eventsLock(fPendingNodeMonitorEventsLock);
fPendingNodeMonitorEvents.Add(event);
eventsLock.Unlock();
fNodeMonitorEventHandleTime
= system_time() + kNodeMonitorEventHandlingDelay;
BMessage message(kHandleNodeMonitorEvents);
BMessageRunner::StartSending(this, &message, kNodeMonitorEventHandlingDelay,
1);
}
void
Volume::_PackagesEntryCreated(const char* name)
{
INFORM("Volume::_PackagesEntryCreated(\"%s\")\n", name);
// Ignore the event, if the package is already known.
Package* package = fLatestState->FindPackage(name);
if (package != NULL) {
if (package->File()->EntryCreatedIgnoreLevel() > 0) {
package->File()->DecrementEntryCreatedIgnoreLevel();
} else {
WARN("node monitoring created event for already known entry "
"\"%s\"\n", name);
}
return;
}
status_t error = fPackageFileManager->CreatePackage(
NotOwningEntryRef(PackagesDirectoryRef(), name),
package);
if (error != B_OK) {
ERROR("failed to init package for file \"%s\"\n", name);
return;
}
fLock.Lock();
fLatestState->AddPackage(package);
fChangeCount++;
fLock.Unlock();
try {
fPackagesToBeActivated.insert(package);
} catch (std::bad_alloc& exception) {
ERROR("out of memory\n");
return;
}
}
void
Volume::_PackagesEntryRemoved(const char* name)
{
INFORM("Volume::_PackagesEntryRemoved(\"%s\")\n", name);
Package* package = fLatestState->FindPackage(name);
if (package == NULL)
return;
// Ignore the event, if we generated it ourselves.
if (package->File()->EntryRemovedIgnoreLevel() > 0) {
package->File()->DecrementEntryRemovedIgnoreLevel();
return;
}
// Remove the package from the packages-to-be-activated set, if it is in
// there (unlikely, unless we see a create-remove-create sequence).
PackageSet::iterator it = fPackagesToBeActivated.find(package);
if (it != fPackagesToBeActivated.end())
fPackagesToBeActivated.erase(it);
// If the package isn't active, just remove it for good.
if (!package->IsActive()) {
AutoLocker<BLocker> locker(fLock);
fLatestState->RemovePackage(package);
fChangeCount++;
delete package;
return;
}
// The package must be deactivated.
try {
fPackagesToBeDeactivated.insert(package);
} catch (std::bad_alloc& exception) {
ERROR("out of memory\n");
return;
}
}
status_t
Volume::_ReadPackagesDirectory()
{
BDirectory directory;
status_t error = directory.SetTo(&PackagesDirectoryRef());
if (error != B_OK) {
ERROR("Volume::_ReadPackagesDirectory(): failed to open packages "
"directory: %s\n", strerror(error));
RETURN_ERROR(error);
}
entry_ref entry;
while (directory.GetNextRef(&entry) == B_OK) {
if (!BString(entry.name).EndsWith(kPackageFileNameExtension))
continue;
Package* package;
status_t error = fPackageFileManager->CreatePackage(entry, package);
if (error == B_OK) {