summaryrefslogtreecommitdiff
path: root/ept/apt/apt.cc
blob: 0825828411f30a0979f9c0e429def09aa33ebe01 (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
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
/** \file
 * High-level front-end to libapt-pkg, as a data provider for the ept framework.
 */

/* 
 * Copyright (C) 2007,2008  Enrico Zini <enrico@enricozini.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */

#include "apt.h"
#include "ept/utils/sys.h"
#include <apt-pkg/error.h>
#include <apt-pkg/init.h>
#include <apt-pkg/progress.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/pkgcachegen.h>
#include <apt-pkg/policy.h>
#include <apt-pkg/cachefile.h>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

namespace ept {
namespace apt {

static time_t aptTimestamp()
{
    time_t t1 = sys::timestamp(_config->FindFile("Dir::Cache::pkgcache"), 0);
    time_t t2 = sys::timestamp(_config->FindFile("Dir::State::status"), 0);

    return t1 > t2 ? t1 : t2;
}

static std::string apt_annotate_error_message(const std::string& message)
{
    string res = message;
    res += ":\n";
    // Concatenate all errors and warnings found
    string err;
    while (!_error->empty())
    {
        bool type = _error->PopMessage(err);
        if (type)
            res += "E: " + err + "\n";
        else
            res += "W: " + err + "\n";
    }
    return res;
}

Exception::Exception(const std::string& message)
    : std::runtime_error(apt_annotate_error_message(message))
{
}

Exception::~Exception() noexcept {}

static void aptInit ()
{
    if (_config->FindB("Initialized"))
        return;

    if (!pkgInitConfig (*_config))
		throw Exception("initialising apt configuration");

    _config->Set("Initialized", 1);

	/*
    _config->Set("Dir", CACHE_DIR);
    _config->Set("Dir::Cache", "cache");
    _config->Set("Dir::State", "state");
    _config->Set("Dir::Etc", "etc");
    _config->Set("Dir::State::status", CACHE_DIR "dpkg-status");
	*/
    if (!pkgInitSystem (*_config, _system))
		throw Exception("initialising apt system");
}

struct AptImplementation
{
	pkgSourceList* m_list;
	MMap *m;
	OpProgress progress;
	pkgCache* m_cache;
	pkgPolicy* m_policy;
	pkgCacheFile* m_depcache;
	time_t m_open_timestamp;
	
	AptImplementation() : m_list(0), m(0), m_cache(0), m_policy(0), m_depcache(0), m_open_timestamp(0)
	{
		// Init the apt library if needed
		aptInit();

		m_open_timestamp = aptTimestamp();

		m_list = new pkgSourceList;
		if (!m_list->ReadMainList())
			throw Exception("reading list of sources");

		bool res = pkgMakeStatusCache(*m_list, progress, &m, true);
		progress.Done();
		if (!res)
			throw Exception("Reading the package lists or status file");

		m_cache = new pkgCache(m);
		m_policy = new pkgPolicy(m_cache);
		if (!ReadPinFile(*m_policy))
			throw Exception("Reading the policy pin file");
	}

	~AptImplementation()
	{
		if (m_depcache) delete m_depcache;
		if (m_policy) delete m_policy;
		if (m_cache) delete m_cache;
		if (m) delete m;
		if (m_list) delete m_list;
	}

	pkgCache& cache()
	{
		return *m_cache;
	}

	pkgPolicy& policy()
	{
		return *m_policy;
	}

	pkgCacheFile& depcache()
	{
		if (!m_depcache)
		{
			m_depcache = new pkgCacheFile;
			if (!m_depcache->Open(progress, false))
				throw Exception("Opening the cache file");
		}
		return *m_depcache;
	}
};

// Sort a version list by package file locality
bool localityCompare(const pkgCache::VerFile* a, const pkgCache::VerFile* b)
{
   if (a == 0 && b == 0)
      return false;
   if (a == 0)
      return true;
   if (b == 0)
      return false;
   
   if (a->File == b->File)
      return a->Offset < b->Offset;
   return a->File < b->File;
}

// Iterate records using the algorithm used by apt-cache dumpavail
struct RecordIteratorImpl
{
	mutable int _ref;
	AptImplementation& apt;
	vector<pkgCache::VerFile*> vflist;
	pkgCache::PkgFileIterator lastFile;
	FileFd file;
	size_t lastOffset;

	RecordIteratorImpl(AptImplementation& apt) : _ref(0), apt(apt)
	{
		// We already have an estimate of how many versions we're about to find
		vflist.reserve(apt.cache().HeaderP->PackageCount + 1);

		// Populate the vector of versions to print
		for (pkgCache::PkgIterator pi = apt.cache().PkgBegin(); !pi.end(); ++pi)
		{    
			if (pi->VersionList == 0)
				continue;

			/* Get the candidate version or fallback on the installed version,
			 * as usual */
			pkgCache::VerIterator vi = apt.policy().GetCandidateVer(pi);
			if (vi.end() == true)
			{
				if (pi->CurrentVer == 0)
					continue;
				vi = pi.CurrentVer();
			}

			// Choose a valid file that contains the record for this version
			pkgCache::VerFileIterator vfi = vi.FileList();
			for ( ; !vfi.end(); ++vfi)
				if ((vfi.File()->Flags & pkgCache::Flag::NotSource) == 0)
					break;

			// Handle packages whose candidate version is currently installed
			// from outside the archives (like from a locally built .deb
			if (vfi.end() == true)
			{
				for (pkgCache::VerIterator cur = pi.VersionList(); cur.end() != true; cur++)
				{
					for (vfi = cur.FileList(); vfi.end() == false; vfi++)
					{	 
						if ((vfi.File()->Flags & pkgCache::Flag::NotSource) == 0)
						{
							vfi = vi.FileList();
							break;
						}
					}

					if (vfi.end() == false)
						break;
				}
			}
			if (!vfi.end())
				vflist.push_back(vfi);
		}

		//cerr << vflist.size() << " versions found" << endl;

		sort(vflist.begin(), vflist.end(), localityCompare);

		//for (size_t i = 0; i < vflist.size(); ++i)
		//{
		//	pkgCache::PkgFileIterator fi(apt.cache(), vflist[i]->File + apt.cache().PkgFileP);
		//	cerr << i << ": " << fi.FileName() << ":" << vflist[i]->Offset << "-" << vflist[i]->Size << endl;
		//}
		//cerr << "Done indexing." << endl;
	}

	~RecordIteratorImpl()
	{
		if (file.IsOpen())
			file.Close();
	}

	void ref() { ++_ref; }
	bool unref() { return --_ref == 0; }

	size_t size() { return vflist.size(); }

	string record(size_t idx)
	{
		//cerr << "Access record " << idx << endl;
		//cerr << "lastfile: " << (lastFile.Cache() != 0) << endl;
		// We can't reuse the file that was already open: open the new one
		if ((lastFile.Cache() == 0) || vflist[idx]->File + apt.cache().PkgFileP != lastFile)
		{
			//cerr << "Needs open/reopen" << endl;
			lastFile = pkgCache::PkgFileIterator(apt.cache(), vflist[idx]->File + apt.cache().PkgFileP);
			if (!lastFile.IsOk())
				throw Exception(string("Reading the data record for a package from file ") + lastFile.FileName());
			//cerr << "Ok for " << lastFile.FileName() << endl;
			if (file.IsOpen())
				file.Close();
			if (!file.Open(lastFile.FileName(), FileFd::ReadOnly))
				throw Exception(string("Opening file ") + lastFile.FileName());
			//cerr << "Opened " << lastFile.FileName() << endl;
			lastOffset = 0;
		}

		//cerr << "Reading from " << lastFile.FileName() << ":" << vflist[idx]->Offset << "-" << vflist[idx]->Size << " (lastOffset: " << lastOffset << ")" << endl;

		// If we start near were we ended, avoid a seek and enlarge the read a bit
		size_t slack = vflist[idx]->Offset - lastOffset;
		//cerr << "Slack: " << slack << endl;
		if (slack > 8)
		{
			//cerr << "Slack too big: seek to " << vflist[idx]->Offset << endl;
			slack = 0;
			if (!file.Seek(vflist[idx]->Offset))
				throw Exception(string("Cannot seek to package record in file ") + lastFile.FileName());
		}

		char buffer[vflist[idx]->Size + slack + 1];
		if (!file.Read(buffer, vflist[idx]->Size + slack))
			throw Exception(string("Cannot read package record in file ") + lastFile.FileName());
		buffer[vflist[idx]->Size + slack] = '\n';
		//cerr << "Data read (slack: " << slack << ")" << endl;

		lastOffset = vflist[idx]->Offset + vflist[idx]->Size;

		return string(buffer+slack, vflist[idx]->Size);
	}
};

Apt::Iterator::Iterator(const Iterator& i)
{
	if (i.cur)
	{
		pkgCache::PkgIterator* p = new pkgCache::PkgIterator;
		*p = *static_cast<pkgCache::PkgIterator*>(i.cur);
		cur = p;
	} else
		cur = 0;
}

Apt::Iterator& Apt::Iterator::operator=(const Iterator& i)
{
	if (cur != i.cur)
	{
		if (cur) delete static_cast<pkgCache::PkgIterator*>(cur);
		if (i.cur)
		{
			pkgCache::PkgIterator* p = new pkgCache::PkgIterator;
			*p = *static_cast<pkgCache::PkgIterator*>(i.cur);
			cur = p;
		} else
			cur = 0;
	}
	return *this;
}

Apt::Iterator::~Iterator()
{
	if (cur) delete static_cast<pkgCache::PkgIterator*>(cur);
}
std::string Apt::Iterator::operator*()
{
	return static_cast<pkgCache::PkgIterator*>(cur)->Name();
}
Apt::Iterator& Apt::Iterator::operator++()
{
	pkgCache::PkgIterator* iter = static_cast<pkgCache::PkgIterator*>(cur);
	++*iter;
	while (!iter->end() && (*iter)->VersionList == 0)
		++*iter;
	if (iter->end())
	{
		delete iter;
		cur = 0;
	}
	return *this;
}
bool Apt::Iterator::operator==(const Iterator& i) const
{
	if (cur == 0 && i.cur == 0)
		return true;
	if (cur == 0 || i.cur == 0)
		return false;
	pkgCache::PkgIterator* iter1 = static_cast<pkgCache::PkgIterator*>(cur);
	pkgCache::PkgIterator* iter2 = static_cast<pkgCache::PkgIterator*>(i.cur);
	return *iter1 == *iter2;
}
bool Apt::Iterator::operator!=(const Iterator& i) const
{
	if (cur == 0 && i.cur == 0)
		return false;
	if (cur == 0 || i.cur == 0)
		return true;
	pkgCache::PkgIterator* iter1 = static_cast<pkgCache::PkgIterator*>(cur);
	pkgCache::PkgIterator* iter2 = static_cast<pkgCache::PkgIterator*>(i.cur);
	return *iter1 != *iter2;
}


Apt::RecordIterator::RecordIterator(RecordIteratorImpl* impl, size_t pos)
	: impl(impl), pos(pos), cur_pos(pos)
{
	if (impl)
	{
		impl->ref();
		cur = impl->record(pos);
		cur_pos = pos;
	}
}
Apt::RecordIterator::RecordIterator(const RecordIterator& r)
	: impl(r.impl), pos(r.pos), cur(r.cur), cur_pos(r.cur_pos)
{
	if (impl)
		impl->ref();
}
Apt::RecordIterator::~RecordIterator()
{
	if (impl && impl->unref())
		delete impl;
}
std::string Apt::RecordIterator::operator*()
{
	if (cur_pos != pos)
	{
		cur = impl->record(pos);
		cur_pos = pos;
	}
	return cur;
}
std::string* Apt::RecordIterator::operator->()
{
	if (cur_pos != pos)
	{
		cur = impl->record(pos);
		cur_pos = pos;
	}
	return &cur;
}
Apt::RecordIterator& Apt::RecordIterator::operator++()
{
	++pos;
	if (pos >= impl->size())
	{
		// If we reach the end, we become an end iterator
		if (impl && impl->unref())
			delete impl;
		impl = 0;
		pos = 0;
	}
	return *this;
}
Apt::RecordIterator& Apt::RecordIterator::operator=(const RecordIterator& r)
{
	// Increment first, to avoid it reaching zero on assignment to self
	if (r.impl) r.impl->ref();
	if (impl && impl->unref())
		delete impl;
	impl = r.impl;
	pos = r.pos;
	cur = r.cur;
	cur_pos = r.cur_pos;
	return *this;
}
bool Apt::RecordIterator::operator==(const RecordIterator& ri) const
{
	return impl == ri.impl && pos == ri.pos;
}
bool Apt::RecordIterator::operator!=(const RecordIterator& ri) const
{
	return impl != ri.impl || pos != ri.pos;
}


Apt::Apt() : impl(new AptImplementation()) {}
Apt::~Apt() { delete impl; }

Apt::iterator Apt::begin() const
{
	pkgCache::PkgIterator* p = new pkgCache::PkgIterator;
	*p = impl->cache().PkgBegin();
	return Apt::Iterator(p);
}

Apt::iterator Apt::end() const
{
	return Apt::Iterator();
}

Apt::record_iterator Apt::recordBegin() const
{
	return Apt::RecordIterator(new RecordIteratorImpl(*impl));
}

Apt::record_iterator Apt::recordEnd() const
{
	return Apt::RecordIterator();
}

size_t Apt::size() const
{
   	return impl->cache().HeaderP->PackageCount;
}

time_t Apt::timestamp()
{
	return aptTimestamp();
}

bool Apt::isValid(const std::string& pkg) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(pkg);
	return !pi.end();
}

Version Apt::validate(const Version& ver) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(ver.name());
	if (pi.end()) return Version();
	for (pkgCache::VerIterator vi = pi.VersionList(); !vi.end(); vi++)
	{
		const char* v = vi.VerStr();
		if (v == 0) continue;
		if (ver.version() == v)
			return ver;
	}
	return Version();
}

Version Apt::candidateVersion(const std::string& pkg) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(pkg);
	if (pi.end()) return Version();
	pkgCache::VerIterator vi = impl->policy().GetCandidateVer(pi);
	if (vi.end()) return Version();
	return Version(pkg, vi.VerStr());
}

