File: apt.cc

package info (click to toggle)
aptitude 0.8.11-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 40,536 kB
  • sloc: cpp: 95,205; xml: 31,928; sh: 5,142; makefile: 922; perl: 88; cs: 70; lisp: 55; sed: 16
file content (1753 lines) | stat: -rw-r--r-- 47,607 bytes parent folder | download
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
// apt.cc
//
//  Copyright 1999-2010 Daniel Burrows
//  Copyright 2015-2018 Manuel A. Fernandez Montecelo
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  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 General Public License
//  along with this program; see the file COPYING.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
//  Boston, MA 02110-1301, USA.
//
//  Handles basic apt bookkeeping.

#include "apt.h"

#include <aptitude.h>
#include <loggers.h>

#include "aptitude_resolver_universe.h"
#include "config_file.h"
#include "config_signal.h"
#include "download_queue.h"
#include "resolver_manager.h"
#include "rev_dep_iterator.h"
#include "tags.h"
#include "tasks.h"

#include <cwidget/generic/util/eassert.h>
#include <cwidget/generic/util/transcode.h>

#include <generic/util/file_cache.h>
#include <generic/util/util.h>

#include <generic/util/undo.h>

#include <apt-pkg/acquire.h>
#include <apt-pkg/aptconfiguration.h>
#include <apt-pkg/clean.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/depcache.h>
#include <apt-pkg/dpkgpm.h>
#include <apt-pkg/error.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/init.h>
#include <apt-pkg/pkgcachegen.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/version.h>

#include <exception>
#include <filesystem>
#include <fstream>
#include <regex>
#include <sstream>

#include <signal.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>

using namespace std;
using aptitude::Loggers;

namespace cw = cwidget;
namespace fs = std::filesystem;

enum interesting_state {uncached = 0, uninteresting, interesting};
static interesting_state *cached_deps_interesting = NULL;

// Memoization of surrounding_or.  To save space, the low bit of each
// pointer in the following table is set to 1 when a result is cached:
static pkgCache::Dependency **cached_surrounding_or = NULL;

string *pendingerr=NULL;
bool erroriswarning=false;


// Set to "true" if we have a version of the apt library with
// support for overriding configuration settings via RootDir.
static bool apt_knows_about_rootdir;

static Configuration *theme_config;
static Configuration *user_config;

sigc::signal0<void> cache_closed, cache_reloaded, cache_reload_failed;
sigc::signal0<void> hier_reloaded;
sigc::signal0<void> consume_errors;

static string apt_native_arch;

// Access to the download_cache
std::shared_ptr<aptitude::util::file_cache> download_cache;


static void reset_interesting_dep_memoization()
{
  delete[] cached_deps_interesting;
  cached_deps_interesting = NULL;
}

static void reset_surrounding_or_memoization()
{
  delete[] cached_surrounding_or;
  cached_surrounding_or = NULL;
}

bool get_apt_knows_about_rootdir()
{
  return apt_knows_about_rootdir;
}

/** Read and check that the config file doesn't contain errors, otherwise exit.
 *
 * See #472701 for the motivation.  Upon reading the configuration file
 * (especially "~/.aptitude/config"), it was writing it back immediately, and
 * the writing stopped at the point of the reading failure (instead of just
 * skipping the problematic parts), so part of the previous configuration file
 * was lost.
 *
 * It is safer (and not too onerous) to ask the user to fix the configuration
 * before continuing, rather than stomping on valid configuration values.
 */
void readconfigfile_or_die(Configuration& config, const std::string& path)
{
  bool config_ok = ReadConfigFile(config, path);

  if (!config_ok)
    {
      _error->Error(_("Configuration file '%s' is not correct, please fix it"), path.c_str());
      _error->DumpErrors();
      exit(EXIT_FAILURE);
    }
}

void apt_preinit(const char *rootdir)
{
  logging::LoggerPtr logger(Loggers::getAptitudeAptGlobals());

  // The old name for the recommends-should-be-automatically-installed
  // setting and the new one.
  const char * const aptitudeIgnoreRecommendsImportant = PACKAGE "::Ignore-Recommends-Important";
  const char * const aptitudeRecommendsImportant = PACKAGE "::Recommends-Important";
  const char * const aptInstallRecommends = "APT::Install-Recommends";

  signal(SIGPIPE, SIG_IGN);

  // Probe apt to see if it has RootDir support.
  {
    Configuration tmp;
    config_change_pusher push1("RootDir", "/a/b/c/d", tmp);
    config_change_pusher push2("Dir::ASDF", "/x/y/z", tmp);

    std::string found_loc = tmp.FindFile("Dir::ASDF");

    std::string real_found_loc;
    for(std::string::const_iterator it = found_loc.begin();
	it != found_loc.end(); ++it)
      {
	// Drop repeated slashes.
	if(*it != '/' || real_found_loc.size() == 0 ||
	   real_found_loc[real_found_loc.size() - 1] != '/')
	  real_found_loc.push_back(*it);
      }

    apt_knows_about_rootdir =
      (real_found_loc == "/a/b/c/d/x/y/z");
  }

  theme_config=new Configuration;
  user_config=new Configuration;

  if(strempty(rootdir) == false)
    {
      _config->Set("RootDir", rootdir);
      theme_config->Set("RootDir", rootdir);
      user_config->Set("RootDir", rootdir);
    }

  readconfigfile_or_die(*theme_config, PKGDATADIR "/aptitude-defaults");

  pkgInitConfig(*_config);

  readconfigfile_or_die(*_config, PKGDATADIR "/section-descriptions");

  // TRANSLATORS: Set this string to the name of a configuration
  // file in $pkgdatadir/aptitude that overrides defaults for your
  // language.  This is particularly intended for overriding entries
  // in the Aptitude::Sections::Descriptions tree.
  //
  // For instance, Sections localized for the language .ww might be
  // stored in a file named aptitude-defaults.ww, which would be
  // indicated by translating "Localized defaults|" below to
  // "aptitude-defaults.ww".  If you use this mechanism, you should
  // also add your defaults file to pkgdata_DATA in Makefile.am.
  std::string localized_config_name = P_("Localized defaults|");
  if (localized_config_name.size() > 0)
    {
      readconfigfile_or_die(*_config, string(PKGDATADIR "/") + localized_config_name);
    }

  pkgInitSystem(*_config, _system);

  // Allow a user-specific customization file.
  const char *HOME = getenv("HOME");

  string cfgloc;

  if(strempty(HOME) == false &&
     access((string(HOME) + "/.aptitude").c_str(), R_OK | X_OK) == 0)
    cfgloc = string(HOME) + "/.aptitude/config";
  else
    {
      cfgloc = get_homedir();
      if(!cfgloc.empty())
	cfgloc += "/.aptitude/config";
    }

  if(!cfgloc.empty() && access(cfgloc.c_str(), R_OK) == 0)
    {
      readconfigfile_or_die(*user_config, cfgloc);
      readconfigfile_or_die(*_config, cfgloc);
    }

  aptcfg=new signalling_config(user_config, _config, theme_config);

  // If the user has a Recommends-Important setting and has allowed us
  // to read it by seting Ignore-Recommends-Important to false,
  // migrate it over and then set Ignore-Recommends-Important to true.
  if(!aptcfg->FindB(aptitudeIgnoreRecommendsImportant, false) &&
     aptcfg->Exists(aptitudeRecommendsImportant))
    {
      // If it was overridden to "false" and the system setting for
      // APT::Install-Recommends is "true", set the latter to "false"
      // to preserve aptitude's behavior.
      if(!aptcfg->FindB(aptitudeRecommendsImportant, true) &&
	 aptcfg->FindB(aptInstallRecommends, true))
	aptcfg->Set(aptInstallRecommends, "false");

      aptcfg->Set(aptitudeIgnoreRecommendsImportant, "true");

      apt_dumpcfg(PACKAGE);
    }

  aptcfg->connect("APT::Install-Recommends",
		  sigc::ptr_fun(&reset_interesting_dep_memoization));

  cache_closed.connect(sigc::ptr_fun(&reset_interesting_dep_memoization));

  cache_closed.connect(sigc::ptr_fun(&reset_surrounding_or_memoization));

  apt_dumpcfg(PACKAGE);

  apt_undos=new undo_list;
}

void apt_dumpcfg(const char *root)
{
  // Don't write RootDir to the user's configuration file -- it causes
  // horrible confusion.
  std::string rootDir(_config->Find("RootDir", ""));
  _config->Clear("RootDir");

  std::ostringstream content;
  aptcfg->Dump(content);

  _config->Set("RootDir", rootDir);

  try
    {
      if ( ! aptitude::apt::ConfigFile::write(content.str()) )
	{
	  throw std::runtime_error("");
	}
    }
  catch (...)
    {
      _error->Errno("apt_dumpcfg", _("Error saving configuration file"));
      return;
    }
}

// Revert back to the default set of options.  Is it a hack?  mHmm...
void apt_revertoptions()
{
  Configuration *old_user_config=user_config;
  Configuration *old_config=_config;

  // Preserve any existing root-dir settings in the new configuration.
  const std::string old_rootdir = _config->Find("RootDir", "");

  _config=new Configuration;

  user_config=new Configuration;

  _config->Set("RootDir", old_rootdir);
  user_config->Set("RootDir", old_rootdir);

  // ick?
  pkgInitConfig(*_config);
  pkgInitSystem(*_config, _system);

  aptcfg->setcfg(user_config, _config, theme_config);

  delete old_user_config;
  delete old_config;
}

void apt_init(OpProgress *progress_bar, bool do_initselections,
	      bool operation_needs_lock,
	      const char *status_fname)
{
  if(!apt_cache_file)
    apt_reload_cache(progress_bar, do_initselections, operation_needs_lock, status_fname);
}

void apt_close_cache()
{
  logging::LoggerPtr logger(Loggers::getAptitudeAptGlobals());

  LOG_INFO(logger, "Closing apt cache.");

  cache_closed();

  LOG_TRACE(logger, "Done emitting cache_closed().");

  //   DANGER WILL ROBINSON!
  //
  // This must be done *** BEFORE BEFORE BEFORE *** we delete the
  // current cache file, since until the resolver manager is deleted,
  // there might actually be an active resolver thread trying to use
  // the cache!
  if(resman)
    {
      delete resman;
      resman = NULL;

      LOG_TRACE(logger, "Deleted the global dependency resolver manager.");
    }
  else
    LOG_TRACE(logger, "No global dependency resolver manager exists; none deleted.");

  aptitude::apt::reset_tasks();

  LOG_TRACE(logger, "Tasks reset.");

  if(apt_package_records)
    {
      delete apt_package_records;
      apt_package_records=NULL;
      LOG_TRACE(logger, "Deleted the apt package records.");
    }
  else
    LOG_TRACE(logger, "No global apt package records exist; none deleted.");

  if(apt_cache_file)
    {
      delete apt_cache_file;
      apt_cache_file=NULL;
      LOG_TRACE(logger, "Deleted the apt cache file.");
    }
  else
    LOG_TRACE(logger, "No global apt cache file exists; none deleted.");

  if(apt_source_list)
    {
      delete apt_source_list;
      apt_source_list=NULL;
      LOG_TRACE(logger, "Deleted the apt sources list.");
    }
  else
    LOG_TRACE(logger, "No global apt sources list exists; none deleted.");

  LOG_DEBUG(logger, "Done closing the apt cache.");
}

