-
-
Notifications
You must be signed in to change notification settings - Fork 340
/
Volume.cpp
2461 lines (2100 loc) · 68.3 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, 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 <grp.h>
#include <pwd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <string>
#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 <CopyEngine.h>
#include <NotOwningEntryRef.h>
#include <package/DaemonDefs.h>
#include <package/PackagesDirectoryDefs.h>
#include <RemoveEngine.h>
#include "DebugSupport.h"
#include "Exception.h"
#include "FSTransaction.h"
using namespace BPackageKit::BPrivate;
typedef std::set<std::string> StringSet;
static const char* const kPackageFileNameExtension = ".hpkg";
static const char* const kAdminDirectoryName
= PACKAGES_DIRECTORY_ADMIN_DIRECTORY;
static const char* const kActivationFileName
= PACKAGES_DIRECTORY_ACTIVATION_FILE;
static const char* const kTemporaryActivationFileName
= PACKAGES_DIRECTORY_ACTIVATION_FILE ".tmp";
static const char* const kWritableFilesDirectoryName = "writable-files";
static const char* const kPackageFileAttribute = "SYS:PACKAGE";
static const bigtime_t kHandleNodeMonitorEvents = 'nmon';
static const bigtime_t kNodeMonitorEventHandlingDelay = 500000;
static const bigtime_t kCommunicationTimeout = 1000000;
// #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 - CommitTransactionHandler
struct Volume::CommitTransactionHandler {
CommitTransactionHandler(Volume* volume,
const PackageSet& packagesAlreadyAdded,
const PackageSet& packagesAlreadyRemoved)
:
fVolume(volume),
fPackagesToActivate(),
fPackagesToDeactivate(),
fAddedPackages(),
fRemovedPackages(),
fPackagesAlreadyAdded(packagesAlreadyAdded),
fPackagesAlreadyRemoved(packagesAlreadyRemoved),
fAddedGroups(),
fAddedUsers(),
fFSTransaction()
{
}
~CommitTransactionHandler()
{
// Delete Package objects we created in case of error (on success
// fPackagesToActivate will be empty).
int32 count = fPackagesToActivate.CountItems();
for (int32 i = 0; i < count; i++) {
Package* package = fPackagesToActivate.ItemAt(i);
if (fPackagesAlreadyAdded.find(package)
== fPackagesAlreadyAdded.end()) {
delete package;
}
}
}
void HandleRequest(BMessage* request, BMessage* reply)
{
status_t error;
BActivationTransaction transaction(request, &error);
if (error == B_OK)
error = transaction.InitCheck();
if (error != B_OK) {
if (error == B_NO_MEMORY)
throw Exception(B_NO_MEMORY);
throw Exception(B_DAEMON_BAD_REQUEST);
}
HandleRequest(transaction, reply);
}
void HandleRequest(const BActivationTransaction& transaction,
BMessage* reply)
{
// check the change count
if (transaction.ChangeCount() != fVolume->fChangeCount)
throw Exception(B_DAEMON_CHANGE_COUNT_MISMATCH);
// collect the packages to deactivate
_GetPackagesToDeactivate(transaction);
// read the packages to activate
_ReadPackagesToActivate(transaction);
// anything to do at all?
if (fPackagesToActivate.IsEmpty() && fPackagesToDeactivate.empty()) {
throw Exception(B_DAEMON_BAD_REQUEST,
"no packages to activate or deactivate");
}
_ApplyChanges(reply);
}
void HandleRequest(const PackageSet& packagesAdded,
const PackageSet& packagesRemoved)
{
// Copy package sets to fPackagesToActivate/fPackagesToDeactivate. The
// given sets are assumed to be identical to the ones specified in the
// constructor invocation (fPackagesAlreadyAdded,
// fPackagesAlreadyRemoved).
for (PackageSet::const_iterator it = packagesAdded.begin();
it != packagesAdded.end(); ++it) {
if (!fPackagesToActivate.AddItem(*it))
throw std::bad_alloc();
}
fPackagesToDeactivate = packagesRemoved;
_ApplyChanges(NULL);
}
void Revert()
{
// move packages to activate back to transaction directory
_RevertAddPackagesToActivate();
// move packages to deactivate back to packages directory
_RevertRemovePackagesToDeactivate();
// revert user and group changes
_RevertUserGroupChanges();
// Revert all other FS operations, i.e. the writable files changes as
// well as the creation of the old state directory.
fFSTransaction.RollBack();
}
const BString& OldStateDirectoryName() const
{
return fOldStateDirectoryName;
}
private:
typedef BObjectList<Package> PackageList;
void _GetPackagesToDeactivate(const BActivationTransaction& transaction)
{
// get the number of packages to deactivate
const BStringList& packagesToDeactivate
= transaction.PackagesToDeactivate();
int32 packagesToDeactivateCount = packagesToDeactivate.CountStrings();
if (packagesToDeactivateCount == 0)
return;
for (int32 i = 0; i < packagesToDeactivateCount; i++) {
BString packageName = packagesToDeactivate.StringAt(i);
Package* package = fVolume->fPackagesByFileName.Lookup(packageName);
if (package == NULL) {
throw Exception(B_DAEMON_NO_SUCH_PACKAGE, "no such package",
packageName);
}
fPackagesToDeactivate.insert(package);
if (fPackagesAlreadyRemoved.find(package)
== fPackagesAlreadyRemoved.end()) {
package->IncrementEntryRemovedIgnoreLevel();
}
}
}
void _ReadPackagesToActivate(const BActivationTransaction& transaction)
{
// get the number of packages to activate
const BStringList& packagesToActivate
= transaction.PackagesToActivate();
int32 packagesToActivateCount = packagesToActivate.CountStrings();
if (packagesToActivateCount == 0)
return;
// check the transaction directory name -- we only allow a simple
// subdirectory of the admin directory
const BString& transactionDirectoryName
= transaction.TransactionDirectoryName();
if (transactionDirectoryName.IsEmpty()
|| transactionDirectoryName.FindFirst('/') >= 0
|| transactionDirectoryName == "."
|| transactionDirectoryName == "..") {
throw Exception(B_DAEMON_BAD_REQUEST);
}
// open the directory
RelativePath directoryPath(kAdminDirectoryName,
transactionDirectoryName);
BDirectory directory;
status_t error = fVolume->_OpenPackagesSubDirectory(directoryPath,
false, directory);
if (error != B_OK)
throw Exception(error, "failed to open transaction directory");
error = directory.GetNodeRef(&fTransactionDirectoryRef);
if (error != B_OK) {
throw Exception(error,
"failed to get transaction directory node ref");
}
// read the packages
for (int32 i = 0; i < packagesToActivateCount; i++) {
BString packageName = packagesToActivate.StringAt(i);
// make sure it doesn't clash with an already existing package
Package* package = fVolume->fPackagesByFileName.Lookup(packageName);
if (package != NULL) {
if (fPackagesAlreadyAdded.find(package)
!= fPackagesAlreadyAdded.end()) {
if (!fPackagesToActivate.AddItem(package))
throw Exception(B_NO_MEMORY);
continue;
}
if (fPackagesToDeactivate.find(package)
== fPackagesToDeactivate.end()) {
throw Exception(B_DAEMON_PACKAGE_ALREADY_EXISTS, NULL,
packageName);
}
}
// read the package
entry_ref entryRef;
entryRef.device = fTransactionDirectoryRef.device;
entryRef.directory = fTransactionDirectoryRef.node;
if (entryRef.set_name(packageName) != B_OK)
throw Exception(B_NO_MEMORY);
package = new(std::nothrow) Package;
if (package == NULL || !fPackagesToActivate.AddItem(package)) {
delete package;
throw Exception(B_NO_MEMORY);
}
error = package->Init(entryRef);
if (error != B_OK)
throw Exception(error, "failed to read package", packageName);
package->IncrementEntryCreatedIgnoreLevel();
}
}
void _ApplyChanges(BMessage* reply)
{
// create an old state directory
_CreateOldStateDirectory(reply);
// move packages to deactivate to old state directory
_RemovePackagesToDeactivate();
// move packages to activate to packages directory
_AddPackagesToActivate();
// activate/deactivate packages
fVolume->_ChangePackageActivation(fAddedPackages, fRemovedPackages);
// run post-installation scripts
_RunPostInstallScripts();
// removed packages have been deleted, new packages shall not be deleted
fAddedPackages.clear();
fRemovedPackages.clear();
fPackagesToActivate.MakeEmpty(false);
fPackagesToDeactivate.clear();
}
void _CreateOldStateDirectory(BMessage* reply)
{
// construct a nice name from the current date and time
time_t nowSeconds = time(NULL);
struct tm now;
BString baseName;
if (localtime_r(&nowSeconds, &now) != NULL) {
baseName.SetToFormat("state_%d-%02d-%02d_%02d:%02d:%02d",
1900 + now.tm_year, now.tm_mon + 1, now.tm_mday, now.tm_hour,
now.tm_min, now.tm_sec);
} else
baseName = "state";
if (baseName.IsEmpty())
throw Exception(B_NO_MEMORY);
// make sure the directory doesn't exist yet
BDirectory adminDirectory;
status_t error = fVolume->_OpenPackagesSubDirectory(
RelativePath(kAdminDirectoryName), true, adminDirectory);
if (error != B_OK)
throw Exception(error, "failed to open administrative directory");
int uniqueId = 1;
BString directoryName = baseName;
while (BEntry(&adminDirectory, directoryName).Exists()) {
directoryName.SetToFormat("%s-%d", baseName.String(), uniqueId++);
if (directoryName.IsEmpty())
throw Exception(B_NO_MEMORY);
}
// create the directory
FSTransaction::CreateOperation createOldStateDirectoryOperation(
&fFSTransaction, FSUtils::Entry(adminDirectory, directoryName));
error = adminDirectory.CreateDirectory(directoryName,
&fOldStateDirectory);
if (error != B_OK)
throw Exception(error, "failed to create old state directory");
createOldStateDirectoryOperation.Finished();
fOldStateDirectoryName = directoryName;
// write the old activation file
BEntry activationFile;
error = fVolume->_WriteActivationFile(
RelativePath(kAdminDirectoryName, directoryName),
kActivationFileName, PackageSet(), PackageSet(), activationFile);
if (error != B_OK)
throw Exception(error, "failed to write old activation file");
// add the old state directory to the reply
if (reply != NULL) {
error = reply->AddString("old state", fOldStateDirectoryName);
if (error != B_OK)
throw Exception(error, "failed to add field to reply");
}
}
void _RemovePackagesToDeactivate()
{
if (fPackagesToDeactivate.empty())
return;
for (PackageSet::const_iterator it = fPackagesToDeactivate.begin();
it != fPackagesToDeactivate.end(); ++it) {
Package* package = *it;
if (fPackagesAlreadyRemoved.find(package)
!= fPackagesAlreadyRemoved.end()) {
fRemovedPackages.insert(package);
continue;
}
// get a BEntry for the package
NotOwningEntryRef entryRef(fVolume->fPackagesDirectoryRef,
package->FileName());
BEntry entry;
status_t error = entry.SetTo(&entryRef);
if (error != B_OK) {
throw Exception(error, "failed to get package entry",
package->FileName());
}
// move entry
fRemovedPackages.insert(package);
error = entry.MoveTo(&fOldStateDirectory);
if (error != B_OK) {
fRemovedPackages.erase(package);
throw Exception(error,
"failed to move old package from packages directory",
package->FileName());
}
}
}
void _AddPackagesToActivate()
{
if (fPackagesToActivate.IsEmpty())
return;
// open packages directory
BDirectory packagesDirectory;
status_t error
= packagesDirectory.SetTo(&fVolume->fPackagesDirectoryRef);
if (error != B_OK)
throw Exception(error, "failed to open packages directory");
int32 count = fPackagesToActivate.CountItems();
for (int32 i = 0; i < count; i++) {
Package* package = fPackagesToActivate.ItemAt(i);
if (fPackagesAlreadyAdded.find(package)
!= fPackagesAlreadyAdded.end()) {
fAddedPackages.insert(package);
_PreparePackageToActivate(package);
continue;
}
// get a BEntry for the package
entry_ref entryRef;
entryRef.device = fTransactionDirectoryRef.device;
entryRef.directory = fTransactionDirectoryRef.node;
if (entryRef.set_name(package->FileName()) != B_OK)
throw Exception(B_NO_MEMORY);
BEntry entry;
error = entry.SetTo(&entryRef);
if (error != B_OK) {
throw Exception(error, "failed to get package entry",
package->FileName());
}
// move entry
fAddedPackages.insert(package);
error = entry.MoveTo(&packagesDirectory);
if (error != B_OK) {
fAddedPackages.erase(package);
throw Exception(error,
"failed to move new package to packages directory",
package->FileName());
}
// also add the package to the volume
fVolume->_AddPackage(package);
_PreparePackageToActivate(package);
}
}
void _PreparePackageToActivate(Package* package)
{
// add groups
const BStringList& groups = package->Info().Groups();
int32 count = groups.CountStrings();
for (int32 i = 0; i < count; i++)
_AddGroup(package, groups.StringAt(i));
// add users
const BObjectList<BUser>& users = package->Info().Users();
for (int32 i = 0; const BUser* user = users.ItemAt(i); i++)
_AddUser(package, *user);
// handle global writable files
_AddGlobalWritableFiles(package);
}
void _AddGroup(Package* package, const BString& groupName)
{
// Check whether the group already exists.
char buffer[256];
struct group groupBuffer;
struct group* groupFound;
int error = getgrnam_r(groupName, &groupBuffer, buffer, sizeof(buffer),
&groupFound);
if ((error == 0 && groupFound != NULL) || error == ERANGE)
return;
// add it
fAddedGroups.insert(groupName.String());
std::string commandLine("groupadd ");
commandLine += FSUtils::ShellEscapeString(groupName).String();
if (system(commandLine.c_str()) != 0) {
fAddedGroups.erase(groupName.String());
throw Exception(error,
BString().SetToFormat("failed to add group \%s\"",
groupName.String()),
package->FileName());
}
}
void _AddUser(Package* package, const BUser& user)
{
// Check whether the user already exists.
char buffer[256];
struct passwd passwdBuffer;
struct passwd* passwdFound;
int error = getpwnam_r(user.Name(), &passwdBuffer, buffer,
sizeof(buffer), &passwdFound);
if ((error == 0 && passwdFound != NULL) || error == ERANGE)
return;
// add it
fAddedUsers.insert(user.Name().String());
std::string commandLine("useradd ");
if (!user.RealName().IsEmpty()) {
commandLine += std::string("-n ")
+ FSUtils::ShellEscapeString(user.RealName()).String() + " ";
}
if (!user.Home().IsEmpty()) {
commandLine += std::string("-d ")
+ FSUtils::ShellEscapeString(user.Home()).String() + " ";
}
if (!user.Shell().IsEmpty()) {
commandLine += std::string("-s ")
+ FSUtils::ShellEscapeString(user.Shell()).String() + " ";
}
if (!user.Groups().IsEmpty()) {
commandLine += std::string("-g ")
+ FSUtils::ShellEscapeString(user.Groups().First()).String()
+ " ";
}
commandLine += FSUtils::ShellEscapeString(user.Name()).String();
if (system(commandLine.c_str()) != 0) {
fAddedUsers.erase(user.Name().String());
throw Exception(error,
BString().SetToFormat("failed to add user \%s\"",
user.Name().String()),
package->FileName());
}
// add the supplementary groups
int32 groupCount = user.Groups().CountStrings();
for (int32 i = 1; i < groupCount; i++) {
commandLine = std::string("groupmod -A ")
+ FSUtils::ShellEscapeString(user.Name()).String()
+ " "
+ FSUtils::ShellEscapeString(user.Groups().StringAt(i))
.String();
if (system(commandLine.c_str()) != 0) {
fAddedUsers.erase(user.Name().String());
throw Exception(error,
BString().SetToFormat("failed to add user \%s\" to group "
"\"%s\"", user.Name().String(),
user.Groups().StringAt(i).String()),
package->FileName());
}
}
}
void _AddGlobalWritableFiles(Package* package)
{
// get the list of included files
const BObjectList<BGlobalWritableFileInfo>& files
= package->Info().GlobalWritableFileInfos();
BStringList contentPaths;
for (int32 i = 0; const BGlobalWritableFileInfo* file = files.ItemAt(i);
i++) {
if (file->IsIncluded() && !contentPaths.Add(file->Path()))
throw std::bad_alloc();
}
if (contentPaths.IsEmpty())
return;
// Open the root directory of the installation location where we will
// extract the files -- that's the volume's root directory.
BDirectory rootDirectory;
status_t error = rootDirectory.SetTo(&fVolume->fRootDirectoryRef);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to get the root directory "
"for writable files"),
package->FileName());
}
// Open writable-files directory in the administrative directory.
if (fWritableFilesDirectory.InitCheck() != B_OK) {
error = fVolume->_OpenPackagesSubDirectory(
RelativePath(kAdminDirectoryName, kWritableFilesDirectoryName),
true, fWritableFilesDirectory);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to get the backup directory "
"for writable files"),
package->FileName());
}
}
// extract files into a subdir of the writable-files directory
BDirectory extractedFilesDirectory;
_ExtractPackageContent(package, contentPaths,
fWritableFilesDirectory, extractedFilesDirectory);
for (int32 i = 0; const BGlobalWritableFileInfo* file = files.ItemAt(i);
i++) {
if (file->IsIncluded()) {
_AddGlobalWritableFile(package, *file, rootDirectory,
extractedFilesDirectory);
}
}
}
void _AddGlobalWritableFile(Package* package,
const BGlobalWritableFileInfo& file, const BDirectory& rootDirectory,
const BDirectory& extractedFilesDirectory)
{
// Map the path name to the actual target location. Currently this only
// concerns "settings/", which is mapped to "settings/global/".
BString targetPath(file.Path());
if (fVolume->fMountType == PACKAGE_FS_MOUNT_TYPE_HOME) {
if (targetPath == "settings"
|| targetPath.StartsWith("settings/")) {
targetPath.Insert("/global", 8);
if (targetPath.Length() == file.Path().Length())
throw std::bad_alloc();
}
}
// open parent directory of the source entry
const char* lastSlash = strrchr(file.Path(), '/');
const BDirectory* sourceDirectory;
BDirectory stackSourceDirectory;
if (lastSlash != NULL) {
sourceDirectory = &stackSourceDirectory;
BString sourceParentPath(file.Path(),
lastSlash - file.Path().String());
if (sourceParentPath.Length() == 0)
throw std::bad_alloc();
status_t error = stackSourceDirectory.SetTo(
&extractedFilesDirectory, sourceParentPath);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to open directory \"%s\"",
_GetPath(
FSUtils::Entry(extractedFilesDirectory,
sourceParentPath),
sourceParentPath).String()),
package->FileName());
}
} else {
sourceDirectory = &extractedFilesDirectory;
}
// open parent directory of the target entry -- create, if necessary
FSUtils::Path relativeSourcePath(file.Path());
lastSlash = strrchr(targetPath, '/');
if (lastSlash != NULL) {
BString targetParentPath(targetPath,
lastSlash - targetPath.String());
if (targetParentPath.Length() == 0)
throw std::bad_alloc();
BDirectory targetDirectory;
status_t error = FSUtils::OpenSubDirectory(rootDirectory,
RelativePath(targetParentPath), true, targetDirectory);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to open/create directory "
"\"%s\"",
_GetPath(
FSUtils::Entry(rootDirectory,targetParentPath),
targetParentPath).String()),
package->FileName());
}
_AddGlobalWritableFileRecurse(package, *sourceDirectory,
relativeSourcePath, targetDirectory, lastSlash + 1,
file.UpdateType());
} else {
_AddGlobalWritableFileRecurse(package, *sourceDirectory,
relativeSourcePath, rootDirectory, targetPath,
file.UpdateType());
}
}
void _AddGlobalWritableFileRecurse(Package* package,
const BDirectory& sourceDirectory, FSUtils::Path& relativeSourcePath,
const BDirectory& targetDirectory, const char* targetName,
BWritableFileUpdateType updateType)
{
// * If the file doesn't exist, just copy the extracted one.
// * If the file does exist, compare with the previous original version:
// * If unchanged, just overwrite it.
// * If changed, leave it to the user for now. When we support merging
// first back the file up, then try the merge.
// Check whether the target location exists and what type the entry at
// both locations are.
struct stat targetStat;
if (targetDirectory.GetStatFor(targetName, &targetStat) != B_OK) {
// target doesn't exist -- just copy
PRINT("Volume::CommitTransactionHandler::_AddGlobalWritableFile(): "
"couldn't get stat for writable file, copying...\n");
FSTransaction::CreateOperation copyOperation(&fFSTransaction,
FSUtils::Entry(targetDirectory, targetName));
status_t error = BCopyEngine(BCopyEngine::COPY_RECURSIVELY)
.CopyEntry(
FSUtils::Entry(sourceDirectory, relativeSourcePath.Leaf()),
FSUtils::Entry(targetDirectory, targetName));
if (error != B_OK) {
if (targetDirectory.GetStatFor(targetName, &targetStat) == B_OK)
copyOperation.Finished();
throw Exception(error,
BString().SetToFormat("failed to copy entry \"%s\"",
_GetPath(
FSUtils::Entry(sourceDirectory,
relativeSourcePath.Leaf()),
relativeSourcePath).String()),
package->FileName());
}
copyOperation.Finished();
return;
}
struct stat sourceStat;
status_t error = sourceDirectory.GetStatFor(relativeSourcePath.Leaf(),
&sourceStat);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to get stat data for entry "
"\"%s\"",
_GetPath(
FSUtils::Entry(targetDirectory, targetName),
targetName).String()),
package->FileName());
}
if ((sourceStat.st_mode & S_IFMT) != (targetStat.st_mode & S_IFMT)
|| (!S_ISDIR(sourceStat.st_mode) && !S_ISREG(sourceStat.st_mode)
&& !S_ISLNK(sourceStat.st_mode))) {
// Source and target entry types don't match or this is an entry
// we cannot handle. The user must handle this manually.
PRINT("Volume::CommitTransactionHandler::_AddGlobalWritableFile(): "
"writable file exists, but type doesn't match previous type\n");
// TODO: Notify user!
return;
}
if (S_ISDIR(sourceStat.st_mode)) {
// entry is a directory -- recurse
BDirectory sourceSubDirectory;
error = sourceSubDirectory.SetTo(&sourceDirectory,
relativeSourcePath.Leaf());
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to open directory \"%s\"",
_GetPath(
FSUtils::Entry(sourceDirectory,
relativeSourcePath.Leaf()),
relativeSourcePath).String()),
package->FileName());
}
BDirectory targetSubDirectory;
error = targetSubDirectory.SetTo(&targetDirectory, targetName);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to open directory \"%s\"",
_GetPath(
FSUtils::Entry(targetDirectory, targetName),
targetName).String()),
package->FileName());
}
entry_ref entry;
while (sourceSubDirectory.GetNextRef(&entry) == B_OK) {
relativeSourcePath.AppendComponent(entry.name);
_AddGlobalWritableFileRecurse(package, sourceSubDirectory,
relativeSourcePath, targetSubDirectory, entry.name,
updateType);
relativeSourcePath.RemoveLastComponent();
}
PRINT("Volume::CommitTransactionHandler::_AddGlobalWritableFile(): "
"writable directory, recursion done\n");
return;
}
// get the package the target file originated from
BString originalPackage;
if (BNode(&targetDirectory, targetName).ReadAttrString(
kPackageFileAttribute, &originalPackage) != B_OK) {
// Can't determine the original package. The user must handle this
// manually.
// TODO: Notify user, if not B_WRITABLE_FILE_UPDATE_TYPE_KEEP_OLD!
PRINT("Volume::CommitTransactionHandler::_AddGlobalWritableFile(): "
"failed to get SYS:PACKAGE attribute\n");
return;
}
// If that's our package, we're happy.
if (originalPackage == package->RevisionedNameThrows()) {
PRINT("Volume::CommitTransactionHandler::_AddGlobalWritableFile(): "
"file tagged with same package version we're activating\n");
return;
}
// Check, whether the writable-files directory for the original package
// exists.
BString originalRelativeSourcePath = BString().SetToFormat("%s/%s",
originalPackage.String(), relativeSourcePath.ToCString());
if (originalRelativeSourcePath.IsEmpty())
throw std::bad_alloc();
struct stat originalPackageStat;
if (fWritableFilesDirectory.GetStatFor(originalRelativeSourcePath,
&originalPackageStat) != B_OK
|| (sourceStat.st_mode & S_IFMT)
!= (originalPackageStat.st_mode & S_IFMT)) {
// Original entry doesn't exist (either we don't have the data from
// the original package or the entry really didn't exist) or its
// type differs from the expected one. The user must handle this
// manually.
PRINT("Volume::CommitTransactionHandler::_AddGlobalWritableFile(): "
"original \"%s\" doesn't exist or has other type\n",
_GetPath(FSUtils::Entry(fWritableFilesDirectory,
originalRelativeSourcePath),
originalRelativeSourcePath).String());
return;
// TODO: Notify user!
}
if (S_ISREG(sourceStat.st_mode)) {
// compare file content
bool equal;
error = FSUtils::CompareFileContent(
FSUtils::Entry(fWritableFilesDirectory,
originalRelativeSourcePath),
FSUtils::Entry(targetDirectory, targetName),
equal);
// TODO: Merge support!
if (error != B_OK || !equal) {
// The comparison failed or the files differ. The user must
// handle this manually.
PRINT("Volume::CommitTransactionHandler::"
"_AddGlobalWritableFile(): "
"file comparison failed (%s) or files aren't equal\n",
strerror(error));
return;
// TODO: Notify user, if not B_WRITABLE_FILE_UPDATE_TYPE_KEEP_OLD!
}
} else {
// compare symlinks
bool equal;
error = FSUtils::CompareSymLinks(
FSUtils::Entry(fWritableFilesDirectory,
originalRelativeSourcePath),
FSUtils::Entry(targetDirectory, targetName),
equal);
if (error != B_OK || !equal) {
// The comparison failed or the symlinks differ. The user must
// handle this manually.
PRINT("Volume::CommitTransactionHandler::"
"_AddGlobalWritableFile(): "
"symlink comparison failed (%s) or symlinks aren't equal\n",
strerror(error));
return;
// TODO: Notify user, if not B_WRITABLE_FILE_UPDATE_TYPE_KEEP_OLD!
}
}
// Replace the existing file/symlink. We do that in two steps: First
// copy the new file to a neighoring location, then move-replace the
// old file.
BString tempTargetName;
tempTargetName.SetToFormat("%s.%s", targetName,
package->RevisionedNameThrows().String());
if (tempTargetName.IsEmpty())
throw std::bad_alloc();
// copy
FSTransaction::CreateOperation copyOperation(&fFSTransaction,
FSUtils::Entry(targetDirectory, tempTargetName));
error = BCopyEngine(BCopyEngine::UNLINK_DESTINATION).CopyEntry(
FSUtils::Entry(sourceDirectory, relativeSourcePath.Leaf()),
FSUtils::Entry(targetDirectory, tempTargetName));
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to copy entry \"%s\"",
_GetPath(
FSUtils::Entry(sourceDirectory,
relativeSourcePath.Leaf()),
relativeSourcePath).String()),
package->FileName());
}
copyOperation.Finished();
// rename
FSTransaction::RemoveOperation renameOperation(&fFSTransaction,
FSUtils::Entry(targetDirectory, targetName),
FSUtils::Entry(fWritableFilesDirectory,
originalRelativeSourcePath));
BEntry targetEntry;
error = targetEntry.SetTo(&targetDirectory, tempTargetName);
if (error == B_OK)
error = targetEntry.Rename(targetName, true);
if (error != B_OK) {
throw Exception(error,
BString().SetToFormat("failed to rename entry \"%s\" to \"%s\"",
_GetPath(
FSUtils::Entry(targetDirectory, tempTargetName),
tempTargetName).String(),
targetName),
package->FileName());
}
renameOperation.Finished();
copyOperation.Unregister();
}
void _RevertAddPackagesToActivate()
{
if (fAddedPackages.empty())
return;
// open transaction directory
BDirectory transactionDirectory;
status_t error = transactionDirectory.SetTo(&fTransactionDirectoryRef);
if (error != B_OK) {
ERROR("failed to open transaction directory: %s\n",
strerror(error));
}
for (PackageSet::iterator it = fAddedPackages.begin();
it != fAddedPackages.end(); ++it) {
// remove package from the volume
Package* package = *it;
if (fPackagesAlreadyAdded.find(package)
!= fPackagesAlreadyAdded.end()) {
continue;
}
fVolume->_RemovePackage(package);