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