void apt_load_cache(OpProgress *progress_bar, bool do_initselections,
		    bool operation_needs_lock,
		    const char * status_fname,
		    bool reset_reinstall)
{
  logging::LoggerPtr logger(Loggers::getAptitudeAptGlobals());

  if(apt_cache_file != NULL)
    {
      LOG_TRACE(logger, "Not loading apt cache: it's already loaded.");
      return;
    }

  LOG_INFO(logger, "Loading apt cache.");

  aptitudeCacheFile *new_file=new aptitudeCacheFile;

  LOG_TRACE(logger, "Reading the sources list.");
  apt_source_list=new pkgSourceList;
  apt_source_list->ReadMainList();

  bool simulate = aptcfg->FindB(PACKAGE "::Simulate", false);

  if(simulate)
    LOG_DEBUG(logger, PACKAGE "::Simulate is set; not locking the cache file.");

  // Clear the error stack so that we don't get confused by old errors.
  consume_errors();

  LOG_TRACE(logger, "Opening the apt cache.");

  bool open_failed=!new_file->Open(progress_bar, do_initselections,
				   operation_needs_lock && ((getuid() == 0) && !simulate),
				   status_fname,
				   reset_reinstall)
    || _error->PendingError();

  if(open_failed && getuid() == 0)
    {
      // Hm, we should include the errors, but there's no
      // nondestructive way to do that. :-(
      LOG_ERROR(logger, "Failed to load the apt cache; trying to open it without locking.");

      // Don't discard errors, make sure they get displayed instead.
      consume_errors();

      open_failed=!new_file->Open(progress_bar, do_initselections,
				  false, status_fname,
				  reset_reinstall);

      if(open_failed)
	LOG_ERROR(logger, "Unable to load the apt cache at all; giving up.");
      else
	LOG_DEBUG(logger, "Opening the apt cache with locking succeeded.");

      if(!open_failed)
	_error->Warning(_("Could not lock the cache file; this usually means that dpkg or another apt tool is already installing packages.  Opening in read-only mode; any changes you make to the states of packages will NOT be preserved!"));
    }

  if(open_failed)
    {
      delete new_file;
      LOG_DEBUG(logger, "Unable to load the apt cache; aborting and emitting cache_reload_failed().");
      cache_reload_failed();
      LOG_TRACE(logger, "Done emitting cache_reload_failed().");
      return;
    }

  apt_cache_file=new_file;

  // *If we were loading the global list of states*, dump immediate
  // changes back to it.  This reduces the chance that the user will
  // ^C and lose important changes (like the new dselect states of
  // packages).  Note, though, that we don't fail if this fails.
  if(!status_fname && apt_cache_file->is_locked())
    {
      LOG_TRACE(logger, "Trying to save the current selection list.");
      (*apt_cache_file)->save_selection_list(progress_bar);
    }

  // stop here if shutdown is in progress
  if (shutdown_in_progress)
    {
      return;
    }

  LOG_TRACE(logger, "Loading the apt package records.");
  apt_package_records=new pkgRecords(*apt_cache_file);

  // Um, good time to clear our undo info.
  apt_undos->clear_items();

  LOG_TRACE(logger, "Loading tags.");
  aptitude::apt::load_tags(progress_bar);

  LOG_TRACE(logger, "Initializing global dependency resolver manager.");
  resman = new resolver_manager(new_file, imm::map<aptitude_resolver_package, aptitude_resolver_version>());

  LOG_DEBUG(logger, "Emitting cache_reloaded().");
  cache_reloaded();
  LOG_TRACE(logger, "Done emitting cache_reloaded().");
}

std::shared_ptr<aptitude::util::file_cache> get_download_cache()
{
  // return if already initialised
  if (download_cache)
    return download_cache;

  logging::LoggerPtr logger(Loggers::getAptitudeAptGlobals());

  LOG_INFO(logger, "Loading download_cache.");

  // Open the download cache.  By default, it goes in
  // ~/.cache/aptitude/metadata-download; it has 512Kb of in-memory cache and
  // 10MB of on-disk cache.
  {
    // remove old path, if exists, so if config is empty and there are no other
    // files, ~/.aptitude can also be removed
    try
      {
	const char* env_HOME = getenv("HOME");
	if ( ! strempty(env_HOME))
	  {
	    string old_file = string(env_HOME) + "/.aptitude/cache";
	    fs::remove(old_file);
	  }
      }
    catch (const fs::filesystem_error& e)
      {
	// ignore exceptions, if the file does not exist or we cannot remove it,
	// it doesn't matter
      }

    // get xdg_cache_home directory to use
    const char* env_XDG_CACHE_HOME = getenv("XDG_CACHE_HOME");
    string xdg_cache_home;
    if ( ! strempty(env_XDG_CACHE_HOME))
      {
	xdg_cache_home = string(env_XDG_CACHE_HOME);
      }
    else
      {
	const char* env_HOME = getenv("HOME");
	string home = (! strempty(env_HOME)) ? string(env_HOME) : get_homedir();
	if (home.empty())
	  {
	    _error->Error(_("Could not establish home directory (username: '%s')"), get_username().c_str());
	  }
	else if ( ! fs::is_directory(home) )
	  {
	    _error->Error(_("Home directory does not exist or is not a directory: '%s')"), home.c_str());
	  }
	else
	  {
	    xdg_cache_home = home + "/.cache";
	  }
      }

    // if directory to be used could be gathered, create the path if needed
    std::string download_cache_dir;
    if (!xdg_cache_home.empty())
      {
	// if dir does not exist, create default $XDG_CACHE_HOME with the right
	// permisisons (0700) according to the spec -- see
	// http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html and
	// http://standards.freedesktop.org/basedir-spec/latest/ar01s04.html
	if ( ! fs::is_directory(xdg_cache_home) )
	  {
	    mode_t previous_umask = umask(0077);

	    try
	      {
		fs::create_directory(xdg_cache_home);
	      }
	    catch (const fs::filesystem_error& e)
	      {
		_error->Error(_("Could not create directory: %s: %s"), xdg_cache_home.c_str(), e.what());
	      }

	    umask(previous_umask);
	  }

	// if the directory exist, continue to the next step
	if ( fs::is_directory(xdg_cache_home) )
	  {
	    download_cache_dir = xdg_cache_home + "/aptitude";
	  }
      }

    // if directory to be used could be gathered, create full path if needed,
    // then assign filename
    std::string download_cache_file_name;
    if (!download_cache_dir.empty())
      {
	try
	  {
	    fs::create_directories(download_cache_dir);
	    download_cache_file_name = download_cache_dir + "/metadata-download";
	  }
	catch (const fs::filesystem_error& e)
	  {
	    _error->Error(_("Could not create directories: %s: %s"), download_cache_dir.c_str(), e.what());
	  }
      }

    // do create the cache file
    if (!download_cache_file_name.empty())
      {
	const int download_cache_memory_size =
	  aptcfg->FindI(PACKAGE "::UI::DownloadCache::MemorySize", 512 * 1024);
	const int download_cache_disk_size   =
	  aptcfg->FindI(PACKAGE "::UI::DownloadCache::DiskSize", 10 * 1024 * 1024);
	try
	  {
	    download_cache = aptitude::util::file_cache::create(download_cache_file_name,
								download_cache_memory_size,
								download_cache_disk_size);
	  }
	catch(cwidget::util::Exception &ex)
	  {
	    LOG_WARN(logger,
		     "Can't open the file cache \""
		     << download_cache_file_name
		     << "\": " << ex.errmsg());
	  }
	catch(std::exception &ex)
	  {
	    LOG_WARN(logger,
		     "Can't open the file cache \""
		     << download_cache_file_name
		     << "\": " << ex.what());
	  }
      }
  }

  return download_cache;
}

void apt_reload_cache(OpProgress *progress_bar, bool do_initselections,
		      bool operation_needs_lock,
		      const char * status_fname)
{
  apt_close_cache();
  apt_load_cache(progress_bar, do_initselections, operation_needs_lock, status_fname, false);
}

void apt_shutdown()
{
  aptitude::shutdown_download_queue();


  apt_close_cache();

  delete aptcfg;
  aptcfg = NULL;

  delete theme_config;
  theme_config = NULL;

  delete user_config;
  user_config = NULL;

  delete apt_undos;
  apt_undos = NULL;

  delete pendingerr;
  pendingerr = NULL;


  download_cache.reset();

  cache_closed.clear();
  cache_reloaded.clear();
  cache_reload_failed.clear();
  hier_reloaded.clear();
  consume_errors.clear();
}