Version Apt::installedVersion(const std::string& pkg) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(pkg);
	if (pi.end()) return Version();
	if (pi->CurrentVer == 0) return Version();
	pkgCache::VerIterator vi = pi.CurrentVer();
	if (vi.end()) return Version();
	return Version(pkg, vi.VerStr());
}

Version Apt::anyVersion(const std::string& pkg) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(pkg);
	if (pi.end()) return Version();

	pkgCache::VerIterator vi = impl->policy().GetCandidateVer(pi);
	if (vi.end())
	{
		if (pi->CurrentVer == 0) return Version();
		vi = pi.CurrentVer();
		if (vi.end()) return Version();
	}
	return Version(pkg, vi.VerStr());
}

PackageState Apt::state(const std::string& pkg) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(pkg);
	if (pi.end()) return PackageState();
	pkgDepCache::StateCache sc = impl->depcache()[pi];

	unsigned int flags = PackageState::Valid;

	// Check if the package is installed
    if (pi->CurrentState != pkgCache::State::ConfigFiles &&
		pi->CurrentState != pkgCache::State::NotInstalled &&
		pi->CurrentVer != 0)
	{
		// Try to get a VerIterator to the installed version
		pkgCache::VerIterator inst = pi.CurrentVer();
		if (!inst.end())
		{
			// If we made it so far, it is installed
			flags |= PackageState::Installed;

			// Now check if it is upgradable
			pkgCache::VerIterator cand = impl->policy().GetCandidateVer(pi);

			// If the candidate version is different than the installed one, then
			// it is installable
			if (!cand.end() && inst != cand)
				flags |= PackageState::Upgradable;
		}
	}
    if (sc.Install())
        flags |= PackageState::Install;
    if ((sc.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
        flags |= PackageState::ReInstall;
    if (sc.Keep())
        flags |= PackageState::Keep;
    if (sc.Delete())
        flags |= PackageState::Remove;
    if ((sc.iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
        flags |= PackageState::Purge;
    if (sc.NowBroken())
        flags |= PackageState::NowBroken;
    if (sc.InstBroken())
        flags |= PackageState::WillBreak;

	return PackageState(flags);
}

std::string Apt::rawRecord(const std::string& ver) const
{
	// TODO: possibly reimplement using a single lump of apt code, to avoid
	// repeating lookups
	return rawRecord(anyVersion(ver));
}

std::string Apt::rawRecord(const Version& ver) const
{
	pkgCache::PkgIterator pi = impl->cache().FindPkg(ver.name());
	if (pi.end()) return std::string();
	for (pkgCache::VerIterator vi = pi.VersionList(); !vi.end(); vi++)
	{
		const char* v = vi.VerStr();
		if (v == 0) continue;
		if (ver.version() == v)
		{
			// Code taken and adapted from apt-cache's DisplayRecord

			// Find an appropriate file
			pkgCache::VerFileIterator vfi = vi.FileList();
			for (; !vfi.end(); vfi++)
				if ((vfi.File()->Flags & pkgCache::Flag::NotSource) == 0)
					break;
			if (vfi.end())
				vfi = vi.FileList();

			// Check and load the package list file
			pkgCache::PkgFileIterator pfi = vfi.File();
			if (!pfi.IsOk())
				throw Exception(string("Reading the data record for a package version from file ") + pfi.FileName());

			FileFd pkgf(pfi.FileName(), FileFd::ReadOnly);
			if (_error->PendingError() == true)
				return std::string();

			// Read the record and then write it out again.
			char* buffer = new char[vfi->Size+1];
			buffer[vfi->Size] = '\n';
			if (!pkgf.Seek(vfi->Offset) || !pkgf.Read(buffer, vfi->Size))
			{
				delete[] buffer;
				return std::string();
			}

			std::string res(buffer, vfi->Size);
			delete[] buffer;
			return res;
		}
	}
	return std::string();
}


const pkgCache* Apt::aptPkgCache() const 
{
	return impl->m_cache;
}


void Apt::checkCacheUpdates()
{
	if (impl->m_open_timestamp < timestamp())
	{
		// Crudely reopen everything
		delete impl;
		impl = new AptImplementation;
	}
}

void Apt::invalidateTimestamp()
{
	impl->m_open_timestamp = 0;
}

}
}

// vim:set ts=4 sw=4: