This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
mirrored from https://salsa.debian.org/apt-team/apt.git
-
Notifications
You must be signed in to change notification settings - Fork 189
/
dpkgpm.cc
2490 lines (2278 loc) · 81.6 KB
/
dpkgpm.cc
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
// -*- mode: cpp; mode: fold -*-
// Description /*{{{*/
/* ######################################################################
DPKG Package Manager - Provide an interface to dpkg
##################################################################### */
/*}}}*/
// Includes /*{{{*/
#include <config.h>
#include <apt-pkg/cachefile.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/debsystem.h>
#include <apt-pkg/depcache.h>
#include <apt-pkg/dpkgpm.h>
#include <apt-pkg/error.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/install-progress.h>
#include <apt-pkg/macros.h>
#include <apt-pkg/packagemanager.h>
#include <apt-pkg/pkgcache.h>
#include <apt-pkg/statechanges.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/version.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <cstring>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>
#include <apti18n.h>
/*}}}*/
extern char **environ;
using namespace std;
APT_PURE static string AptHistoryRequestingUser() /*{{{*/
{
const char* EnvKeys[]{"SUDO_UID", "PKEXEC_UID", "PACKAGEKIT_CALLER_UID"};
for (const auto &Key: EnvKeys)
{
if (getenv(Key) != nullptr)
{
int uid = atoi(getenv(Key));
if (uid > 0) {
struct passwd pwd;
struct passwd *result;
char buf[255];
if (getpwuid_r(uid, &pwd, buf, sizeof(buf), &result) == 0 && result != NULL) {
std::string res;
strprintf(res, "%s (%d)", pwd.pw_name, uid);
return res;
}
}
}
}
return "";
}
/*}}}*/
APT_PURE static unsigned int EnvironmentSize() /*{{{*/
{
unsigned int size = 0;
char **envp = environ;
while (*envp != NULL)
size += strlen (*envp++) + 1;
return size;
}
/*}}}*/
class pkgDPkgPMPrivate /*{{{*/
{
public:
pkgDPkgPMPrivate() : stdin_is_dev_null(false), status_fd_reached_end_of_file(false),
dpkgbuf_pos(0), term_out(NULL), history_out(NULL),
progress(NULL), tt_is_valid(false), master(-1),
slave(NULL), protect_slave_from_dying(-1),
direct_stdin(false)
{
dpkgbuf[0] = '\0';
}
~pkgDPkgPMPrivate()
{
}
bool stdin_is_dev_null;
bool status_fd_reached_end_of_file;
// the buffer we use for the dpkg status-fd reading
char dpkgbuf[1024];
size_t dpkgbuf_pos;
FILE *term_out;
FILE *history_out;
string dpkg_error;
APT::Progress::PackageManager *progress;
// pty stuff
struct termios tt;
bool tt_is_valid;
int master;
char * slave;
int protect_slave_from_dying;
// signals
sigset_t sigmask;
sigset_t original_sigmask;
bool direct_stdin;
};
/*}}}*/
namespace
{
// Maps the dpkg "processing" info to human readable names. Entry 0
// of each array is the key, entry 1 is the value.
const std::pair<const char *, const char *> PackageProcessingOps[] = {
std::make_pair("install", N_("Preparing %s")),
// we don't care for the difference
std::make_pair("upgrade", N_("Preparing %s")),
std::make_pair("configure", N_("Preparing to configure %s")),
std::make_pair("remove", N_("Preparing for removal of %s")),
std::make_pair("purge", N_("Preparing to completely remove %s")),
std::make_pair("disappear", N_("Noting disappearance of %s")),
std::make_pair("trigproc", N_("Running post-installation trigger %s"))
};
const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
// Predicate to test whether an entry in the PackageProcessingOps
// array matches a string.
class MatchProcessingOp
{
const char *target;
public:
explicit MatchProcessingOp(const char *the_target)
: target(the_target)
{
}
bool operator()(const std::pair<const char *, const char *> &pair) const
{
return strcmp(pair.first, target) == 0;
}
};
}
// ionice - helper function to ionice the given PID /*{{{*/
/* there is no C header for ionice yet - just the syscall interface
so we use the binary from util-linux */
static bool ionice(int PID)
{
if (!FileExists("/usr/bin/ionice"))
return false;
pid_t Process = ExecFork();
if (Process == 0)
{
char buf[32];
snprintf(buf, sizeof(buf), "-p%d", PID);
const char *Args[4];
Args[0] = "/usr/bin/ionice";
Args[1] = "-c3";
Args[2] = buf;
Args[3] = 0;
execv(Args[0], (char **)Args);
}
return ExecWait(Process, "ionice");
}
/*}}}*/
// FindNowVersion - Helper to find a Version in "now" state /*{{{*/
// ---------------------------------------------------------------------
/* This is helpful when a package is no longer installed but has residual
* config files
*/
static
pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
{
pkgCache::VerIterator Ver;
for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
for (pkgCache::VerFileIterator Vf = Ver.FileList(); Vf.end() == false; ++Vf)
for (pkgCache::PkgFileIterator F = Vf.File(); F.end() == false; ++F)
{
if (F.Archive() != 0 && strcmp(F.Archive(), "now") == 0)
return Ver;
}
return Ver;
}
/*}}}*/
static pkgCache::VerIterator FindToBeRemovedVersion(pkgCache::PkgIterator const &Pkg)/*{{{*/
{
auto const PV = Pkg.CurrentVer();
if (PV.end() == false)
return PV;
return FindNowVersion(Pkg);
}
/*}}}*/
// DPkgPM::pkgDPkgPM - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* */
pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
: pkgPackageManager(Cache),d(new pkgDPkgPMPrivate()), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
{
}
/*}}}*/
// DPkgPM::pkgDPkgPM - Destructor /*{{{*/
// ---------------------------------------------------------------------
/* */
pkgDPkgPM::~pkgDPkgPM()
{
delete d;
}
/*}}}*/
// DPkgPM::Install - Install a package /*{{{*/
// ---------------------------------------------------------------------
/* Add an install operation to the sequence list */
bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
{
if (File.empty() == true || Pkg.end() == true)
return _error->Error("Internal Error, No file name for %s",Pkg.FullName().c_str());
// If the filename string begins with DPkg::Chroot-Directory, return the
// substr that is within the chroot so dpkg can access it.
string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
if (chrootdir != "/" && File.find(chrootdir) == 0)
{
size_t len = chrootdir.length();
if (chrootdir.at(len - 1) == '/')
len--;
List.push_back(Item(Item::Install,Pkg,File.substr(len)));
}
else
List.push_back(Item(Item::Install,Pkg,File));
return true;
}
/*}}}*/
// DPkgPM::Configure - Configure a package /*{{{*/
// ---------------------------------------------------------------------
/* Add a configure operation to the sequence list */
bool pkgDPkgPM::Configure(PkgIterator Pkg)
{
if (Pkg.end() == true)
return false;
List.push_back(Item(Item::Configure, Pkg));
// Use triggers for config calls if we configure "smart"
// as otherwise Pre-Depends will not be satisfied, see #526774
if (_config->FindB("DPkg::TriggersPending", false) == true)
List.push_back(Item(Item::TriggersPending, PkgIterator()));
return true;
}
/*}}}*/
// DPkgPM::Remove - Remove a package /*{{{*/
// ---------------------------------------------------------------------
/* Add a remove operation to the sequence list */
bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
{
if (Pkg.end() == true)
return false;
if (Purge == true)
List.push_back(Item(Item::Purge,Pkg));
else
List.push_back(Item(Item::Remove,Pkg));
return true;
}
/*}}}*/
// DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
// ---------------------------------------------------------------------
/* This is part of the helper script communication interface, it sends
very complete information down to the other end of the pipe.*/
bool pkgDPkgPM::SendPkgsInfo(FILE * const F, unsigned int const &Version)
{
// This version of APT supports only v3, so don't sent higher versions
if (Version <= 3)
fprintf(F,"VERSION %u\n", Version);
else
fprintf(F,"VERSION 3\n");
/* Write out all of the configuration directives by walking the
configuration tree */
const Configuration::Item *Top = _config->Tree(0);
for (; Top != 0;)
{
if (Top->Value.empty() == false)
{
fprintf(F,"%s=%s\n",
QuoteString(Top->FullTag(),"=\"\n").c_str(),
QuoteString(Top->Value,"\n").c_str());
}
if (Top->Child != 0)
{
Top = Top->Child;
continue;
}
while (Top != 0 && Top->Next == 0)
Top = Top->Parent;
if (Top != 0)
Top = Top->Next;
}
fprintf(F,"\n");
// Write out the package actions in order.
for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
{
if(I->Pkg.end() == true)
continue;
pkgDepCache::StateCache &S = Cache[I->Pkg];
fprintf(F,"%s ",I->Pkg.Name());
// Current version which we are going to replace
pkgCache::VerIterator CurVer = I->Pkg.CurrentVer();
if (CurVer.end() == true && (I->Op == Item::Remove || I->Op == Item::Purge))
CurVer = FindNowVersion(I->Pkg);
if (CurVer.end() == true)
{
if (Version <= 2)
fprintf(F, "- ");
else
fprintf(F, "- - none ");
}
else
{
fprintf(F, "%s ", CurVer.VerStr());
if (Version >= 3)
fprintf(F, "%s %s ", CurVer.Arch(), CurVer.MultiArchType());
}
// Show the compare operator between current and install version
if (S.InstallVer != 0)
{
pkgCache::VerIterator const InstVer = S.InstVerIter(Cache);
int Comp = 2;
if (CurVer.end() == false)
Comp = InstVer.CompareVer(CurVer);
if (Comp < 0)
fprintf(F,"> ");
else if (Comp == 0)
fprintf(F,"= ");
else if (Comp > 0)
fprintf(F,"< ");
fprintf(F, "%s ", InstVer.VerStr());
if (Version >= 3)
fprintf(F, "%s %s ", InstVer.Arch(), InstVer.MultiArchType());
}
else
{
if (Version <= 2)
fprintf(F, "> - ");
else
fprintf(F, "> - - none ");
}
// Show the filename/operation
if (I->Op == Item::Install)
{
// No errors here..
if (I->File[0] != '/')
fprintf(F,"**ERROR**\n");
else
fprintf(F,"%s\n",I->File.c_str());
}
else if (I->Op == Item::Configure)
fprintf(F,"**CONFIGURE**\n");
else if (I->Op == Item::Remove ||
I->Op == Item::Purge)
fprintf(F,"**REMOVE**\n");
if (ferror(F) != 0)
return false;
}
return true;
}
/*}}}*/
// DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
// ---------------------------------------------------------------------
/* This looks for a list of scripts to run from the configuration file
each one is run and is fed on standard input a list of all .deb files
that are due to be installed. */
bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
{
bool result = true;
Configuration::Item const *Opts = _config->Tree(Cnf);
if (Opts == 0 || Opts->Child == 0)
return true;
Opts = Opts->Child;
sighandler_t old_sigpipe = signal(SIGPIPE, SIG_IGN);
sighandler_t old_sigint = signal(SIGINT, SIG_IGN);
sighandler_t old_sigquit = signal(SIGQUIT, SIG_IGN);
unsigned int Count = 1;
for (; Opts != 0; Opts = Opts->Next, Count++)
{
if (Opts->Value.empty() == true)
continue;
if(_config->FindB("Debug::RunScripts", false) == true)
std::clog << "Running external script with list of all .deb file: '"
<< Opts->Value << "'" << std::endl;
// Determine the protocol version
string OptSec = Opts->Value;
string::size_type Pos;
if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
Pos = OptSec.length();
OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
unsigned int Version = _config->FindI(OptSec+"::Version",1);
unsigned int InfoFD = _config->FindI(OptSec + "::InfoFD", STDIN_FILENO);
// Create the pipes
std::set<int> KeepFDs;
MergeKeepFdsFromConfiguration(KeepFDs);
int Pipes[2];
if (pipe(Pipes) != 0) {
result = _error->Errno("pipe","Failed to create IPC pipe to subprocess");
break;
}
if (InfoFD != (unsigned)Pipes[0])
SetCloseExec(Pipes[0],true);
else
KeepFDs.insert(Pipes[0]);
SetCloseExec(Pipes[1],true);
// Purified Fork for running the script
pid_t Process = ExecFork(KeepFDs);
if (Process == 0)
{
// Setup the FDs
dup2(Pipes[0], InfoFD);
SetCloseExec(STDOUT_FILENO,false);
SetCloseExec(STDIN_FILENO,false);
SetCloseExec(STDERR_FILENO,false);
string hookfd;
strprintf(hookfd, "%d", InfoFD);
setenv("APT_HOOK_INFO_FD", hookfd.c_str(), 1);
if (_system != nullptr && _system->IsLocked() == true && stringcasecmp(Cnf, "DPkg::Pre-Install-Pkgs") == 0)
setenv("DPKG_FRONTEND_LOCKED", "true", 1);
debSystem::DpkgChrootDirectory();
const char *Args[4];
Args[0] = "/bin/sh";
Args[1] = "-c";
Args[2] = Opts->Value.c_str();
Args[3] = 0;
execv(Args[0],(char **)Args);
_exit(100);
}
close(Pipes[0]);
FILE *F = fdopen(Pipes[1],"w");
if (F == 0) {
result = _error->Errno("fdopen","Failed to open new FD");
break;
}
// Feed it the filenames.
if (Version <= 1)
{
for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
{
// Only deal with packages to be installed from .deb
if (I->Op != Item::Install)
continue;
// No errors here..
if (I->File[0] != '/')
continue;
/* Feed the filename of each package that is pending install
into the pipe. */
fprintf(F,"%s\n",I->File.c_str());
if (ferror(F) != 0)
break;
}
}
else
SendPkgsInfo(F, Version);
fclose(F);
// Clean up the sub process
if (ExecWait(Process,Opts->Value.c_str()) == false) {
result = _error->Error("Failure running script %s",Opts->Value.c_str());
break;
}
}
signal(SIGINT, old_sigint);
signal(SIGPIPE, old_sigpipe);
signal(SIGQUIT, old_sigquit);
return result;
}
/*}}}*/
// DPkgPM::DoStdin - Read stdin and pass to master pty /*{{{*/
// ---------------------------------------------------------------------
/*
*/
void pkgDPkgPM::DoStdin(int master)
{
unsigned char input_buf[256] = {0,};
ssize_t len = read(STDIN_FILENO, input_buf, sizeof(input_buf));
if (len)
FileFd::Write(master, input_buf, len);
else
d->stdin_is_dev_null = true;
}
/*}}}*/
// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
// ---------------------------------------------------------------------
/*
* read the terminal pty and write log
*/
void pkgDPkgPM::DoTerminalPty(int master)
{
unsigned char term_buf[1024] = {0,0, };
ssize_t len=read(master, term_buf, sizeof(term_buf));
if(len == -1 && errno == EIO)
{
// this happens when the child is about to exit, we
// give it time to actually exit, otherwise we run
// into a race so we sleep for half a second.
struct timespec sleepfor = { 0, 500000000 };
nanosleep(&sleepfor, NULL);
return;
}
if(len <= 0)
return;
FileFd::Write(1, term_buf, len);
if(d->term_out)
fwrite(term_buf, len, sizeof(char), d->term_out);
}
/*}}}*/
// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
{
bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
if (Debug == true)
std::clog << "got from dpkg '" << line << "'" << std::endl;
/* dpkg sends strings like this:
'status: <pkg>: <pkg qstate>'
'status: <pkg>:<arch>: <pkg qstate>'
'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: pkg'
'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: trigger'
*/
// we need to split on ": " (note the appended space) as the ':' is
// part of the pkgname:arch information that dpkg sends
//
// A dpkg error message may contain additional ":" (like
// "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
// so we need to ensure to not split too much
std::vector<std::string> list = StringSplit(line, ": ", 4);
if(list.size() < 3)
{
if (Debug == true)
std::clog << "ignoring line: not enough ':'" << std::endl;
return;
}
// build the (prefix, pkgname, action) tuple, position of this
// is different for "processing" or "status" messages
std::string prefix = APT::String::Strip(list[0]);
std::string pkgname;
std::string action;
// "processing" has the form "processing: action: pkg or trigger"
// with action = ["install", "upgrade", "configure", "remove", "purge",
// "disappear", "trigproc"]
if (prefix == "processing")
{
pkgname = APT::String::Strip(list[2]);
action = APT::String::Strip(list[1]);
}
// "status" has the form: "status: pkg: state"
// with state in ["half-installed", "unpacked", "half-configured",
// "installed", "config-files", "not-installed"]
else if (prefix == "status")
{
pkgname = APT::String::Strip(list[1]);
action = APT::String::Strip(list[2]);
/* handle the special cases first:
errors look like this:
'status: /var/cache/apt/archives/krecipes_0.8.1-0ubuntu1_i386.deb : error : trying to overwrite `/usr/share/doc/kde/HTML/en/krecipes/krectip.png', which is also in package krecipes-data
and conffile-prompt like this
'status:/etc/compiz.conf/compiz.conf : conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
*/
if(action == "error")
{
d->progress->Error(pkgname, PackagesDone, PackagesTotal, list[3]);
++pkgFailures;
WriteApportReport(pkgname.c_str(), list[3].c_str());
return;
}
else if(action == "conffile-prompt")
{
d->progress->ConffilePrompt(pkgname, PackagesDone, PackagesTotal, list[3]);
return;
}
} else {
if (Debug == true)
std::clog << "unknown prefix '" << prefix << "'" << std::endl;
return;
}
// At this point we have a pkgname, but it might not be arch-qualified !
if (pkgname.find(":") == std::string::npos)
{
pkgCache::GrpIterator const Grp = Cache.FindGrp(pkgname);
if (unlikely(Grp.end()== true))
{
if (Debug == true)
std::clog << "unable to figure out which package is dpkg referring to with '" << pkgname << "'! (0)" << std::endl;
return;
}
/* No arch means that dpkg believes there can only be one package
this can refer to so lets see what could be candidates here: */
std::vector<pkgCache::PkgIterator> candset;
for (auto P = Grp.PackageList(); P.end() != true; P = Grp.NextPkg(P))
{
if (PackageOps.find(P.FullName()) != PackageOps.end())
candset.push_back(P);
// packages can disappear without them having any interaction itself
// so we have to consider these as candidates, too
else if (P->CurrentVer != 0 && action == "disappear")
candset.push_back(P);
}
if (unlikely(candset.empty()))
{
if (Debug == true)
std::clog << "unable to figure out which package is dpkg referring to with '" << pkgname << "'! (1)" << std::endl;
return;
}
else if (candset.size() == 1) // we are lucky
pkgname = candset.cbegin()->FullName();
else
{
/* here be dragons^Wassumptions about dpkg:
- an M-A:same version is always arch-qualified
- a package from a foreign arch is (in newer versions) */
size_t installedInstances = 0, wannabeInstances = 0;
for (auto const &P: candset)
{
if (P->CurrentVer != 0)
{
++installedInstances;
if (Cache[P].Delete() == false)
++wannabeInstances;
}
else if (Cache[P].Install())
++wannabeInstances;
}
// the package becomes M-A:same, so we are still talking about current
if (installedInstances == 1 && wannabeInstances >= 2)
{
for (auto const &P: candset)
{
if (P->CurrentVer == 0)
continue;
pkgname = P.FullName();
break;
}
}
// the package was M-A:same, it isn't now, so we can only talk about that
else if (installedInstances >= 2 && wannabeInstances == 1)
{
for (auto const &P: candset)
{
auto const IV = Cache[P].InstVerIter(Cache);
if (IV.end())
continue;
pkgname = P.FullName();
break;
}
}
// that is a crossgrade
else if (installedInstances == 1 && wannabeInstances == 1 && candset.size() == 2)
{
auto const PkgHasCurrentVersion = [](pkgCache::PkgIterator const &P) { return P->CurrentVer != 0; };
auto const P = std::find_if(candset.begin(), candset.end(), PkgHasCurrentVersion);
if (unlikely(P == candset.end()))
{
if (Debug == true)
std::clog << "situation for '" << pkgname << "' looked like a crossgrade, but no current version?!" << std::endl;
return;
}
auto fullname = P->FullName();
if (PackageOps[fullname].size() != PackageOpsDone[fullname])
pkgname = std::move(fullname);
else
{
auto const pkgi = std::find_if_not(candset.begin(), candset.end(), PkgHasCurrentVersion);
if (unlikely(pkgi == candset.end()))
{
if (Debug == true)
std::clog << "situation for '" << pkgname << "' looked like a crossgrade, but all are installed?!" << std::endl;
return;
}
pkgname = pkgi->FullName();
}
}
// we are desperate: so "just" take the native one, but that might change mid-air,
// so we have to ask dpkg what it believes native is at the moment… all the time
else
{
std::vector<std::string> sArgs = debSystem::GetDpkgBaseCommand();
sArgs.push_back("--print-architecture");
int outputFd = -1;
pid_t const dpkgNativeArch = debSystem::ExecDpkg(sArgs, nullptr, &outputFd, true);
if (unlikely(dpkgNativeArch == -1))
{
if (Debug == true)
std::clog << "calling dpkg failed to ask it for its current native architecture to expand '" << pkgname << "'!" << std::endl;
return;
}
FILE *dpkg = fdopen(outputFd, "r");
if(dpkg != NULL)
{
char* buf = NULL;
size_t bufsize = 0;
if (getline(&buf, &bufsize, dpkg) != -1)
pkgname += ':' + bufsize;
free(buf);
fclose(dpkg);
}
ExecWait(dpkgNativeArch, "dpkg --print-architecture", true);
if (pkgname.find(':') != std::string::npos)
{
if (Debug == true)
std::clog << "unable to figure out which package is dpkg referring to with '" << pkgname << "'! (2)" << std::endl;
return;
}
}
}
}
std::string arch = "";
if (pkgname.find(":") != string::npos)
arch = StringSplit(pkgname, ":")[1];
std::string i18n_pkgname = pkgname;
if (arch.size() != 0)
strprintf(i18n_pkgname, "%s (%s)", StringSplit(pkgname, ":")[0].c_str(), arch.c_str());
// 'processing' from dpkg looks like
// 'processing: action: pkg'
if(prefix == "processing")
{
auto const iter = std::find_if(PackageProcessingOpsBegin, PackageProcessingOpsEnd, MatchProcessingOp(action.c_str()));
if(iter == PackageProcessingOpsEnd)
{
if (Debug == true)
std::clog << "ignoring unknown action: " << action << std::endl;
return;
}
std::string msg;
strprintf(msg, _(iter->second), i18n_pkgname.c_str());
d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
// FIXME: this needs a muliarch testcase
// FIXME2: is "pkgname" here reliable with dpkg only sending us
// short pkgnames?
if (action == "disappear")
handleDisappearAction(pkgname);
else if (action == "upgrade")
handleCrossUpgradeAction(pkgname);
return;
}
if (prefix == "status")
{
std::vector<struct DpkgState> &states = PackageOps[pkgname];
if(PackageOpsDone[pkgname] < states.size())
{
char const * next_action = states[PackageOpsDone[pkgname]].state;
if (next_action)
{
/*
if (action == "half-installed" && strcmp("half-configured", next_action) == 0 &&
PackageOpsDone[pkg] + 2 < states.size() && action == states[PackageOpsDone[pkg] + 2].state)
{
if (Debug == true)
std::clog << "(parsed from dpkg) pkg: " << short_pkgname << " action: " << action
<< " pending trigger defused by unpack" << std::endl;
// unpacking a package defuses the pending trigger
PackageOpsDone[pkg] += 2;
PackagesDone += 2;
next_action = states[PackageOpsDone[pkg]].state;
}
*/
if (Debug == true)
std::clog << "(parsed from dpkg) pkg: " << pkgname
<< " action: " << action << " (expected: '" << next_action << "' "
<< PackageOpsDone[pkgname] << " of " << states.size() << ")" << endl;
// check if the package moved to the next dpkg state
if(action == next_action)
{
// only read the translation if there is actually a next action
char const * const translation = _(states[PackageOpsDone[pkgname]].str);
// we moved from one dpkg state to a new one, report that
++PackageOpsDone[pkgname];
++PackagesDone;
std::string msg;
strprintf(msg, translation, i18n_pkgname.c_str());
d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
}
}
}
else if (action == "triggers-pending")
{
if (Debug == true)
std::clog << "(parsed from dpkg) pkg: " << pkgname
<< " action: " << action << " (prefix 2 to "
<< PackageOpsDone[pkgname] << " of " << states.size() << ")" << endl;
states.insert(states.begin(), {"installed", N_("Installed %s")});
states.insert(states.begin(), {"half-configured", N_("Configuring %s")});
PackagesTotal += 2;
}
}
}
/*}}}*/
// DPkgPM::handleDisappearAction /*{{{*/
void pkgDPkgPM::handleDisappearAction(string const &pkgname)
{
pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
if (unlikely(Pkg.end() == true))
return;
// a disappeared package has no further actions
auto const ROps = PackageOps[Pkg.FullName()].size();
auto && ROpsDone = PackageOpsDone[Pkg.FullName()];
PackagesDone += ROps - ROpsDone;
ROpsDone = ROps;
// record the package name for display and stuff later
disappearedPkgs.insert(Pkg.FullName(true));
// the disappeared package was auto-installed - nothing to do
if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
return;
pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
if (unlikely(PkgVer.end() == true))
return;
/* search in the list of dependencies for (Pre)Depends,
check if this dependency has a Replaces on our package
and if so transfer the manual installed flag to it */
for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
{
if (Dep->Type != pkgCache::Dep::Depends &&
Dep->Type != pkgCache::Dep::PreDepends)
continue;
pkgCache::PkgIterator Tar = Dep.TargetPkg();
if (unlikely(Tar.end() == true))
continue;
// the package is already marked as manual
if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
continue;
pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
if (TarVer.end() == true)
continue;
for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
{
if (Rep->Type != pkgCache::Dep::Replaces)
continue;
if (Pkg != Rep.TargetPkg())
continue;
// okay, they are strongly connected - transfer manual-bit
if (Debug == true)
std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
Cache[Tar].Flags &= ~Flag::Auto;
break;
}
}
}
/*}}}*/
void pkgDPkgPM::handleCrossUpgradeAction(string const &pkgname) /*{{{*/
{
// in a crossgrade what looked like a remove first is really an unpack over it
auto const Pkg = Cache.FindPkg(pkgname);
if (likely(Pkg.end() == false) && Cache[Pkg].Delete())
{
auto const Grp = Pkg.Group();
if (likely(Grp.end() == false))
{
for (auto P = Grp.PackageList(); P.end() != true; P = Grp.NextPkg(P))
if(Cache[P].Install())
{
auto && Ops = PackageOps[P.FullName()];
auto const unpackOp = std::find_if(Ops.cbegin(), Ops.cend(), [](DpkgState const &s) { return strcmp(s.state, "unpacked") == 0; });
if (unpackOp != Ops.cend())
{
// skip ahead in the crossgraded packages
auto const skipped = std::distance(Ops.cbegin(), unpackOp);
PackagesDone += skipped;
PackageOpsDone[P.FullName()] += skipped;
// finish the crossremoved package
auto const ROps = PackageOps[Pkg.FullName()].size();
auto && ROpsDone = PackageOpsDone[Pkg.FullName()];
PackagesDone += ROps - ROpsDone;
ROpsDone = ROps;
break;
}
}
}
}
}
/*}}}*/
// DPkgPM::DoDpkgStatusFd /*{{{*/
void pkgDPkgPM::DoDpkgStatusFd(int statusfd)
{
auto const remainingBuffer = (sizeof(d->dpkgbuf) / sizeof(d->dpkgbuf[0])) - d->dpkgbuf_pos;
if (likely(remainingBuffer > 0) && d->status_fd_reached_end_of_file == false)
{
auto const len = read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], remainingBuffer);
if (len < 0)
return;
else if (len == 0 && d->dpkgbuf_pos == 0)
{
d->status_fd_reached_end_of_file = true;
return;
}
d->dpkgbuf_pos += (len / sizeof(d->dpkgbuf[0]));
}
// process line by line from the buffer
char *p = d->dpkgbuf, *q = nullptr;
while((q=(char*)memchr(p, '\n', (d->dpkgbuf + d->dpkgbuf_pos) - p)) != nullptr)
{
*q = '\0';
ProcessDpkgStatusLine(p);
p = q + 1; // continue with next line
}
// check if we stripped the buffer clean
if (p > (d->dpkgbuf + d->dpkgbuf_pos))
{
d->dpkgbuf_pos = 0;
return;
}
// otherwise move the unprocessed tail to the start and update pos
memmove(d->dpkgbuf, p, (p - d->dpkgbuf));
d->dpkgbuf_pos = (d->dpkgbuf + d->dpkgbuf_pos) - p;
}
/*}}}*/
// DPkgPM::WriteHistoryTag /*{{{*/
void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
{
size_t const length = value.length();
if (length == 0)