pkg_action_state find_pkg_state(pkgCache::PkgIterator pkg,
				aptitudeDepCache &cache,
                                bool ignore_broken)
{
  aptitudeDepCache::StateCache &state = cache[pkg];
  aptitudeDepCache::aptitude_state &extstate = cache.get_ext_state(pkg);

  if(state.InstBroken() && !ignore_broken)
    return pkg_broken;
  else if(state.Delete())
    {
      if(extstate.remove_reason==aptitudeDepCache::manual)
	return pkg_remove;
      else if(extstate.remove_reason==aptitudeDepCache::unused)
	return pkg_unused_remove;
      else
	return pkg_auto_remove;
    }
  else if(state.Install())
    {
      if(!pkg.CurrentVer().end())
	{
	  if(state.iFlags&pkgDepCache::ReInstall)
	    return pkg_reinstall;
	  else if(state.Downgrade())
	    return pkg_downgrade;
	  else if(state.Upgrade())
	    return pkg_upgrade;
	  else
	    // FOO!  Should I abort here?
	    return pkg_install;
	}
      else if(state.Flags & pkgCache::Flag::Auto)
	return pkg_auto_install;
      else
	return pkg_install;
    }

  else if(state.Status==1 &&
	  state.Keep())
    {
      if(!(state.Flags & pkgDepCache::AutoKept))
	return pkg_hold;
      else
	return pkg_auto_hold;
    }

  else if(state.iFlags&pkgDepCache::ReInstall)
    return pkg_reinstall;
  // States where --configure fixes things.
  else if(pkg->CurrentState == pkgCache::State::UnPacked ||
	  pkg->CurrentState == pkgCache::State::HalfConfigured
	  || pkg->CurrentState == pkgCache::State::TriggersAwaited
	  || pkg->CurrentState == pkgCache::State::TriggersPending
	  )
    return pkg_unconfigured;

  return pkg_unchanged;
}

bool pkg_obsolete(pkgCache::PkgIterator pkg)
{
  if(pkg.CurrentVer().end())
    return false;
  else
    {
      pkgCache::VerIterator ver=pkg.VersionList();
      ver++;

      if(!ver.end())
	return false;
      else // Ok, there's only one version.  Good.
	{
	  pkgCache::VerFileIterator files=pkg.VersionList().FileList();
	  if(!files.end())
	    {
	      files++;
	      if(!files.end())
		return false; // Nope, more than one file
	    }
	}
    }

  return true;
}

// This does not assume that the dependency is the first elements of
// its OR group.
static void surrounding_or_internal(const pkgCache::DepIterator &dep,
				    pkgCache::DepIterator &start,
				    pkgCache::DepIterator &end)
{
  bool found=false;

  start=const_cast<pkgCache::DepIterator &>(dep).ParentVer().DependsList();
  end=start;

  while(!end.end() && !found)
    {
      start=end;

      while(end->CompareOp&pkgCache::Dep::Or)
	{
	  if(end==dep)
	    found=true;

	  ++end;
	}

      if(end==dep)
	found=true;

      ++end;
    }

  // If not, something is wrong with apt's cache.
  eassert(found);
}

void surrounding_or(pkgCache::DepIterator dep,
		    pkgCache::DepIterator &start,
		    pkgCache::DepIterator &end,
		    pkgCache *cache)
{
  if(cache == NULL)
    cache = *apt_cache_file;

  if(cached_surrounding_or == NULL)
    {
      cached_surrounding_or = new pkgCache::Dependency *[cache->Head().DependsCount];
      for(unsigned long i = 0; i<cache->Head().DependsCount; ++i)
	cached_surrounding_or[i] = 0;
    }

  pkgCache::Dependency *s = cached_surrounding_or[dep->ID];

  // Use the old trick of stuffing values into the low bits of a
  // pointer.
  if(((unsigned long) s & 0x1) != 0)
    {
      pkgCache::Dependency *unmunged
	= (pkgCache::Dependency *) (((unsigned long) s) & ~0x1UL);

      start = pkgCache::DepIterator(*cache, unmunged);
      end = start;

      while(end->CompareOp & pkgCache::Dep::Or)
	++end;

      ++end;
    }
  else
    {
      surrounding_or_internal(dep, start, end);

      cached_surrounding_or[dep->ID] = (pkgCache::Dependency *) ((unsigned long) ((pkgCache::Dependency *) start) | 0x1UL);
    }
}

bool package_suggested(const pkgCache::PkgIterator &pkg)
{
  pkgDepCache::StateCache &state=(*apt_cache_file)[pkg];
  pkgCache::VerIterator candver=state.CandidateVerIter(*apt_cache_file);

  for(rev_dep_iterator d(pkg); !d.end(); ++d)
    if((*d)->Type==pkgCache::Dep::Suggests)
      {
	bool satisfied=false;

	pkgCache::DepIterator start,end;

	surrounding_or(*d, start, end);

	while(start!=end)
	  {
	    if(((*apt_cache_file)[start])&pkgDepCache::DepGInstall)
	      {
		satisfied=true;
		break;
	      }

	    ++start;
	  }

	if(!satisfied)
	  {
	    // Check whether the package doing the depending is going
	    // to be installed.
	    pkgCache::PkgIterator depender=(*d).ParentPkg();
	    pkgDepCache::StateCache &depstate=(*apt_cache_file)[depender];
	    pkgCache::VerIterator depinstver=depstate.InstVerIter(*apt_cache_file);

	    if(depender.CurrentVer().end() &&
	       depstate.Install() &&
	       !depinstver.end() &&
	       !candver.end() &&
	       _system->VS->CheckDep(candver.VerStr(),
				     (*d)->CompareOp, (*d).TargetVer()))
	      {
		if((*d).ParentVer()==depinstver)
		  return true;
	      }
	  }
      }

  return false;
}

bool package_recommended(const pkgCache::PkgIterator &pkg)
{
  pkgDepCache::StateCache &state=(*apt_cache_file)[pkg];
  pkgCache::VerIterator candver=state.CandidateVerIter(*apt_cache_file);

  for(rev_dep_iterator d(pkg); !d.end(); ++d)
    if((*d)->Type==pkgCache::Dep::Recommends)
      {
	bool satisfied=false;

	pkgCache::DepIterator start,end;

	surrounding_or(*d, start, end);

	while(start!=end)
	  {
	    if(((*apt_cache_file)[start])&pkgDepCache::DepGInstall)
	      {
		satisfied=true;
		break;
	      }

	    ++start;
	  }

	if(!satisfied)
	  {
	    // Check whether the package doing the depending is going
	    // to be installed or upgraded.
	    pkgCache::PkgIterator depender=(*d).ParentPkg();
	    pkgDepCache::StateCache &depstate=(*apt_cache_file)[depender];
	    pkgCache::VerIterator depinstver=depstate.InstVerIter(*apt_cache_file);

	    if(depstate.Install() &&
	       !candver.end() &&
	       _system->VS->CheckDep(candver.VerStr(),
				     (*d)->CompareOp, (*d).TargetVer()))
	      {
		if((*d).ParentVer()==depinstver)
		  return true;
	      }
	  }
      }

  return false;
}

bool package_trusted(const pkgCache::VerIterator &ver)
{
  for(pkgCache::VerFileIterator i = ver.FileList(); !i.end(); ++i)
    {
      pkgIndexFile *index;

      if(!apt_source_list->FindIndex(i.File(), index))
	// Corresponds to the currently installed package, which is
	// always "trusted".
	return true;
      else if(index->IsTrusted())
	return true;
    }

  return false;
}

pkgCache::VerIterator install_version(const pkgCache::PkgIterator &pkg,
				      aptitudeDepCache &cache)
{
  if(pkg.VersionList().end())
    return pkgCache::VerIterator(cache);

  pkgDepCache::StateCache &state(cache[pkg]);

  if(state.Delete())
    return pkgCache::VerIterator(cache);
  else if(state.Install())
    return state.InstVerIter(cache);
  else // state.Keep()
    {
      if(pkg->CurrentState == pkgCache::State::NotInstalled ||
	 pkg->CurrentState == pkgCache::State::ConfigFiles)
	return pkgCache::VerIterator(cache);
      else
	return pkg.CurrentVer();
    }
}

pkgCache::DepIterator is_conflicted(const pkgCache::VerIterator &ver,
				    aptitudeDepCache &cache)
{
  if(ver.end())
    return pkgCache::DepIterator();

  pkgCache::PkgIterator parentPkg = ver.ParentPkg();

  // Look for forward conflicts:
  for(pkgCache::DepIterator dep = ver.DependsList(); !dep.end(); ++dep)
    if(dep->Type == pkgCache::Dep::Conflicts ||
       dep->Type == pkgCache::Dep::DpkgBreaks)
    {
      // Look for direct conflicts:
      pkgCache::VerIterator depTargetPkgInstallVer(install_version(dep.TargetPkg(),
								   cache));
	if(dep.TargetPkg() != parentPkg &&
	   !depTargetPkgInstallVer.end() &&
	   _system->VS->CheckDep(depTargetPkgInstallVer.VerStr(),
				 dep->CompareOp,
				 dep.TargetVer()))
	return dep;

      // Look for virtual conflicts:
      for(pkgCache::PrvIterator prv = dep.TargetPkg().ProvidesList();
	  !prv.end(); ++prv)
	{
	  if(prv.OwnerPkg() != parentPkg &&
	     install_version(prv.OwnerPkg(), cache) == prv.OwnerVer() &&
	     _system->VS->CheckDep(prv.ProvideVersion(),
				   dep->CompareOp,
				   dep.TargetVer()))
	    return dep;
	}
    }

  // Look for reverse conflicts:

  // Look for direct reverse conflicts:
  for(pkgCache::DepIterator dep = parentPkg.RevDependsList();
      !dep.end(); ++dep)
    {
      if(dep->Type == pkgCache::Dep::Conflicts ||
	 dep->Type == pkgCache::Dep::DpkgBreaks)
	{
	  if(dep.ParentPkg() != parentPkg &&
	     install_version(dep.ParentPkg(), cache) == dep.ParentVer() &&
	     _system->VS->CheckDep(ver.VerStr(),
				   dep->CompareOp,
				   dep.TargetVer()))
	    return dep;
	}
    }

  // Look for indirect reverse conflicts: that is, things that
  // conflict with a package that this version provides.
  for(pkgCache::PrvIterator prv = ver.ProvidesList();
      !prv.end(); ++prv)
    {
      for(pkgCache::DepIterator dep = prv.ParentPkg().RevDependsList();
	  !dep.end(); ++dep)
	{
	  if(dep->Type == pkgCache::Dep::Conflicts ||
	     dep->Type == pkgCache::Dep::DpkgBreaks)
	    {
	      if(dep.ParentPkg() != parentPkg &&
		 install_version(dep.ParentPkg(), cache) == dep.ParentVer() &&
		 _system->VS->CheckDep(prv.ProvideVersion(),
				       dep->CompareOp,
				       dep.TargetVer()))
		return dep;
	    }
	}
    }

  return pkgCache::DepIterator(cache, 0, (pkgCache::Version *)0);
}


bool can_remove_autoinstalled(const pkgCache::PkgIterator& pkg,
			      aptitudeDepCache& cache,
			      bool keep_recommends_installed,
			      bool keep_suggests_installed)
{
  // if not valid, consider not-OK -- cannot decide if it's safe
  if (pkg.end())
    return false;

  if (is_virtual(pkg))
    {
      // handle virtual packages later
    }
  else if (!pkg.VersionList().end() && pkg.CurrentVer().end())
    {
      // if not virtual and not installed, consider not-OK -- cannot decide if
      // it's safe
      return false;
    }
  else if (!pkg.CurrentVer().end() && !pkg.CurrentVer().Automatic())
    {
      // if installed and not automatic, consider not-OK
      return false;
    }

  bool rdeps_prevent_removal = false;

  // walk all rdeps of the given package, and see if any of them is to be/remain
  // installed (incl. upgrades, downgrades) or kept installed
  for (pkgCache::DepIterator rev_dep = pkg.RevDependsList(); !rev_dep.end(); ++rev_dep)
    {
      // consider only these type of dependencies
      if (! ((rev_dep->Type == pkgCache::Dep::Depends) ||
	     (rev_dep->Type == pkgCache::Dep::PreDepends) ||
	     (rev_dep->Type == pkgCache::Dep::Recommends && keep_recommends_installed) ||
	     (rev_dep->Type == pkgCache::Dep::Suggests   && keep_suggests_installed)))
	continue;

      // consider only to be/remain installed rdeps
      pkgDepCache::StateCache& rev_dep_state = cache[rev_dep.ParentPkg()];
      bool rev_dep_to_remain_installed = is_installed(rev_dep.ParentPkg()) && !rev_dep_state.Delete();
      bool rev_dep_to_be_installed = rev_dep_state.Install();

      if (rev_dep_to_remain_installed || rev_dep_to_be_installed)
	{
	  rdeps_prevent_removal = true;
	  break;
	}
    }

  return !rdeps_prevent_removal;
}

