File: download.cpp

package info (click to toggle)
cupt 2.10.4%2Bnmu2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 3,144 kB
  • sloc: cpp: 23,642; perl: 1,599; sh: 40; makefile: 19
file content (362 lines) | stat: -rw-r--r-- 10,622 bytes parent folder | download | duplicates (5)
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
/**************************************************************************
*   Copyright (C) 2010-2011 by Eugene V. Lyubimkin                        *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License                  *
*   (version 3 or above) as published by the Free Software Foundation.    *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU GPL                        *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA               *
**************************************************************************/
#include <iostream>
using std::cout;
using std::endl;

#include "../common.hpp"
#include "../handlers.hpp"
#include "../selectors.hpp"

#include <cupt/cache/sourceversion.hpp>
#include <cupt/cache/releaseinfo.hpp>
#include <cupt/system/state.hpp>
#include <cupt/download/manager.hpp>

int downloadSourcePackage(Context& context)
{
	auto config = context.getConfig();
	vector< string > arguments;
	bpo::options_description options("");
	options.add_options()
		("download-only,d", "")
		("tar-only", "")
		("diff-only", "")
		("dsc-only", "");

	auto variables = parseOptions(context, options, arguments);

	if (arguments.empty())
	{
		fatal2(__("no source package expressions specified"));
	}

	if (!shellMode)
	{
		Version::parseInfoOnly = false;
		Version::parseRelations = false;
	}
	auto cache = context.getCache(true, true, true);

	vector< SourceVersion::FileParts::Type > partsToDownload = {
		SourceVersion::FileParts::Tarball,
		SourceVersion::FileParts::Diff,
		SourceVersion::FileParts::Dsc
	};

	bool downloadOnly = false;
	if (variables.count("download-only"))
	{
		downloadOnly = true;
	}
	if (variables.count("tar-only"))
	{
		partsToDownload = { SourceVersion::FileParts::Tarball };
		downloadOnly = true;
	}
	if (variables.count("diff-only"))
	{
		partsToDownload = { SourceVersion::FileParts::Diff };
		downloadOnly = true;
	}
	if (variables.count("dsc-only"))
	{
		partsToDownload = { SourceVersion::FileParts::Dsc };
		downloadOnly = true;
	}

	vector< Manager::DownloadEntity > downloadEntities;
	vector< string > dscFilenames;

	for (const auto& argument: arguments)
	{
		for (const auto& version: selectSourceVersionsWildcarded(*cache, argument))
		{
			const string& packageName = version->packageName;
			const string& versionString = version->versionString;

			auto downloadInfo = version->getDownloadInfo();

			for (auto part: partsToDownload)
			{
				for (const Version::FileRecord& record: version->files[part])
				{
					const string& filename = record.name;
					if (part == SourceVersion::FileParts::Dsc)
					{
						dscFilenames.push_back(filename); // for unpacking after
					}

					{ // exclude from downloading packages that are already present
						decltype(cupt::messageFd) oldMessageFd = cupt::messageFd;
						cupt::messageFd = -1; // don't print errors if any
						try
						{
							if (record.hashSums.verify(filename))
							{
								continue;
							}
						}
						catch (Exception&) {}
						cupt::messageFd = oldMessageFd;
					}

					Manager::DownloadEntity downloadEntity;
					for (const auto& downloadRecord: downloadInfo)
					{
						string shortAlias = packageName + ' ' + SourceVersion::FileParts::strings[part];
						string longAlias = format2("%s %s %s %s %s", downloadRecord.baseUri,
								version->getCodenameAndComponentString(downloadRecord.baseUri),
								packageName, versionString, SourceVersion::FileParts::strings[part]);
						string uri = downloadRecord.baseUri + '/' +
								downloadRecord.directory + '/' + filename;

						downloadEntity.extendedUris.push_back(
								Manager::ExtendedUri(uri, shortAlias, longAlias));
					}
					downloadEntity.targetPath = filename;
					downloadEntity.size = record.size;
					downloadEntity.postAction = [record, filename]() -> string
					{
						if (!record.hashSums.verify(filename))
						{
							if (unlink(filename.c_str()) == -1)
							{
								warn2e(__("unable to remove the file '%s'"), filename);
							}
							return __("hash sums mismatch");
						}
						return "";
					};

					downloadEntities.push_back(std::move(downloadEntity));
				}
			}
		}
	}


	{ // downloading
		auto downloadProgress = getDownloadProgress(*config);
		Manager downloadManager(config, downloadProgress);
		auto downloadError = downloadManager.download(downloadEntities);
		if (!downloadError.empty())
		{
			fatal2(__("there were download errors"));
		}
	}; // make sure that download manager is already destroyed at this point

	if (!downloadOnly)
	{
		// unpack downloaded sources
		for (const auto& filename: dscFilenames)
		{
			string command = "dpkg-source -x " + filename;
			if (::system(command.c_str()))
			{
				warn2(__("dpkg-source on the file '%s' failed"), filename);
			}
		}
	}

	// all's good
	return 0;
}

int downloadChangelogOrCopyright(Context& context, ChangelogOrCopyright::Type type)
{
	if (!shellMode)
	{
		Version::parseInfoOnly = false;
		Version::parseRelations = false;
	}

	auto config = context.getConfig();

	vector< string > arguments;
	bpo::options_description options("");
	options.add_options()
		("installed-only", "");
	auto variables = parseOptions(context, options, arguments);

	if (arguments.empty())
	{
		fatal2(__("no binary package expressions specified"));
	}

	auto cache = context.getCache(false, !variables.count("installed-only"), true);

	const string typeString = (type == ChangelogOrCopyright::Changelog ?
			"changelog" : "copyright");
	const map< string, string > baseUrisByVendor = {
		{ "Debian", "http://packages.debian.org/changelogs/pool" },
		{ "Ubuntu", "http://changelogs.ubuntu.com/changelogs/pool" },
		// yes, 'changelogs' even for copyrights :)
	};

	string pagerProgram;
	{
		auto systemState = cache->getSystemState();
		auto installedStatus = State::InstalledRecord::Status::Installed;

		auto sensibleUtilsInstalledInfo = systemState->getInstalledInfo("sensible-utils");
		if (sensibleUtilsInstalledInfo && sensibleUtilsInstalledInfo->status == installedStatus)
		{
			pagerProgram = "sensible-pager";
		}
		else
		{
			auto lessInstalledInfo = systemState->getInstalledInfo("less");
			if (lessInstalledInfo && lessInstalledInfo->status == installedStatus)
			{
				pagerProgram = "less";
			}
			else
			{
				pagerProgram = "cat";
			}
		}
	}

	for (const auto& argument: arguments)
	{
		auto versions = selectBinaryVersionsWildcarded(*cache, argument);

		for (const auto& version: versions)
		{
			string localTargetPath;
			if (type == ChangelogOrCopyright::Changelog)
			{
				localTargetPath = Cache::getPathOfChangelog(version);
			}
			else
			{
				localTargetPath = Cache::getPathOfCopyright(version);
			}

			if (!localTargetPath.empty())
			{
				// there is a local changelog/copyright, display it
				auto preparedCommand = (type == ChangelogOrCopyright::Changelog ? "zcat" : "cat");
				auto result = ::system(format2("%s %s | %s",
						preparedCommand, localTargetPath, pagerProgram).c_str());
				// return non-zero code in case of some error
				if (result)
				{
					return result;
				}
			}
			else
			{
				Manager::DownloadEntity downloadEntity;
				for (const auto& source: version->sources)
				{
					if (source.release->vendor != "Debian" && source.release->vendor != "Ubuntu")
					{
						// this is probably not a package from Debian or Ubuntu archive
						continue;
					}

					// all following is only good guessings
					string sourceVersionString = version->sourceVersionString;
					{ // a hack to work around dropping epoch on Debian/Ubuntu web links
						auto position = sourceVersionString.find(':');
						if (position != string::npos)
						{
							sourceVersionString = sourceVersionString.substr(position+1);
						}
					}
					const string& sourcePackageName = version->sourcePackageName;
					string shortPrefix = sourcePackageName.compare(0, 3, "lib") ?
							sourcePackageName.substr(0, 1) : sourcePackageName.substr(0, 4);


					string uri = baseUrisByVendor.find(source.release->vendor)->second + '/' +
							source.release->component + '/' + shortPrefix + '/' +
							sourcePackageName + '/' + sourcePackageName + '_' +
							sourceVersionString + '/' + typeString;

					const string& shortAlias = version->packageName;
					string longAlias = version->packageName + ' ' + version->versionString + ' ' + typeString;
					downloadEntity.extendedUris.push_back(Manager::ExtendedUri(
							uri, shortAlias, longAlias));
				}

				if (!downloadEntity.extendedUris.empty())
				{
					downloadEntity.size = (size_t)-1;

					char tempFilename[] = "cupt-download-XXXXXX";
					if (mkstemp(tempFilename) == -1)
					{
						fatal2e(__("%s() failed"), "mkstemp");
					}

					try
					{
						downloadEntity.targetPath = tempFilename;
						downloadEntity.postAction = []()
						{
							return string(); // no action
						};

						string downloadError;
						{ // downloading
							auto downloadProgress = getDownloadProgress(*config);
							Manager downloadManager(config, downloadProgress);
							downloadError = downloadManager.download(
									vector< Manager::DownloadEntity >{ downloadEntity });

						}
						if (!downloadError.empty())
						{
							fatal2(__("there were download errors"));
						}

						auto viewResult = ::system((pagerProgram + ' ' + tempFilename).c_str());

						// remove the file
						if (unlink(tempFilename) == -1)
						{
							fatal2e(__("unable to remove the file '%s'"), tempFilename);
						}

						// return non-zero code in case of some error
						if (viewResult)
						{
							return viewResult;
						}
					}
					catch (...)
					{
						unlink(tempFilename); // without checking errors
						throw;
					}
				}
				else
				{
					fatal2(__("no info where to acquire %s for version '%s' of package '%s'"),
							typeString, version->versionString, version->packageName);
				}
			}
		}
	}

	return 0;
}