xref: /haiku/src/apps/installer/WorkerThread.cpp (revision c05253c64ed5afe485062830e21ff448a48bc741)
1 /*
2  * Copyright 2009, Stephan Aßmus <superstippi@gmx.de>.
3  * Copyright 2005-2008, Jérôme DUVAL.
4  * All rights reserved. Distributed under the terms of the MIT License.
5  */
6 
7 #include "WorkerThread.h"
8 
9 #include <errno.h>
10 #include <stdio.h>
11 
12 #include <set>
13 #include <string>
14 #include <strings.h>
15 
16 #include <Alert.h>
17 #include <Autolock.h>
18 #include <Catalog.h>
19 #include <Directory.h>
20 #include <DiskDeviceVisitor.h>
21 #include <DiskDeviceTypes.h>
22 #include <FindDirectory.h>
23 #include <fs_index.h>
24 #include <Locale.h>
25 #include <Menu.h>
26 #include <MenuItem.h>
27 #include <Message.h>
28 #include <Messenger.h>
29 #include <Path.h>
30 #include <String.h>
31 #include <VolumeRoster.h>
32 
33 #include "AutoLocker.h"
34 #include "CopyEngine.h"
35 #include "InstallerDefs.h"
36 #include "PackageViews.h"
37 #include "PartitionMenuItem.h"
38 #include "ProgressReporter.h"
39 #include "StringForSize.h"
40 #include "UnzipEngine.h"
41 
42 
43 #define B_TRANSLATION_CONTEXT "InstallProgress"
44 
45 
46 //#define COPY_TRACE
47 #ifdef COPY_TRACE
48 #define CALLED() 		printf("CALLED %s\n",__PRETTY_FUNCTION__)
49 #define ERR2(x, y...)	fprintf(stderr, "WorkerThread: "x" %s\n", y, strerror(err))
50 #define ERR(x)			fprintf(stderr, "WorkerThread: "x" %s\n", strerror(err))
51 #else
52 #define CALLED()
53 #define ERR(x)
54 #define ERR2(x, y...)
55 #endif
56 
57 const char BOOT_PATH[] = "/boot";
58 
59 const uint32 MSG_START_INSTALLING = 'eSRT';
60 
61 
62 class SourceVisitor : public BDiskDeviceVisitor {
63 public:
64 	SourceVisitor(BMenu* menu);
65 	virtual bool Visit(BDiskDevice* device);
66 	virtual bool Visit(BPartition* partition, int32 level);
67 
68 private:
69 	BMenu* fMenu;
70 };
71 
72 
73 class TargetVisitor : public BDiskDeviceVisitor {
74 public:
75 	TargetVisitor(BMenu* menu);
76 	virtual bool Visit(BDiskDevice* device);
77 	virtual bool Visit(BPartition* partition, int32 level);
78 
79 private:
80 	BMenu* fMenu;
81 };
82 
83 
84 // #pragma mark - WorkerThread
85 
86 
87 class WorkerThread::EntryFilter : public CopyEngine::EntryFilter {
88 public:
89 	EntryFilter(const char* sourceDirectory)
90 		:
91 		fIgnorePaths(),
92 		fSourceDevice(-1)
93 	{
94 		try {
95 			fIgnorePaths.insert(kPackagesDirectoryPath);
96 			fIgnorePaths.insert(kSourcesDirectoryPath);
97 			fIgnorePaths.insert("rr_moved");
98 			fIgnorePaths.insert("boot.catalog");
99 			fIgnorePaths.insert("haiku-boot-floppy.image");
100 			fIgnorePaths.insert("system/var/swap");
101 			fIgnorePaths.insert("system/var/shared_memory");
102 			fIgnorePaths.insert("system/var/log/syslog");
103 			fIgnorePaths.insert("system/var/log/syslog.old");
104 
105 			fPackageFSRootPaths.insert("system");
106 			fPackageFSRootPaths.insert("home/config");
107 		} catch (std::bad_alloc&) {
108 		}
109 
110 		struct stat st;
111 		if (stat(sourceDirectory, &st) == 0)
112 			fSourceDevice = st.st_dev;
113 	}
114 
115 	virtual bool ShouldCopyEntry(const BEntry& entry, const char* path,
116 		const struct stat& statInfo) const
117 	{
118 		if (S_ISBLK(statInfo.st_mode) || S_ISCHR(statInfo.st_mode)
119 				|| S_ISFIFO(statInfo.st_mode) || S_ISSOCK(statInfo.st_mode)) {
120 			printf("skipping '%s', it is a special file.\n", path);
121 			return false;
122 		}
123 
124 		if (fIgnorePaths.find(path) != fIgnorePaths.end()) {
125 			printf("ignoring '%s'.\n", path);
126 			return false;
127 		}
128 
129 		if (statInfo.st_dev != fSourceDevice) {
130 			// Allow that only for the root of the packagefs mounts, since
131 			// those contain directories that shine through from the
132 			// underlying volume.
133 			if (fPackageFSRootPaths.find(path) == fPackageFSRootPaths.end())
134 				return false;
135 		}
136 
137 		return true;
138 	}
139 
140 private:
141 	typedef std::set<std::string> StringSet;
142 
143 			StringSet			fIgnorePaths;
144 			StringSet			fPackageFSRootPaths;
145 			dev_t				fSourceDevice;
146 };
147 
148 
149 // #pragma mark - WorkerThread
150 
151 
152 WorkerThread::WorkerThread(const BMessenger& owner)
153 	:
154 	BLooper("copy_engine"),
155 	fOwner(owner),
156 	fPackages(NULL),
157 	fSpaceRequired(0),
158 	fCancelSemaphore(-1)
159 {
160 	Run();
161 }
162 
163 
164 void
165 WorkerThread::MessageReceived(BMessage* message)
166 {
167 	CALLED();
168 
169 	switch (message->what) {
170 		case MSG_START_INSTALLING:
171 			_PerformInstall(message->GetInt32("source", -1),
172 				message->GetInt32("target", -1));
173 			break;
174 
175 		case MSG_WRITE_BOOT_SECTOR:
176 		{
177 			int32 id;
178 			if (message->FindInt32("id", &id) != B_OK) {
179 				_SetStatusMessage(B_TRANSLATE("Boot sector not written "
180 					"because of an internal error."));
181 				break;
182 			}
183 
184 			// TODO: Refactor with _PerformInstall()
185 			BPath targetDirectory;
186 			BDiskDevice device;
187 			BPartition* partition;
188 
189 			if (fDDRoster.GetPartitionWithID(id, &device, &partition) == B_OK) {
190 				if (!partition->IsMounted()) {
191 					if (partition->Mount() < B_OK) {
192 						_SetStatusMessage(B_TRANSLATE("The partition can't be "
193 							"mounted. Please choose a different partition."));
194 						break;
195 					}
196 				}
197 				if (partition->GetMountPoint(&targetDirectory) != B_OK) {
198 					_SetStatusMessage(B_TRANSLATE("The mount point could not "
199 						"be retrieved."));
200 					break;
201 				}
202 			} else if (fDDRoster.GetDeviceWithID(id, &device) == B_OK) {
203 				if (!device.IsMounted()) {
204 					if (device.Mount() < B_OK) {
205 						_SetStatusMessage(B_TRANSLATE("The disk can't be "
206 							"mounted. Please choose a different disk."));
207 						break;
208 					}
209 				}
210 				if (device.GetMountPoint(&targetDirectory) != B_OK) {
211 					_SetStatusMessage(B_TRANSLATE("The mount point could not "
212 						"be retrieved."));
213 					break;
214 				}
215 			}
216 
217 			if (_WriteBootSector(targetDirectory) != B_OK) {
218 				_SetStatusMessage(
219 					B_TRANSLATE("Error writing boot sector."));
220 				break;
221 			}
222 			_SetStatusMessage(
223 				B_TRANSLATE("Boot sector successfully written."));
224 		}
225 		default:
226 			BLooper::MessageReceived(message);
227 	}
228 }
229 
230 
231 
232 
233 void
234 WorkerThread::ScanDisksPartitions(BMenu *srcMenu, BMenu *targetMenu)
235 {
236 	// NOTE: This is actually executed in the window thread.
237 	BDiskDevice device;
238 	BPartition *partition = NULL;
239 
240 	SourceVisitor srcVisitor(srcMenu);
241 	fDDRoster.VisitEachMountedPartition(&srcVisitor, &device, &partition);
242 
243 	TargetVisitor targetVisitor(targetMenu);
244 	fDDRoster.VisitEachPartition(&targetVisitor, &device, &partition);
245 }
246 
247 
248 void
249 WorkerThread::SetPackagesList(BList *list)
250 {
251 	// Executed in window thread.
252 	BAutolock _(this);
253 
254 	delete fPackages;
255 	fPackages = list;
256 }
257 
258 
259 void
260 WorkerThread::StartInstall(partition_id sourcePartitionID,
261 	partition_id targetPartitionID)
262 {
263 	// Executed in window thread.
264 	BMessage message(MSG_START_INSTALLING);
265 	message.AddInt32("source", sourcePartitionID);
266 	message.AddInt32("target", targetPartitionID);
267 
268 	PostMessage(&message, this);
269 }
270 
271 
272 void
273 WorkerThread::WriteBootSector(BMenu* targetMenu)
274 {
275 	// Executed in window thread.
276 	CALLED();
277 
278 	PartitionMenuItem* item = (PartitionMenuItem*)targetMenu->FindMarked();
279 	if (item == NULL) {
280 		ERR("bad menu items\n");
281 		return;
282 	}
283 
284 	BMessage message(MSG_WRITE_BOOT_SECTOR);
285 	message.AddInt32("id", item->ID());
286 	PostMessage(&message, this);
287 }
288 
289 
290 // #pragma mark -
291 
292 
293 status_t
294 WorkerThread::_WriteBootSector(BPath &path)
295 {
296 	BPath bootPath;
297 	find_directory(B_BEOS_BOOT_DIRECTORY, &bootPath);
298 	BString command;
299 	command.SetToFormat("makebootable \"%s\"", path.Path());
300 	_SetStatusMessage(B_TRANSLATE("Writing bootsector."));
301 	return system(command.String());
302 }
303 
304 
305 status_t
306 WorkerThread::_LaunchFinishScript(BPath &path)
307 {
308 	_SetStatusMessage(B_TRANSLATE("Finishing installation."));
309 
310 	BString command;
311 	command.SetToFormat("mkdir -p \"%s/system/cache/tmp\"", path.Path());
312 	if (system(command.String()) != 0)
313 		return B_ERROR;
314 
315 	command.SetToFormat("rm -f \"%s/home/Desktop/Installer\"", path.Path());
316 	return system(command.String());
317 }
318 
319 
320 status_t
321 WorkerThread::_PerformInstall(partition_id sourcePartitionID,
322 	partition_id targetPartitionID)
323 {
324 	CALLED();
325 
326 	BPath targetDirectory;
327 	BPath srcDirectory;
328 	BPath trashPath;
329 	BPath testPath;
330 	BDirectory targetDir;
331 	BDiskDevice device;
332 	BPartition* partition;
333 	BVolume targetVolume;
334 	status_t err = B_OK;
335 	int32 entries = 0;
336 	entry_ref testRef;
337 	const char* mountError = B_TRANSLATE("The disk can't be mounted. Please "
338 		"choose a different disk.");
339 
340 	if (sourcePartitionID < 0 || targetPartitionID < 0) {
341 		ERR("bad source or target partition ID\n");
342 		return _InstallationError(err);
343 	}
344 
345 	// check if target is initialized
346 	// ask if init or mount as is
347 	if (fDDRoster.GetPartitionWithID(targetPartitionID, &device,
348 			&partition) == B_OK) {
349 		if (!partition->IsMounted()) {
350 			if ((err = partition->Mount()) < B_OK) {
351 				_SetStatusMessage(mountError);
352 				ERR("BPartition::Mount");
353 				return _InstallationError(err);
354 			}
355 		}
356 		if ((err = partition->GetVolume(&targetVolume)) != B_OK) {
357 			ERR("BPartition::GetVolume");
358 			return _InstallationError(err);
359 		}
360 		if ((err = partition->GetMountPoint(&targetDirectory)) != B_OK) {
361 			ERR("BPartition::GetMountPoint");
362 			return _InstallationError(err);
363 		}
364 	} else if (fDDRoster.GetDeviceWithID(targetPartitionID, &device) == B_OK) {
365 		if (!device.IsMounted()) {
366 			if ((err = device.Mount()) < B_OK) {
367 				_SetStatusMessage(mountError);
368 				ERR("BDiskDevice::Mount");
369 				return _InstallationError(err);
370 			}
371 		}
372 		if ((err = device.GetVolume(&targetVolume)) != B_OK) {
373 			ERR("BDiskDevice::GetVolume");
374 			return _InstallationError(err);
375 		}
376 		if ((err = device.GetMountPoint(&targetDirectory)) != B_OK) {
377 			ERR("BDiskDevice::GetMountPoint");
378 			return _InstallationError(err);
379 		}
380 	} else
381 		return _InstallationError(err);  // shouldn't happen
382 
383 	// check if target has enough space
384 	if (fSpaceRequired > 0 && targetVolume.FreeBytes() < fSpaceRequired) {
385 		BAlert* alert = new BAlert("", B_TRANSLATE("The destination disk may "
386 			"not have enough space. Try choosing a different disk or choose "
387 			"to not install optional items."),
388 			B_TRANSLATE("Try installing anyway"), B_TRANSLATE("Cancel"), 0,
389 			B_WIDTH_AS_USUAL, B_STOP_ALERT);
390 		alert->SetShortcut(1, B_ESCAPE);
391 		if (alert->Go() != 0)
392 			return _InstallationError(err);
393 	}
394 
395 	if (fDDRoster.GetPartitionWithID(sourcePartitionID, &device, &partition)
396 			== B_OK) {
397 		if ((err = partition->GetMountPoint(&srcDirectory)) != B_OK) {
398 			ERR("BPartition::GetMountPoint");
399 			return _InstallationError(err);
400 		}
401 	} else if (fDDRoster.GetDeviceWithID(sourcePartitionID, &device) == B_OK) {
402 		if ((err = device.GetMountPoint(&srcDirectory)) != B_OK) {
403 			ERR("BDiskDevice::GetMountPoint");
404 			return _InstallationError(err);
405 		}
406 	} else
407 		return _InstallationError(err); // shouldn't happen
408 
409 	// check not installing on itself
410 	if (strcmp(srcDirectory.Path(), targetDirectory.Path()) == 0) {
411 		_SetStatusMessage(B_TRANSLATE("You can't install the contents of a "
412 			"disk onto itself. Please choose a different disk."));
413 		return _InstallationError(err);
414 	}
415 
416 	// check not installing on boot volume
417 	if (strncmp(BOOT_PATH, targetDirectory.Path(), strlen(BOOT_PATH)) == 0) {
418 		BAlert* alert = new BAlert("", B_TRANSLATE("Are you sure you want to "
419 			"install onto the current boot disk? The Installer will have to "
420 			"reboot your machine if you proceed."), B_TRANSLATE("OK"),
421 			B_TRANSLATE("Cancel"), 0, B_WIDTH_AS_USUAL, B_STOP_ALERT);
422 		alert->SetShortcut(1, B_ESCAPE);
423 		if (alert->Go() != 0) {
424 			_SetStatusMessage("Installation stopped.");
425 			return _InstallationError(err);
426 		}
427 	}
428 
429 	// check if target volume's trash dir has anything in it
430 	// (target volume w/ only an empty trash dir is considered
431 	// an empty volume)
432 	if (find_directory(B_TRASH_DIRECTORY, &trashPath, false,
433 		&targetVolume) == B_OK && targetDir.SetTo(trashPath.Path()) == B_OK) {
434 			while (targetDir.GetNextRef(&testRef) == B_OK) {
435 				// Something in the Trash
436 				entries++;
437 				break;
438 			}
439 	}
440 
441 	targetDir.SetTo(targetDirectory.Path());
442 
443 	// check if target volume otherwise has any entries
444 	while (entries == 0 && targetDir.GetNextRef(&testRef) == B_OK) {
445 		if (testPath.SetTo(&testRef) == B_OK && testPath != trashPath)
446 			entries++;
447 	}
448 
449 	if (entries != 0) {
450 		BAlert* alert = new BAlert("", B_TRANSLATE("The target volume is not "
451 			"empty. If it already contains a Haiku installation, it will be "
452 			"overwritten. This will remove all installed software.\n\n"
453 			"If you want to upgrade your system without removing installed "
454 			"software, see the Haiku User Guide's topic on the application "
455 			"\"SoftwareUpdater\" for update instructions.\n\n"
456 			"Are you sure you want to continue the installation?"),
457 			B_TRANSLATE("Install anyway"), B_TRANSLATE("Cancel"), 0,
458 			B_WIDTH_AS_USUAL, B_STOP_ALERT);
459 		alert->SetShortcut(1, B_ESCAPE);
460 		if (alert->Go() != 0) {
461 		// TODO: Would be cool to offer the option here to clean additional
462 		// folders at the user's choice.
463 			return _InstallationError(B_CANCELED);
464 		}
465 		err = _PrepareCleanInstall(targetDirectory);
466 		if (err != B_OK)
467 			return _InstallationError(err);
468 	}
469 
470 	// Begin actual installation
471 
472 	ProgressReporter reporter(fOwner, new BMessage(MSG_STATUS_MESSAGE));
473 	EntryFilter entryFilter(srcDirectory.Path());
474 	CopyEngine engine(&reporter, &entryFilter);
475 	BList unzipEngines;
476 
477 	// Create the default indices which should always be present on a proper
478 	// boot volume. We don't care if the source volume does not have them.
479 	// After all, the user might be re-installing to another drive and may
480 	// want problems fixed along the way...
481 	err = _CreateDefaultIndices(targetDirectory);
482 	if (err != B_OK)
483 		return _InstallationError(err);
484 	// Mirror all the indices which are present on the source volume onto
485 	// the target volume.
486 	err = _MirrorIndices(srcDirectory, targetDirectory);
487 	if (err != B_OK)
488 		return _InstallationError(err);
489 
490 	// Let the engine collect information for the progress bar later on
491 	engine.ResetTargets(srcDirectory.Path());
492 	err = engine.CollectTargets(srcDirectory.Path(), fCancelSemaphore);
493 	if (err != B_OK)
494 		return _InstallationError(err);
495 
496 	// Collect selected packages also
497 	if (fPackages) {
498 		int32 count = fPackages->CountItems();
499 		for (int32 i = 0; i < count; i++) {
500 			Package *p = static_cast<Package*>(fPackages->ItemAt(i));
501 			const BPath& pkgPath = p->Path();
502 			err = pkgPath.InitCheck();
503 			if (err != B_OK)
504 				return _InstallationError(err);
505 			err = engine.CollectTargets(pkgPath.Path(), fCancelSemaphore);
506 			if (err != B_OK)
507 				return _InstallationError(err);
508 		}
509 	}
510 
511 	// collect information about all zip packages
512 	err = _ProcessZipPackages(srcDirectory.Path(), targetDirectory.Path(),
513 		&reporter, unzipEngines);
514 	if (err != B_OK)
515 		return _InstallationError(err);
516 
517 	reporter.StartTimer();
518 
519 	// copy source volume
520 	err = engine.Copy(srcDirectory.Path(), targetDirectory.Path(),
521 		fCancelSemaphore);
522 	if (err != B_OK)
523 		return _InstallationError(err);
524 
525 	// copy selected packages
526 	if (fPackages) {
527 		int32 count = fPackages->CountItems();
528 		// FIXME: find_directory doesn't return the folder in the target volume,
529 		// so we are hard coding this for now.
530 		BPath targetPkgDir(targetDirectory.Path(), "system/packages");
531 		err = targetPkgDir.InitCheck();
532 		if (err != B_OK)
533 			return _InstallationError(err);
534 		for (int32 i = 0; i < count; i++) {
535 			Package *p = static_cast<Package*>(fPackages->ItemAt(i));
536 			const BPath& pkgPath = p->Path();
537 			err = pkgPath.InitCheck();
538 			if (err != B_OK)
539 				return _InstallationError(err);
540 			BPath targetPath(targetPkgDir.Path(), pkgPath.Leaf());
541 			err = targetPath.InitCheck();
542 			if (err != B_OK)
543 				return _InstallationError(err);
544 			err = engine.Copy(pkgPath.Path(), targetPath.Path(),
545 				fCancelSemaphore);
546 			if (err != B_OK)
547 				return _InstallationError(err);
548 		}
549 	}
550 
551 	// Extract all zip packages. If an error occured, delete the rest of
552 	// the engines, but stop extracting.
553 	for (int32 i = 0; i < unzipEngines.CountItems(); i++) {
554 		UnzipEngine* engine = reinterpret_cast<UnzipEngine*>(
555 			unzipEngines.ItemAtFast(i));
556 		if (err == B_OK)
557 			err = engine->UnzipPackage();
558 		delete engine;
559 	}
560 	if (err != B_OK)
561 		return _InstallationError(err);
562 
563 	err = _WriteBootSector(targetDirectory);
564 	if (err != B_OK)
565 		return _InstallationError(err);
566 
567 	err = _LaunchFinishScript(targetDirectory);
568 	if (err != B_OK)
569 		return _InstallationError(err);
570 
571 	fOwner.SendMessage(MSG_INSTALL_FINISHED);
572 	return B_OK;
573 }
574 
575 
576 status_t
577 WorkerThread::_PrepareCleanInstall(const BPath& targetDirectory) const
578 {
579 	// When a target volume has files (other than the trash), the /system
580 	// folder will be purged, except for the /system/settings subdirectory.
581 	BPath systemPath(targetDirectory.Path(), "system", true);
582 	status_t ret = systemPath.InitCheck();
583 	if (ret != B_OK)
584 		return ret;
585 
586 	BEntry systemEntry(systemPath.Path());
587 	ret = systemEntry.InitCheck();
588 	if (ret != B_OK)
589 		return ret;
590 	if (!systemEntry.Exists())
591 		// target does not exist, done
592 		return B_OK;
593 	if (!systemEntry.IsDirectory())
594 		// the system entry is a file or a symlink
595 		return systemEntry.Remove();
596 
597 	BDirectory systemDirectory(&systemEntry);
598 	ret = systemDirectory.InitCheck();
599 	if (ret != B_OK)
600 		return ret;
601 
602 	BEntry subEntry;
603 	char fileName[B_FILE_NAME_LENGTH];
604 	while (systemDirectory.GetNextEntry(&subEntry) == B_OK) {
605 		ret = subEntry.GetName(fileName);
606 		if (ret != B_OK)
607 			return ret;
608 
609 		if (subEntry.IsDirectory() && strcmp(fileName, "settings") == 0) {
610 			// Keep the settings folder
611 			continue;
612 		} else if (subEntry.IsDirectory()) {
613 			ret = CopyEngine::RemoveFolder(subEntry);
614 			if (ret != B_OK)
615 				return ret;
616 		} else {
617 			ret = subEntry.Remove();
618 			if (ret != B_OK)
619 				return ret;
620 		}
621 	}
622 
623 	return B_OK;
624 }
625 
626 
627 status_t
628 WorkerThread::_InstallationError(status_t error)
629 {
630 	BMessage statusMessage(MSG_RESET);
631 	if (error == B_CANCELED)
632 		_SetStatusMessage(B_TRANSLATE("Installation canceled."));
633 	else
634 		statusMessage.AddInt32("error", error);
635 	ERR("_PerformInstall failed");
636 	fOwner.SendMessage(&statusMessage);
637 	return error;
638 }
639 
640 
641 status_t
642 WorkerThread::_MirrorIndices(const BPath& sourceDirectory,
643 	const BPath& targetDirectory) const
644 {
645 	dev_t sourceDevice = dev_for_path(sourceDirectory.Path());
646 	if (sourceDevice < 0)
647 		return (status_t)sourceDevice;
648 	dev_t targetDevice = dev_for_path(targetDirectory.Path());
649 	if (targetDevice < 0)
650 		return (status_t)targetDevice;
651 	DIR* indices = fs_open_index_dir(sourceDevice);
652 	if (indices == NULL) {
653 		printf("%s: fs_open_index_dir(): (%d) %s\n", sourceDirectory.Path(),
654 			errno, strerror(errno));
655 		// Opening the index directory will fail for example on ISO-Live
656 		// CDs. The default indices have already been created earlier, so
657 		// we simply bail.
658 		return B_OK;
659 	}
660 	while (dirent* index = fs_read_index_dir(indices)) {
661 		if (strcmp(index->d_name, "name") == 0
662 			|| strcmp(index->d_name, "size") == 0
663 			|| strcmp(index->d_name, "last_modified") == 0) {
664 			continue;
665 		}
666 
667 		index_info info;
668 		if (fs_stat_index(sourceDevice, index->d_name, &info) != B_OK) {
669 			printf("Failed to mirror index %s: fs_stat_index(): (%d) %s\n",
670 				index->d_name, errno, strerror(errno));
671 			continue;
672 		}
673 
674 		uint32 flags = 0;
675 			// Flags are always 0 for the moment.
676 		if (fs_create_index(targetDevice, index->d_name, info.type, flags)
677 			!= B_OK) {
678 			if (errno == B_FILE_EXISTS)
679 				continue;
680 			printf("Failed to mirror index %s: fs_create_index(): (%d) %s\n",
681 				index->d_name, errno, strerror(errno));
682 			continue;
683 		}
684 	}
685 	fs_close_index_dir(indices);
686 	return B_OK;
687 }
688 
689 
690 status_t
691 WorkerThread::_CreateDefaultIndices(const BPath& targetDirectory) const
692 {
693 	dev_t targetDevice = dev_for_path(targetDirectory.Path());
694 	if (targetDevice < 0)
695 		return (status_t)targetDevice;
696 
697 	struct IndexInfo {
698 		const char* name;
699 		uint32_t	type;
700 	};
701 
702 	const IndexInfo defaultIndices[] = {
703 		{ "BEOS:APP_SIG", B_STRING_TYPE },
704 		{ "BEOS:LOCALE_LANGUAGE", B_STRING_TYPE },
705 		{ "BEOS:LOCALE_SIGNATURE", B_STRING_TYPE },
706 		{ "_trk/qrylastchange", B_INT32_TYPE },
707 		{ "_trk/recentQuery", B_INT32_TYPE },
708 		{ "be:deskbar_item_status", B_STRING_TYPE }
709 	};
710 
711 	uint32 flags = 0;
712 		// Flags are always 0 for the moment.
713 
714 	for (uint32 i = 0; i < sizeof(defaultIndices) / sizeof(IndexInfo); i++) {
715 		const IndexInfo& info = defaultIndices[i];
716 		if (fs_create_index(targetDevice, info.name, info.type, flags)
717 			!= B_OK) {
718 			if (errno == B_FILE_EXISTS)
719 				continue;
720 			printf("Failed to create index %s: fs_create_index(): (%d) %s\n",
721 				info.name, errno, strerror(errno));
722 			return errno;
723 		}
724 	}
725 
726 	return B_OK;
727 }
728 
729 
730 status_t
731 WorkerThread::_ProcessZipPackages(const char* sourcePath,
732 	const char* targetPath, ProgressReporter* reporter, BList& unzipEngines)
733 {
734 	// TODO: Put those in the optional packages list view
735 	// TODO: Implement mechanism to handle dependencies between these
736 	// packages. (Selecting one will auto-select others.)
737 	BPath pkgRootDir(sourcePath, kPackagesDirectoryPath);
738 	BDirectory directory(pkgRootDir.Path());
739 	BEntry entry;
740 	while (directory.GetNextEntry(&entry) == B_OK) {
741 		char name[B_FILE_NAME_LENGTH];
742 		if (entry.GetName(name) != B_OK)
743 			continue;
744 		int nameLength = strlen(name);
745 		if (nameLength <= 0)
746 			continue;
747 		char* nameExtension = name + nameLength - 4;
748 		if (strcasecmp(nameExtension, ".zip") != 0)
749 			continue;
750 		printf("found .zip package: %s\n", name);
751 
752 		UnzipEngine* unzipEngine = new(std::nothrow) UnzipEngine(reporter,
753 			fCancelSemaphore);
754 		if (unzipEngine == NULL || !unzipEngines.AddItem(unzipEngine)) {
755 			delete unzipEngine;
756 			return B_NO_MEMORY;
757 		}
758 		BPath path;
759 		entry.GetPath(&path);
760 		status_t ret = unzipEngine->SetTo(path.Path(), targetPath);
761 		if (ret != B_OK)
762 			return ret;
763 
764 		reporter->AddItems(unzipEngine->ItemsToUncompress(),
765 			unzipEngine->BytesToUncompress());
766 	}
767 
768 	return B_OK;
769 }
770 
771 
772 void
773 WorkerThread::_SetStatusMessage(const char *status)
774 {
775 	BMessage msg(MSG_STATUS_MESSAGE);
776 	msg.AddString("status", status);
777 	fOwner.SendMessage(&msg);
778 }
779 
780 
781 static void
782 make_partition_label(BPartition* partition, char* label, char* menuLabel,
783 	bool showContentType)
784 {
785 	char size[20];
786 	string_for_size(partition->Size(), size, sizeof(size));
787 
788 	BPath path;
789 	partition->GetPath(&path);
790 
791 	if (showContentType) {
792 		const char* type = partition->ContentType();
793 		if (type == NULL)
794 			type = B_TRANSLATE_COMMENT("Unknown Type", "Partition content type");
795 
796 		sprintf(label, "%s - %s [%s] (%s)", partition->ContentName(), size,
797 			path.Path(), type);
798 	} else {
799 		sprintf(label, "%s - %s [%s]", partition->ContentName(), size,
800 			path.Path());
801 	}
802 
803 	sprintf(menuLabel, "%s - %s", partition->ContentName(), size);
804 }
805 
806 
807 // #pragma mark - SourceVisitor
808 
809 
810 SourceVisitor::SourceVisitor(BMenu *menu)
811 	: fMenu(menu)
812 {
813 }
814 
815 bool
816 SourceVisitor::Visit(BDiskDevice *device)
817 {
818 	return Visit(device, 0);
819 }
820 
821 
822 bool
823 SourceVisitor::Visit(BPartition *partition, int32 level)
824 {
825 	BPath path;
826 
827 	if (partition->ContentType() == NULL)
828 		return false;
829 
830 	bool isBootPartition = false;
831 	if (partition->IsMounted()) {
832 		BPath mountPoint;
833 		if (partition->GetMountPoint(&mountPoint) != B_OK)
834 			return false;
835 		isBootPartition = strcmp(BOOT_PATH, mountPoint.Path()) == 0;
836 	}
837 
838 	if (!isBootPartition
839 		&& strcmp(partition->ContentType(), kPartitionTypeBFS) != 0) {
840 		// Except only BFS partitions, except this is the boot partition
841 		// (ISO9660 with write overlay for example).
842 		return false;
843 	}
844 
845 	// TODO: We could probably check if this volume contains
846 	// the Haiku kernel or something. Does it make sense to "install"
847 	// from your BFS volume containing the music collection?
848 	// TODO: Then the check for BFS could also be removed above.
849 
850 	char label[255];
851 	char menuLabel[255];
852 	make_partition_label(partition, label, menuLabel, false);
853 	PartitionMenuItem* item = new PartitionMenuItem(partition->ContentName(),
854 		label, menuLabel, new BMessage(SOURCE_PARTITION), partition->ID());
855 	item->SetMarked(isBootPartition);
856 	fMenu->AddItem(item);
857 	return false;
858 }
859 
860 
861 // #pragma mark - TargetVisitor
862 
863 
864 TargetVisitor::TargetVisitor(BMenu *menu)
865 	: fMenu(menu)
866 {
867 }
868 
869 
870 bool
871 TargetVisitor::Visit(BDiskDevice *device)
872 {
873 	if (device->IsReadOnlyMedia())
874 		return false;
875 	return Visit(device, 0);
876 }
877 
878 
879 bool
880 TargetVisitor::Visit(BPartition *partition, int32 level)
881 {
882 	if (partition->ContentSize() < 20 * 1024 * 1024) {
883 		// reject partitions which are too small anyway
884 		// TODO: Could depend on the source size
885 		return false;
886 	}
887 
888 	if (partition->CountChildren() > 0) {
889 		// Looks like an extended partition, or the device itself.
890 		// Do not accept this as target...
891 		return false;
892 	}
893 
894 	// TODO: After running DriveSetup and doing another scan, it would
895 	// be great to pick the partition which just appeared!
896 
897 	bool isBootPartition = false;
898 	if (partition->IsMounted()) {
899 		BPath mountPoint;
900 		partition->GetMountPoint(&mountPoint);
901 		isBootPartition = strcmp(BOOT_PATH, mountPoint.Path()) == 0;
902 	}
903 
904 	// Only writable non-boot BFS partitions are valid targets, but we want to
905 	// display the other partitions as well, to inform the user that they are
906 	// detected but somehow not appropriate.
907 	bool isValidTarget = isBootPartition == false
908 		&& !partition->IsReadOnly()
909 		&& partition->ContentType() != NULL
910 		&& strcmp(partition->ContentType(), kPartitionTypeBFS) == 0;
911 
912 	char label[255];
913 	char menuLabel[255];
914 	make_partition_label(partition, label, menuLabel, !isValidTarget);
915 	PartitionMenuItem* item = new PartitionMenuItem(partition->ContentName(),
916 		label, menuLabel, new BMessage(TARGET_PARTITION), partition->ID());
917 
918 	item->SetIsValidTarget(isValidTarget);
919 
920 
921 	fMenu->AddItem(item);
922 	return false;
923 }
924 
925