bool is_version_available(const pkgCache::PkgIterator& pkg, const std::string& version)
{
  if (!pkg.end())
    {
      for (pkgCache::VerIterator vi = pkg.VersionList(); !vi.end(); ++vi)
	{
	  if (version == vi.VerStr())
	    {
	      // we have a match, but is it downloadable?  We could check if
	      // it's already downloaded and ready, but apt (1.4) refuses to
	      // install it if the file is available but the version is not in
	      // the current Packages lists
	      //
	      // the extra check would be something like:
	      // (!vi.FileList().end() && !vi.FileList().File().end() && vi.FileList().File().IsOk())
	      if (vi.Downloadable())
		{
		  return true;
		}
	    }
	}
    }

  return false;
}

/** \return \b true if d1 subsumes d2; that is, if one of the
 *  following holds:
 *
 *  (a) d1 and d2 target the same package and are unversioned.
 *
 *  (b) d1 and d2 are unversioned and some version of d2's target
 *      provides the target package of d1.
 *
 *  (c) d1 and d2 target the same package, d1 is unversioned, and d2
 *      is versioned.
 *
 *  (c) d1 and d2 target the same package and are versioned
 *     (with op1 ver1 and op2 ver2 being the operations and versions)
 *     and:
 *
 *       - op1 is >=, op2 is >>, >=, or =, and ver1 <= ver2; or
 *       - op1 is <=, op2 is <<, <=, or =, and ver1 >= ver2; or
 *       - op1 is >>, op2 is >>, and ver1 <= ver2; or
 *       - op1 is >>, op2 is =, and ver1 < ver2; or
 *       - op1 is <<, op2 is <<, and ver1 >= ver2; or
 *       - op1 is <<, op2 is =, and ver1 > ver2; or
 *       - op1 is =, op2 is =, and ver1 = ver2; or
 *       - op1 is !=, op2 is !=, and ver1 = ver2.
 */
static bool subsumes(const pkgCache::DepIterator &d1,
		     const pkgCache::DepIterator &d2)
{
  pkgCache::PkgIterator target1 = const_cast<pkgCache::DepIterator &>(d1).TargetPkg();
  pkgCache::PkgIterator target2 = const_cast<pkgCache::DepIterator &>(d2).TargetPkg();

  if(!d1.TargetVer())
    {
      if(target1 == target2)
	return true;

      if(d2.TargetVer())
	return false;

      for(pkgCache::PrvIterator p = target1.ProvidesList();
	  !p.end(); ++p)
	if(p.OwnerPkg() == target2)
	  return true;

      return false;
    }
  else
    {
      if(target1 != target2)
	return false;

      if(!d2.TargetVer())
	return false;

      // the lower 4 bits are the actual operator (from documentation of the
      // data type)
      static const int comp_mask = 0xf;
      pkgCache::Dep::DepCompareOp t1 = (pkgCache::Dep::DepCompareOp) (d1->CompareOp & comp_mask);
      pkgCache::Dep::DepCompareOp t2 = (pkgCache::Dep::DepCompareOp) (d2->CompareOp & comp_mask);

      int cmpresult = _system->VS->DoCmpVersion(d1.TargetVer(), d1.TargetVer()+strlen(d1.TargetVer()),
						d2.TargetVer(), d2.TargetVer()+strlen(d2.TargetVer()));

      switch(t1)
	{
	case pkgCache::Dep::LessEq:
	  return
	    (t2 == pkgCache::Dep::Less ||
	     t2 == pkgCache::Dep::LessEq ||
	     t2 == pkgCache::Dep::Equals) &&
	    cmpresult >= 0;
	case pkgCache::Dep::GreaterEq:
	  return
	    (t2 == pkgCache::Dep::Greater ||
	     t2 == pkgCache::Dep::GreaterEq ||
	     t2 == pkgCache::Dep::Equals) &&
	    cmpresult <= 0;
	case pkgCache::Dep::Less:
	  return
	    (t2 == pkgCache::Dep::Less && cmpresult >= 0) ||
	    (t2 == pkgCache::Dep::Equals && cmpresult > 0);
	case pkgCache::Dep::Greater:
	  return
	    (t2 == pkgCache::Dep::Greater && cmpresult <= 0) ||
	    (t2 == pkgCache::Dep::Equals && cmpresult < 0);
	case pkgCache::Dep::Equals:
	  return
	    (t2 == pkgCache::Dep::Equals && cmpresult == 0);
	case pkgCache::Dep::NotEquals:
	  return
	    (t2 == pkgCache::Dep::NotEquals && cmpresult == 0);

	  // These shouldn't happen:
	case pkgCache::Dep::NoOp:
	default:
	  abort();
	}
    }
}

/** \return \b true if the OR group of d1 subsumes the OR group of d2:
 *  that is, if every member of the OR group containing d2 has a
 *  subsuming element in the OR group containing d1.
 */
static bool or_group_subsumes(const pkgCache::DepIterator &d1,
			      const pkgCache::DepIterator &d2,
			      pkgCache *cache)
{
  pkgCache::DepIterator start1, end1, start2, end2;

  surrounding_or(d1, start1, end1, cache);
  surrounding_or(d2, start2, end2, cache);

  for(pkgCache::DepIterator i = start1; i != end1; ++i)
    {
      bool found = false;

      for(pkgCache::DepIterator j = start2; j != end2; ++j)
	if(subsumes(i, j))
	  {
	    found = true;
	    break;
	  }

      if(!found)
	return false;
    }

  return true;
}


/** Whether a particular version is security-related
 *
 * Useful e.g. to classify in menus as "Security Upgrade"
 *
 * @return \b true iff the given package version comes from security.d.o or
 * known places
 */
bool is_security(const pkgCache::VerIterator &ver)
{
  static std::regex site_regex { "^security\\.(.+\\.)?debian.org$" };
  std::smatch site_match;

  for (pkgCache::VerFileIterator F = ver.FileList(); !F.end(); ++F)
    {
      pkgCache::PkgFileIterator fileit = F.File();
      if (!fileit.end())
	{
	  string site  = fileit.Site()  ? fileit.Site()  : "";
	  string label = fileit.Label() ? fileit.Label() : "";
	  std::regex_search(site, site_match, site_regex);

	  if (!site_match.empty() && label == "Debian-Security")
	    return true;
	}
    }

  return false;
}

