summaryrefslogtreecommitdiffstats
path: root/mmc_updater/src/UpdateInstaller.cpp
blob: 29cda0dccd8bcba07a85db0cce88993d7d03859d (plain)
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
#include "UpdateInstaller.h"

#include "AppInfo.h"
#include "FileUtils.h"
#include "Log.h"
#include "ProcessUtils.h"
#include "UpdateObserver.h"

void UpdateInstaller::setWaitPid(PLATFORM_PID pid)
{
	m_waitPid = pid;
}

void UpdateInstaller::setInstallDir(const std::string& path)
{
	m_installDir = path;
}

void UpdateInstaller::setPackageDir(const std::string& path)
{
	m_packageDir = path;
}

void UpdateInstaller::setBackupDir(const std::string& path)
{
	m_backupDir = path;
}

void UpdateInstaller::setMode(Mode mode)
{
	m_mode = mode;
}

void UpdateInstaller::setScript(UpdateScript* script)
{
	m_script = script;
}

void UpdateInstaller::setForceElevated(bool elevated)
{
	m_forceElevated = elevated;
}

void UpdateInstaller::setFinishCmd(const std::string& cmd)
{
	m_finishCmd = cmd;
}

std::list<std::string> UpdateInstaller::updaterArgs() const
{
	std::list<std::string> args;
	args.push_back("--install-dir");
	args.push_back(m_installDir);
	args.push_back("--package-dir");
	args.push_back(m_packageDir);
	args.push_back("--script");
	args.push_back(m_script->path());
	if (m_autoClose)
	{
		args.push_back("--auto-close");
	}
	if (m_dryRun)
	{
		args.push_back("--dry-run");
	}
	return args;
}

void UpdateInstaller::reportError(const std::string& error)
{
	if (m_observer)
	{
		m_observer->updateError(error);
		m_observer->updateFinished();
	}
}

std::string UpdateInstaller::friendlyErrorForError(const FileUtils::IOException& exception) const
{
	std::string friendlyError;

	switch (exception.type())
	{
		case FileUtils::IOException::ReadOnlyFileSystem:
#ifdef PLATFORM_MAC
			friendlyError = AppInfo::appName() + " was started from a read-only location.  "
			                "Copy it to the Applications folder on your Mac and run "
			                "it from there.";
#else
			friendlyError = AppInfo::appName() + " was started from a read-only location.  "
							"Re-install it to a location that can be updated and run it from there.";
#endif
			break;
		case FileUtils::IOException::DiskFull:
			friendlyError = "The disk is full.  Please free up some space and try again.";
			break;
		default:
			break;
	}

	return friendlyError;
}