// Interesting deps are:
//
//   - All critical deps
//   - All recommendations that are currently satisfied
//   - All recommendations that are unrelated under subsumption to
//     each recommendation of the current package version.
static bool internal_is_interesting_dep(const pkgCache::DepIterator &d,
					pkgDepCache *cache)
{
  pkgCache::PkgIterator parpkg = const_cast<pkgCache::DepIterator &>(d).ParentPkg();
  pkgCache::VerIterator currver = parpkg.CurrentVer();
  pkgCache::VerIterator parver = const_cast<pkgCache::DepIterator &>(d).ParentVer();

  if(!parver.Downloadable() &&
     (parver != currver || parpkg->CurrentState == pkgCache::State::ConfigFiles))
    return false;
  else if(const_cast<pkgCache::DepIterator &>(d).IsCritical())
    return true;
  else if(d->Type != pkgCache::Dep::Recommends ||
	  !aptcfg->FindB("APT::Install-Recommends", true))
    return false;
  else
    {
      // Soft deps attached to the current version are interesting iff
      // they are currently satisfied.
      if(currver == parver)
	{
	  pkgCache::DepIterator dtmp = d;
	  while(!dtmp.end() && dtmp->CompareOp & pkgCache::Dep::Or)
	    ++dtmp;
	  if((*cache)[dtmp] & pkgDepCache::DepGNow)
	    return true;

	  return false;
	}
      else if(currver.end())
	return true;
      else
	// Check whether the current version of this package has a dep
	// that either subsumes _or is subsumed by_ this
	// recommendation.  (for mathematical "correctness" we'd only
	// check the first direction, but the goal is to not annoy the
	// user unnecessarily; losing a few new recommendations is OK)
	//
	// NB: full correctness without annoyance means actually
	// TRIMMING DOWN the target set of a recommendation by
	// subtracting elements that are in the current version's
	// recommendation list.  Needless to say, I'm ignoring this
	// for now.
	{
	  pkgCache::DepIterator d2 = currver.DependsList();

	  while(!d2.end())
	    {
	      if(d2->Type == pkgCache::Dep::Recommends &&
		 (or_group_subsumes(d2, d, &cache->GetCache()) ||
		  or_group_subsumes(d, d2, &cache->GetCache())))
		{
		  pkgCache::DepIterator dtmp = d;
		  while(!dtmp.end() && dtmp->CompareOp & pkgCache::Dep::Or)
		    ++dtmp;
		  if((*cache)[dtmp] & pkgDepCache::DepGNow)
		    return true;

		  return false;
		}

	      while(!d2.end() && ((d2->CompareOp & pkgCache::Dep::Or) != 0))
		++d2;

	      if(!d2.end())
		++d2;
	    }

	  return true;
	}
    }
}

bool is_interesting_dep(const pkgCache::DepIterator &d,
			pkgDepCache *cache)
{
  if(cached_deps_interesting == NULL)
    {
      cached_deps_interesting = new interesting_state[cache->Head().DependsCount];
      for(unsigned long i = 0; i<cache->Head().DependsCount; ++i)
	cached_deps_interesting[i] = uncached;
    }

  switch(cached_deps_interesting[d->ID])
    {
    case uncached:
      {
	pkgCache::DepIterator start, end;
	surrounding_or(d, start, end, &cache->GetCache());

	bool rval = internal_is_interesting_dep(start, cache);

	cached_deps_interesting[d->ID] = rval ? interesting : uninteresting;
	return rval;
      }
    case interesting:
      return true;
    case uninteresting:
      return false;
    default:
      abort();
    }
}

std::string get_uri(const pkgCache::VerIterator& ver,
		    const pkgRecords* records)
{
  if (ver.end() || ver.FileList().end() || records == nullptr)
    return string{};

  for (auto vfi = ver.FileList(); !vfi.end(); ++vfi)
    {
      // match against source list
      pkgIndexFile* index = nullptr;
      if (apt_source_list->FindIndex(vfi.File(), index) == false)
	continue;

      // get package record
      pkgRecords::Parser& parse = apt_package_records->Lookup(vfi);
      if (_error->PendingError())
	continue;

      string pkg_file = parse.FileName();
      if (pkg_file.empty())
	continue;

      string uri = index->ArchiveURI(pkg_file);

      return uri;
    }

  return string{};
}

std::string get_label(const pkgCache::VerIterator& ver,
		       const pkgRecords* records)
{
  if (ver.end() || ver.FileList().end() || records == nullptr)
    return string{};

  if (ver.Downloadable())
    {
      if (ver.FileList().File() &&
	  ver.FileList().File().Label())
	{
	  return ver.FileList().File().Label();
	}
      else
	{
	  return string{};
	}
    }
  else
    {
      return _("(installed locally)");
    }
}

std::string get_origin(const pkgCache::VerIterator& ver,
		       const pkgRecords* records)
{
  if (ver.end() || ver.FileList().end() || records == nullptr)
    return string{};

  if (ver.Downloadable())
    {
      return ver.RelStr();
    }
  else
    {
      return _("(installed locally)");
    }
}

pkgCache::VerIterator get_candidate_version(const pkgCache::PkgIterator& pkg)
{
  if (apt_cache_file && ! pkg.end())
    {
      return (*apt_cache_file)[pkg].CandidateVerIter(*apt_cache_file);
    }

  // default return
  return pkgCache::VerIterator();
}

std::wstring get_short_description(const pkgCache::VerIterator &ver,
				   pkgRecords *records)
{
  if(ver.end() || ver.FileList().end() || records == NULL)
    return std::wstring();

  pkgCache::DescIterator d = ver.TranslatedDescription();

  if(d.end())
    return std::wstring();

  pkgCache::DescFileIterator df = d.FileList();

  if(df.end())
    return std::wstring();
  else
    // apt "helpfully" cw::util::transcodes the description for us, instead of
    // providing direct access to it.  So I need to assume that the
    // description is encoded in the current locale.
    return cwidget::util::transcode(records->Lookup(df).ShortDesc());
}

std::wstring get_long_description(const pkgCache::VerIterator &ver,
				  pkgRecords *records)
{
  if(ver.end() || ver.FileList().end() || records == NULL)
    return std::wstring();

  pkgCache::DescIterator d = ver.TranslatedDescription();

  if(d.end())
    return std::wstring();

  pkgCache::DescFileIterator df = d.FileList();

  if(df.end())
    return std::wstring();
  else
    return cwidget::util::transcode(records->Lookup(df).LongDesc());
}

const char *multiarch_type(unsigned char type)
{
  switch(type)
    {
    case pkgCache::Version::Foreign:
    case pkgCache::Version::AllForeign:
      return _("foreign");
    case pkgCache::Version::Same:
      return _("same");
    case pkgCache::Version::Allowed:
    case pkgCache::Version::AllAllowed:
      return _("allowed");
    default:
      return "";
    }
}

int get_arch_order(const char *a)
{
  static const std::vector<std::string> archs =
    APT::Configuration::getArchitectures();

  if(strcmp(a, "all") == 0)
    return -1;

  const std::vector<std::string>::const_iterator it =
    std::find(archs.begin(), archs.end(), a);
  return it - archs.begin();
}

int get_deptype_order(const pkgCache::Dep::DepType t)
{
  switch(t)
    {
    case pkgCache::Dep::PreDepends: return 7;
    case pkgCache::Dep::Depends:    return 6;
    case pkgCache::Dep::Recommends: return 5;
    case pkgCache::Dep::Conflicts:  return 4;
    case pkgCache::Dep::DpkgBreaks: return 3;
    case pkgCache::Dep::Suggests:   return 2;
    case pkgCache::Dep::Replaces:   return 1;
    case pkgCache::Dep::Obsoletes:  return 0;
    default: return -1;
    }
}

namespace aptitude
{
  namespace apt
  {
    std::string priority_to_string(const pkgCache::State::VerPriority priority, bool short_form)
    {
      if (short_form)
	{
	  switch (priority)
	    {
	    case pkgCache::State::Important:
	      // TRANSLATORS: Imp = Important
	      return _("Imp");
	    case pkgCache::State::Required:
	      // TRANSLATORS: Req = Required
	      return _("Req");
	    case pkgCache::State::Standard:
	      // TRANSLATORS: Std = Standard
	      return _("Std");
	    case pkgCache::State::Optional:
	      // TRANSLATORS: Opt = Optional
	      return _("Opt");
	    case pkgCache::State::Extra:
	      // TRANSLATORS: Xtr = Extra
	      return _("Xtr");
	    default:
	      return _("ERR");
	    }
	}
      else
	{
	  // this comes translated from apt
	  const char* str = pkgCache::Priority(priority);
	  if (strempty(str))
	    {
	      return _("ERROR");
	    }
	  else
	    {
	      return str;
	    }
	}
    }


    bool is_full_replacement(const pkgCache::DepIterator &dep)
    {
      if(dep.end())
	return false;

      if(dep->Type != pkgCache::Dep::Replaces)
	return false;

      if((dep->CompareOp & ~pkgCache::Dep::Or) != pkgCache::Dep::NoOp)
	return false;

      pkgCache::PkgIterator target = const_cast<pkgCache::DepIterator &>(dep).TargetPkg();

      // Check whether the parent of the dep provides this target and
      // conflicts with it.

      bool found_provides = false;

      for(pkgCache::PrvIterator prv = const_cast<pkgCache::DepIterator &>(dep).ParentVer().ProvidesList();
	  !found_provides && !prv.end(); ++prv)
	{
	  if(prv.ParentPkg() == target)
	    found_provides = true;
	}

      if(!found_provides)
	return false;

      bool found_conflicts = false;

      for(pkgCache::DepIterator possible_conflict = const_cast<pkgCache::DepIterator &>(dep).ParentVer().DependsList();
	  !found_conflicts && !possible_conflict.end(); ++possible_conflict)
	{
	  if(possible_conflict->Type == pkgCache::Dep::Conflicts &&
	     (possible_conflict->CompareOp & ~pkgCache::Dep::Or) == pkgCache::Dep::NoOp &&
	     possible_conflict.TargetPkg() == target)
	    found_conflicts = true;
	}

      if(!found_conflicts)
	return false;


      return true;
    }

    const std::vector<std::string> get_top_sections(const bool cached)
    {
      static std::vector<std::string> top_sections;
      const char *defaults[] =
        {N_("main"),N_("contrib"),N_("non-free"),N_("non-US")};

      if(top_sections.empty() == false)
        {
          if(cached == true)
            return top_sections;
          else
            top_sections.clear();
        }

      top_sections = aptcfg->FindVector(PACKAGE "::Sections::Top-Sections");
      if(top_sections.empty() == true)
        top_sections.assign(defaults, defaults + sizeof(defaults)/sizeof(*defaults));

      return top_sections;
    }

    bool is_native_arch(const pkgCache::VerIterator &ver)
    {
      if(apt_native_arch.empty())
	apt_native_arch = aptcfg->Find("APT::Architecture");
      const char *arch = ver.Arch();
      return apt_native_arch == arch || strcmp(arch, "all") == 0;
    }

    bool clean_cache_dir()
    {
      string archivedir = aptcfg->FindDir("Dir::Cache::archives");

      // lock the archive directory
      FileFd lock;
      if ( ! _config->FindB("Debug::NoLocking", false))
	{
	  lock.Fd(GetLock(archivedir + "lock"));
	  if (_error->PendingError())
	    {
	      _error->Error(_("Unable to lock the download directory"));
	      return false;
	    }
	}

      // do clean
      pkgAcquire fetcher;
      fetcher.Clean(archivedir);
      fetcher.Clean(archivedir+"partial/");

      // return
      if (_error->PendingError())
	{
	  return false;
	}
      else
	{
	  return true;
	}
    }


    static std::unique_ptr<pkgAcquire_fetch_info> internal_fetchinfo {};

    void reset_pkgAcquire_fetch_info()
    {
      internal_fetchinfo.reset();
    }

    void update_pkgAcquire_fetch_info()
    {
      if (!apt_cache_file || !apt_package_records)
	return;

      pkgAcquire fetcher;
      pkgSourceList l;
      if (!l.ReadMainList())
	{
	  _error->Error(_("Couldn't read list of sources"));
	  return;
	}

      pkgDPkgPM pm(*apt_cache_file);
      pm.GetArchives(&fetcher, &l, apt_package_records);
      if (_error->PendingError())
	return;

      pkgAcquire_fetch_info f { fetcher.FetchNeeded(), fetcher.PartialPresent(), fetcher.TotalNeeded() };

      internal_fetchinfo = std::make_unique<pkgAcquire_fetch_info>(f);
    }

    std::unique_ptr<pkgAcquire_fetch_info> get_pkgAcquire_fetch_info()
    {
      // if invalid, update and register for next time
      if (!internal_fetchinfo && apt_cache_file)
	{
	  update_pkgAcquire_fetch_info();
	  (*apt_cache_file)->package_state_changed.connect(sigc::ptr_fun(update_pkgAcquire_fetch_info));
	  cache_closed.connect(sigc::ptr_fun(reset_pkgAcquire_fetch_info));
	}

      if (internal_fetchinfo)
	return std::make_unique<pkgAcquire_fetch_info>(*internal_fetchinfo);
      else
	return {};
    }

  }
}