void UpdateInstaller::run() throw ()
{
	if (!m_script || !m_script->isValid())
	{
		reportError("Unable to read update script");
		return;
	}
	if (m_installDir.empty())
	{
		reportError("No installation directory specified");
		return;
	}

	std::string updaterPath;
	try
	{
		updaterPath = ProcessUtils::currentProcessPath();
	}
	catch (const FileUtils::IOException&)
	{
		LOG(Error,"error reading process path with mode " + intToStr(m_mode));
		reportError("Unable to determine path of updater");
		return;
	}

	if (m_mode == Setup)
	{
		if (m_waitPid != 0)
		{
			LOG(Info,"Waiting for main app process to finish");
			ProcessUtils::waitForProcess(m_waitPid);
		}

		std::list<std::string> args = updaterArgs();
		args.push_back("--mode");
		args.push_back("main");
		args.push_back("--wait");
		args.push_back(intToStr(ProcessUtils::currentProcessId()));

		int installStatus = 0;
		if (m_forceElevated || !checkAccess())
		{
			LOG(Info,"Insufficient rights to install app to " + m_installDir + " requesting elevation");

			// start a copy of the updater with admin rights
			installStatus = ProcessUtils::runElevated(updaterPath,args,AppInfo::name());
		}
		else
		{
			LOG(Info,"Sufficient rights to install app - restarting with same permissions");
			installStatus = ProcessUtils::runSync(updaterPath,args);
		}

		if (installStatus == 0)
		{
			LOG(Info,"Update install completed");
		}
		else
		{
			LOG(Error,"Update install failed with status " + intToStr(installStatus));
		}

		// restart the main application - this is currently done
		// regardless of whether the installation succeeds or not
		restartMainApp();

		// clean up files created by the updater
		cleanup();
	}
	else if (m_mode == Main)
	{
		LOG(Info,"Starting update installation");

		// the detailed error string returned by the OS
		std::string error;
		// the message to present to the user.  This may be the same
		// as 'error' or may be different if a more helpful suggestion
		// can be made for a particular problem
		std::string friendlyError;

		try
		{
			LOG(Info,"Installing new and updated files");
			installFiles();

			LOG(Info,"Uninstalling removed files");
			uninstallFiles();

			LOG(Info,"Removing backups");
			removeBackups();

			postInstallUpdate();
		}
		catch (const FileUtils::IOException& exception)
		{
			error = exception.what();
			friendlyError = friendlyErrorForError(exception);
		}
		catch (const std::string& genericError)
		{
			error = genericError;
		}

		if (!error.empty())
		{
			LOG(Error,std::string("Error installing update ") + error);

			try
			{
				revert();
			}
			catch (const FileUtils::IOException& exception)
			{
				LOG(Error,"Error reverting partial update " + std::string(exception.what()));
			}

			if (m_observer)
			{
				if (friendlyError.empty())
				{
					friendlyError = error;
				}
				m_observer->updateError(friendlyError);
			}
		}

		if (m_observer)
		{
			m_observer->updateFinished();
		}
	}
}

void UpdateInstaller::cleanup()
{
	try
	{
		FileUtils::rmdirRecursive(m_packageDir.c_str());
	}
	catch (const FileUtils::IOException& ex)
	{
		LOG(Error,"Error cleaning up updater " + std::string(ex.what()));
	}
	LOG(Info,"Updater files removed");
}

void UpdateInstaller::revert()
{
	LOG(Info,"Reverting installation!");
	std::map<std::string,std::string>::const_iterator iter = m_backups.begin();
	for (;iter != m_backups.end();iter++)
	{
		const std::string& installedFile = iter->first;
		const std::string& backupFile = iter->second;
		LOG(Info,"Restoring " + installedFile);
		if(!m_dryRun)
		{
			if (FileUtils::fileExists(installedFile.c_str()))
			{
				FileUtils::removeFile(installedFile.c_str());
			}
			FileUtils::moveFile(backupFile.c_str(),installedFile.c_str());
		}
	}
}

void UpdateInstaller::installFile(const UpdateScriptFile& file)
{
	std::string sourceFile = file.source;
	std::string destPath = file.dest;
	std::string target = file.linkTarget;

	LOG(Info,"Installing file " + sourceFile + " to " + destPath);

	// backup the existing file if any
	backupFile(destPath);

	// create the target directory if it does not exist
	std::string destDir = FileUtils::dirname(destPath.c_str());
	if (!FileUtils::fileExists(destDir.c_str()))
	{
		LOG(Info,"Destination path missing. Creating " + destDir);
		if(!m_dryRun)
		{
			FileUtils::mkpath(destDir.c_str());
		}
	}

	if (!FileUtils::fileExists(sourceFile.c_str()))
	{
		throw "Source file does not exist: " + sourceFile;
	}
	if(!m_dryRun)
	{
		FileUtils::copyFile(sourceFile.c_str(),destPath.c_str());

		// set the permissions on the newly extracted file
		FileUtils::chmod(destPath.c_str(),file.permissions);
	}
}

void UpdateInstaller::installFiles()
{
	LOG(Info,"Installing files.");
	std::vector<UpdateScriptFile>::const_iterator iter = m_script->filesToInstall().begin();
	int filesInstalled = 0;
	for (;iter != m_script->filesToInstall().end();iter++)
	{
		installFile(*iter);
		++filesInstalled;
		if (m_observer)
		{
			int toInstallCount = static_cast<int>(m_script->filesToInstall().size());
			double percentage = ((1.0 * filesInstalled) / toInstallCount) * 100.0;
			m_observer->updateProgress(static_cast<int>(percentage));
		}
	}
}

void UpdateInstaller::uninstallFiles()
{
	LOG(Info,"Uninstalling files.");
	std::vector<std::string>::const_iterator iter = m_script->filesToUninstall().begin();
	for (;iter != m_script->filesToUninstall().end();iter++)
	{
		std::string path = m_installDir + '/' + iter->c_str();
		if (FileUtils::fileExists(path.c_str()))
		{
			LOG(Info,"Uninstalling " + path);
			if(!m_dryRun)
			{
				FileUtils::removeFile(path.c_str());
			}
		}
		else
		{
			LOG(Warn,"Unable to uninstall file " + path + " because it does not exist.");
		}
	}
}

void UpdateInstaller::backupFile(const std::string& path)
{
	if (!FileUtils::fileExists(path.c_str()))
	{
		// no existing file to backup
		return;
	}
	std::string backupPath = path + ".bak";
	LOG(Info,"Backing up file: " + path + " as " + backupPath);
	if(!m_dryRun)
	{
		FileUtils::removeFile(backupPath.c_str());
		FileUtils::moveFile(path.c_str(), backupPath.c_str());
	}
	m_backups[path] = backupPath;
}

void UpdateInstaller::removeBackups()
{
	LOG(Info,"Removing backups.");
	std::map<std::string,std::string>::const_iterator iter = m_backups.begin();
	for (;iter != m_backups.end();iter++)
	{
		const std::string& backupFile = iter->second;
		LOG(Info,"Removing " + backupFile);
		if(!m_dryRun)
		{
			FileUtils::removeFile(backupFile.c_str());
		}
	}
}

bool UpdateInstaller::checkAccess()
{
	std::string testFile = m_installDir + "/update-installer-test-file";
	LOG(Info,"Checking for access: " + testFile);
	try
	{
		if(!m_dryRun)
		{
			FileUtils::removeFile(testFile.c_str());
		}
	}
	catch (const FileUtils::IOException& error)
	{
		LOG(Info,"Removing existing access check file failed " + std::string(error.what()));
	}

	try
	{
		if(!m_dryRun)
		{
			FileUtils::touch(testFile.c_str());
			FileUtils::removeFile(testFile.c_str());
		}
		return true;
	}
	catch (const FileUtils::IOException& error)
	{
		LOG(Info,"checkAccess() failed " + std::string(error.what()));
		return false;
	}
}

void UpdateInstaller::setObserver(UpdateObserver* observer)
{
	m_observer = observer;
}

void UpdateInstaller::restartMainApp()
{
	try
	{
		std::string command = m_finishCmd;
		std::list<std::string> args;

		if (!command.empty())
		{
			LOG(Info,"Starting main application " + command);
			if(!m_dryRun)
			{
				ProcessUtils::runAsync(command,args);
			}
		}
		else
		{
			LOG(Error,"No main binary specified");
		}
	}
	catch (const std::exception& ex)
	{
		LOG(Error,"Unable to restart main app " + std::string(ex.what()));
	}
}

void UpdateInstaller::postInstallUpdate()
{
	// perform post-install actions

#ifdef PLATFORM_MAC
	// touch the application's bundle directory so that
	// OS X' Launch Services notices any changes in the application's
	// Info.plist file.
	LOG(Info,"Touching " + m_installDir + " to notify OSX of metadata changes.");
	if(!m_dryRun)
	{
		FileUtils::touch(m_installDir.c_str());
	}
#endif
}

void UpdateInstaller::setAutoClose(bool autoClose)
{
	m_autoClose = autoClose;
}

void UpdateInstaller::setDryRun(bool dryRun)
{
	m_dryRun = dryRun;
}