forked from community-ssu/hildon-application-manager
/
apt-worker.cc
6872 lines (5674 loc) · 167 KB
/
apt-worker.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
/*
* This file is part of the hildon-application-manager.
*
* Parts of this file are derived from apt. Apt is copyright 1997,
* 1998, 1999 Jason Gunthorpe and others.
*
* Copyright (C) 2005, 2006, 2007, 2008 Nokia Corporation. All Rights reserved.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/* This is the process that runs as root and does all the work.
It is started from a separate program (as opposed to being forked
directly from the GUI process) since that allows us to use sudo for
starting it.
This process communicates with the GUI process via some named pipes
that are created by that process. You can't really use it from the
command line.
It will output stuff to stdin and stderr, which the GUI process is
supposed to catch and put into its log.
The program tries hard not to exit prematurely. Once the
connection between the GUI process and this process has been
established, the apt-worker is supposed to stick around until that
connection is broken, even if it has to fail every request send to
it. This allows the user to try and fix the system after something
went wrong, although the options are limited, of course. The best
example is a corrupted /etc/apt/sources.list: even tho you can't do
anything related to packages, you still need the apt-worker to
correct /etc/apt/sources.list itself in the UI.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <stdarg.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
#include <ftw.h>
#include <fstream>
#include <apt-pkg/init.h>
#include <apt-pkg/error.h>
#include <apt-pkg/tagfile.h>
#include <apt-pkg/pkgcache.h>
#include <apt-pkg/pkgcachegen.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/acquire.h>
#include <apt-pkg/acquire-item.h>
#include <apt-pkg/cachefile.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/packagemanager.h>
#include <apt-pkg/deblistparser.h>
#include <apt-pkg/debversion.h>
#include <apt-pkg/dpkgpm.h>
#include <apt-pkg/debsystem.h>
#include <apt-pkg/orderlist.h>
#include <apt-pkg/algorithms.h>
#include <apt-pkg/metaindex.h>
#include <apt-pkg/debmetaindex.h>
#include <apt-pkg/policy.h>
#include <apt-pkg/hashes.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/progress.h>
#include <apt-pkg/install-progress.h>
#include <glib.h>
#include "apt-worker-proto.h"
#include "confutils.h"
#include "update-notifier-conf.h"
using namespace std;
static void save_operation_record (const char *package,
const char *download_root);
static void erase_operation_record ();
static xexp *read_operation_record ();
/* Table of contents.
COMPILE-TIME CONFIGURATION
RUN-TIME CONFIGURATION
GENERAL UTILITIES
COMMUNICATING WITH THE FRONTEND
STARTUP AND COMMAND DISPATCHER
CACHE HANDLING
*/
/** COMPILE-TIME CONFIGURATION
*/
/* Defining this to non-zero will also recognize packages in the
"maemo" section as user packages. There are still packages
floating around that follow this old rule.
*/
#define ENABLE_OLD_MAEMO_SECTION_TEST 1
/* Requests up to this size are put into a stack allocated buffer.
*/
#define FIXED_REQUEST_BUF_SIZE 4096
/* The location where we keep our lock.
*/
#define APT_WORKER_LOCK "/var/lib/hildon-application-manager/apt-worker-lock"
/* Temporary catalogues and temporary sources.list */
#define TEMP_CATALOGUE_CONF "/var/lib/hildon-application-manager/catalogues.temp"
#define TEMP_APT_SOURCE_LIST "/etc/apt/sources.list.d/hildon-application-manager-temp.list"
/* APT CACHE ARCHIVES DIRECTORIES */
#define DEFAULT_DIR_CACHE_ARCHIVES "archives/"
#define ALT_DIR_CACHE_ARCHIVES ".apt-archive-cache/"
/* Files related to the 'check for updates' process */
#define FAILED_CATALOGUES_FILE "/var/lib/hildon-application-manager/failed-catalogues"
/* Domain names associated with "OS" and "Nokia" updates */
#define OS_UPDATES_DOMAIN_NAME "nokia-system"
#define NOKIA_UPDATES_DOMAIN_NAME "nokia-certified"
/* Where we keep a journal of the current operation
*/
#define CURRENT_OPERATION_FILE "/var/lib/hildon-application-manager/current-operation"
/* File to store the result of rescue mode execution
*/
#define RESCUE_RESULT_FILE "/var/lib/hildon-application-manager/rescue-result"
/* You know what this means.
*/
/*#define DEBUG*/
/*#define DEBUG_COMMANDS*/
#ifdef DEBUG
#define DBG log_stderr
#else
#define DBG(...)
#endif
/** RUN-TIME CONFIGURATION
*/
/* Setting this to true will break the lock of the dpkg status
database if necessary.
*/
bool flag_break_locks = false;
/* Setting this to true will not ignore package versions from a wrong
domain.
*/
bool flag_allow_wrong_domains = false;
/* Setting this to true will use the normal apt-get algorithms for
installing/removing packages instead of our home-grown ones.
*/
bool flag_use_apt_algorithms = false;
/* Setting this to false will not use MMC to save the packages when
downloading them.
*/
bool flag_download_packages_to_mmc = false;
/* List of packages found with the 'system-update' flag (SSU packages)
*/
GArray *ssu_packages = NULL;
/* Flag to tell whether the ssu_packages GArray needs to be refreshed
*/
gboolean ssu_packages_needs_refresh = true;
/** GENERAL UTILITIES
*/
void
log_stderr (const char *fmt, ...)
{
va_list args;
va_start (args, fmt);
fprintf (stderr, "apt-worker: ");
vfprintf (stderr, fmt, args);
va_end (args);
fprintf (stderr, "\n");
}
/** APT WORKER MULTI STATE MANAGEMENT
*/
/* Inside this process, domains are identified with small integers.
*/
typedef signed char domain_t;
struct domain_info {
const char *name;
xexp *conf;
int trust_level;
bool is_certified;
};
xexp *domain_conf = NULL;
domain_info *domains = NULL;
int domains_number = 0;
time_t domains_last_modified = -1;
#define DOMAIN_INVALID -1
#define DOMAIN_UNSIGNED 0
#define DOMAIN_SIGNED 1
#define DOMAIN_DEFAULT DOMAIN_UNSIGNED
static time_t
file_last_modified (const char *file_name)
{
struct stat buf;
if (stat (file_name, &buf) == -1)
{
perror ("error retriving file info");
return -1;
}
return buf.st_mtime;
}
static void
read_domain_conf ()
{
delete[] domains;
xexp_free (domain_conf);
domain_conf = read_domains ();
int n_domains = 2;
if (domain_conf)
n_domains += xexp_length (domain_conf);
domains = new domain_info[n_domains];
/* Setup the two implicit domains.
*/
domains[0].name = "unsigned";
domains[0].conf = NULL;
domains[0].trust_level = 0;
domains[0].is_certified = false;
domains[1].name = "signed";
domains[1].conf = NULL;
domains[1].trust_level = 1;
domains[1].is_certified = false;
int i = 2;
if (domain_conf)
{
for (xexp *d = xexp_first (domain_conf); d; d = xexp_rest (d))
{
if (!xexp_is (d, "domain"))
continue;
domains[i].name = xexp_aref_text (d, "name");
if (domains[i].name == NULL)
continue;
domains[i].trust_level = xexp_aref_int (d, "trust-level", 2);
domains[i].is_certified = xexp_aref_bool (d, "certified");
domains[i].conf = d;
i += 1;
}
}
/* Update domains number and last modified timestamp */
domains_number = i;
domains_last_modified = file_last_modified (PACKAGE_DOMAINS);
}
static domain_t
find_domain_by_tag (const char *tag, const char *val)
{
for (int i = 0; i < domains_number; i++)
{
if (domains[i].conf == NULL)
continue;
for (xexp *x = xexp_aref (domains[i].conf, tag);
x;
x = xexp_aref_rest (x, tag))
{
if (xexp_is_text (x) && g_str_has_suffix (xexp_text (x), val))
return i;
}
}
return DOMAIN_SIGNED;
}
static domain_t
find_domain_by_key (const char *key)
{
return find_domain_by_tag ("key", key);
}
static domain_t
find_domain_by_uri (const char *uri)
{
return find_domain_by_tag ("uri", uri);
}
class myCacheFile;
/* This class implements a global static cache managing for
* apt-worker. */
class AptWorkerCache
{
public:
AptWorkerCache ();
static void Initialize ();
static AptWorkerCache * GetCurrent ();
bool init_cache_after_request;
myCacheFile *cache;
pkgDepCache::ActionGroup *action_group;
static AptWorkerCache *current;
static bool global_initialized;
};
AptWorkerCache *AptWorkerCache::current = 0;
bool AptWorkerCache::global_initialized = false;
AptWorkerCache::AptWorkerCache ()
: init_cache_after_request (false), cache (0)
{
}
AptWorkerCache *
AptWorkerCache::GetCurrent (void)
{
return current;
}
/* Initialization of apt worker cache. It initializes the
* APT subsystem, and then gets the current instance. */
void
AptWorkerCache::Initialize (void)
{
if (!global_initialized)
{
if (pkgInitConfig (*_config) == false ||
pkgInitSystem (*_config, _system) == false)
{
_error->DumpErrors ();
return;
}
_config->Set ("DPkg::Options::", "--force-confold");
_config->Set ("Dir::Log", "var/log");
_config->Set ("Dir::Log::Terminal", "");
global_initialized = true;
}
current = new AptWorkerCache;
}
/* This struct describes some status flags for specific packages.
* myCacheFile includes an array of these, with an entry per
* package.
*/
struct extra_info_struct
{
bool autoinst : 1;
bool related : 1;
bool soft : 1;
domain_t cur_domain, new_domain;
};
class myPolicy : public pkgPolicy {
protected:
myCacheFile *my_cache_file;
int *pf_domain;
public:
myPolicy (pkgCache *Owner, myCacheFile *cache_file)
: pkgPolicy (Owner), my_cache_file (cache_file)
{
pf_domain = new int[Owner->Head().PackageFileCount];
}
void InitDomains ();
virtual pkgCache::VerIterator GetCandidateVer(pkgCache::PkgIterator Pkg);
};
class myCacheFile : public pkgCacheFile {
public:
bool Open (OpProgress &Progress, bool WithLock = true);
void load_extra_info ();
void save_extra_info ();
extra_info_struct *extra_info;
myCacheFile ()
{
extra_info = NULL;
}
~myCacheFile ()
{
delete[] extra_info;
}
};
static void set_sources_for_get_domain (pkgSourceList *sources);
static int get_domain (pkgIndexFile*);
void
myPolicy::InitDomains ()
{
for (pkgCache::PkgFileIterator I = Cache->FileBegin();
I != Cache->FileEnd(); I++)
pf_domain[I->ID] = DOMAIN_UNSIGNED;
pkgSourceList List;
if (!List.ReadMainList ())
{
_error->DumpErrors();
return;
}
set_sources_for_get_domain (&List);
for (pkgCache::PkgFileIterator I = Cache->FileBegin();
I != Cache->FileEnd(); I++)
{
// Locate the associated index files so we can find its domain
pkgIndexFile *Indx;
if (List.FindIndex(I,Indx) || _system->FindIndex(I,Indx))
{
pf_domain[I->ID] = get_domain (Indx);
DBG ("%s: %s", Indx->Describe(true).c_str(),
domains[pf_domain[I->ID]].name);
}
}
set_sources_for_get_domain (NULL);
}
static bool domain_dominates_or_is_equal (int a, int b);
pkgCache::VerIterator
myPolicy::GetCandidateVer (pkgCache::PkgIterator Pkg)
{
// Look for a package pin and evaluate it.
pkgCache::VerIterator Pref = GetCandidateVer(Pkg);
signed Max = GetPriority(Pref);
/* Falling through to the default version.. Setting Max to zero
effectively excludes everything <= 0 which are the non-automatic
priorities.. The status file is given a prio of 100 which will exclude
not-automatic sources, except in a single shot not-installed mode.
The second pseduo-status file is at prio 1000, above which will permit
the user to force-downgrade things.
The user pin is subject to the same priority rules as default
selections. Thus there are two ways to create a pin - a pin that
tracks the default when the default is taken away, and a permanent
pin that stays at that setting.
*/
for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false; Ver++)
{
for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false;
VF++)
{
/* If this is the status file, and the current version is not the
version in the status file (ie it is not installed, or somesuch)
then it is not a candidate for installation, ever. This weeds
out bogus entries that may be due to config-file states, or
other. */
if ((VF.File()->Flags & pkgCache::Flag::NotSource) == pkgCache::Flag::NotSource &&
Pkg.CurrentVer() != Ver)
continue;
/* If requested, skip versions from the wrong domain, but
only for sources.
*/
if (!flag_allow_wrong_domains
&& ((VF.File()->Flags & pkgCache::Flag::NotSource)
!= pkgCache::Flag::NotSource))
{
if (!domain_dominates_or_is_equal
(pf_domain[VF.File()->ID],
my_cache_file->extra_info[Pkg->ID].cur_domain))
{
log_stderr ("Ignoring version from wrong domain: %s %s",
Pkg.Name(), Ver.VerStr());
log_stderr (" %s", VF.File().FileName());
continue;
}
}
signed Prio = PFPriority[VF.File()->ID];
if (Prio > Max)
{
Pref = Ver;
Max = Prio;
}
}
if (Pkg.CurrentVer() == Ver && Max < 1000)
{
/* Elevate our current selection (or the status file itself)
to the Pseudo-status priority. */
if (Pref.end() == true)
Pref = Ver;
Max = 1000;
// Fast path optimize.
if (StatusOverride == false)
break;
}
}
return Pref;
}
bool
myCacheFile::Open (OpProgress &Progress, bool WithLock)
{
if (BuildCaches(&Progress,WithLock) == false)
return false;
// The policy engine
myPolicy *pol = new myPolicy (Cache, this);
Policy = pol;
if (_error->PendingError() == true)
return false;
if (ReadPinFile(*Policy) == false)
return false;
pol->InitDomains ();
load_extra_info ();
// Create the dependency cache
DCache = new pkgDepCache(Cache,Policy);
if (_error->PendingError() == true)
return false;
DCache->Init(&Progress);
Progress.Done();
if (_error->PendingError() == true)
return false;
return true;
}
/* Save the 'extra_info' of the cache. We first make a copy of the
Auto flags in our own extra_info storage so that CACHE_RESET
will reset the Auto flags to the state last saved with this
function.
*/
void
myCacheFile::save_extra_info ()
{
if (mkdir ("/var/lib/hildon-application-manager", 0777) < 0
&& errno != EEXIST)
{
log_stderr ("/var/lib/hildon-application-manager: %m");
return;
}
FILE *f = fopen ("/var/lib/hildon-application-manager/autoinst", "w");
if (f)
{
pkgDepCache &cache = *DCache;
for (pkgCache::PkgIterator pkg = cache.PkgBegin(); !pkg.end (); pkg++)
{
if (cache[pkg].Flags & pkgCache::Flag::Auto)
{
extra_info[pkg->ID].autoinst = true;
fprintf (f, "%s\n", pkg.Name ());
}
else
extra_info[pkg->ID].autoinst = false;
}
fflush (f);
fsync (fileno (f));
fclose (f);
}
for (domain_t i = 0; i < domains_number; i++)
{
char *name =
g_strdup_printf ("/var/lib/hildon-application-manager/domain.%s",
domains[i].name);
FILE *f = fopen (name, "w");
if (f)
{
pkgDepCache &cache = *DCache;
for (pkgCache::PkgIterator pkg = cache.PkgBegin();
!pkg.end (); pkg++)
{
if (extra_info[pkg->ID].cur_domain == i)
fprintf (f, "%s\n", pkg.Name ());
}
fflush (f);
fsync (fileno (f));
fclose (f);
}
}
}
/* Load the 'extra_info'. You need to call CACHE_RESET to
transfer the auto flag into the actual cache. */
void
myCacheFile::load_extra_info ()
{
pkgCache &cache = *Cache;
int package_count = cache.Head().PackageCount;
extra_info = new extra_info_struct[package_count];
for (int i = 0; i < package_count; i++)
{
extra_info[i].autoinst = false;
extra_info[i].cur_domain = DOMAIN_DEFAULT;
}
FILE *f = fopen ("/var/lib/hildon-application-manager/autoinst", "r");
if (f)
{
char *line = NULL;
size_t len = 0;
ssize_t n;
while ((n = getline (&line, &len, f)) != -1)
{
if (n > 0 && line[n-1] == '\n')
line[n-1] = '\0';
pkgCache::PkgIterator pkg = cache.FindPkg (line);
if (!pkg.end ())
{
DBG ("auto: %s", pkg.Name ());
extra_info[pkg->ID].autoinst = true;
}
}
free (line);
fclose (f);
}
for (domain_t i = 0; i < domains_number; i++)
{
char *name =
g_strdup_printf ("/var/lib/hildon-application-manager/domain.%s",
domains[i].name);
FILE *f = fopen (name, "r");
if (f)
{
char *line = NULL;
size_t len = 0;
ssize_t n;
while ((n = getline (&line, &len, f)) != -1)
{
if (n > 0 && line[n-1] == '\n')
line[n-1] = '\0';
pkgCache::PkgIterator pkg = cache.FindPkg (line);
if (!pkg.end ())
{
// DBG ("%s: %s (%d)", domains[i].name, pkg.Name (), pkg->ID);
extra_info[pkg->ID].cur_domain = i;
}
}
free (line);
fclose (f);
}
g_free (name);
}
}
/* ALLOC_BUF and FREE_BUF can be used to manage a temporary buffer of
arbitrary size without having to allocate memory from the heap when
the buffer is small.
The way to use them is to allocate a buffer of 'normal' but fixed
size statically or on the stack and the use ALLOC_BUF when the
actual size of the needed buffer is known. If the actual size is
small enough, ALLOC_BUF will use the fixed size buffer, otherwise
it will allocate a new one. FREE_BUF will free that buffer.
*/
/* Return a pointer to LEN bytes of free storage. When LEN is less
than or equal to FIXED_BUF_LEN return FIXED_BUF, otherwise a newly
allocated block of memory is returned. ALLOC_BUF never return
NULL.
*/
char *
alloc_buf (int len, char *fixed_buf, int fixed_buf_len)
{
if (len <= fixed_buf_len)
return fixed_buf;
else
return new char[len];
}
/* Free the block of memory pointed to by BUF if it is different from
FIXED_BUF.
*/
void
free_buf (char *buf, char *fixed_buf)
{
if (buf != fixed_buf)
delete[] buf;
}
/* Open FILENAME with FLAGS, or die.
*/
static int
must_open (char *filename, int flags)
{
int fd = open (filename, flags);
if (fd < 0)
{
perror (filename);
exit (1);
}
return fd;
}
static void
must_set_flags (int fd, int flags)
{
if (fcntl (fd, F_SETFL, flags) < 0)
{
perror ("apt-worker fcntl");
exit (1);
}
}
static void
block_for_read (int fd)
{
fd_set set;
FD_ZERO (&set);
FD_SET (fd, &set);
if (select (fd+1, &set, NULL, NULL, NULL) < 0)
{
perror ("apt-worker select");
exit (1);
}
}
static int
read_byte (int fd)
{
unsigned char byte;
if (read (fd, &byte, 1) == 1)
return byte;
return -1;
}
/* DRAIN_FD reads all bytes from FD that are available.
*/
static void
drain_fd (int fd)
{
while (read_byte (fd) >= 0)
;
}
/* Get a lock as with GetLock from libapt-pkg, breaking it if needed
and allowed by flag_break_locks.
We do this so that the users can not lock themselves out. We break
locks instead of not locking since noisily breaking a lock is
better than silently corrupting stuff.
*/
int
ForceLock (string File, bool Errors = true)
{
int lock_fd = GetLock (File, false);
if (lock_fd >= 0)
return lock_fd;
if (flag_break_locks)
{
int res = unlink (File.c_str ());
if (res < 0 && errno != ENOENT)
log_stderr ("Can't remove %s: %m", File.c_str ());
else if (res == 0)
log_stderr ("Forcing %s", File.c_str ());
}
return GetLock (File, Errors);
}
/** COMMUNICATING WITH THE FRONTEND.
The communication with the frontend happens over four
unidirectional fifos: requests are read from INPUT_FD and responses
are sent back via OUTPUT_FD. No new request is read until the
response to the current one has been completely sent.
The data read from INPUT_FD must follow the request format
specified in <apt-worker-proto.h>. The data written to OUTPUT_FD
follows the response format specified there.
The CANCEL_FD is polled periodically and when something is
available to be read, the current operation is aborted. There is
currently no meaning defined for the actual bytes that are sent,
the mere arrival of a byte triggers the abort.
When using the libapt-pkg PackageManager, it is configured in such
a way that it sends it "pmstatus:" message lines to STATUS_FD.
Other asynchronous status reports are sent as spontaneous
APTCMD_STATUS responses via OUTPUT_FD. 'Spontaneous' should mean
that no request is required to receive APTCMD_STATUS responses. In
fact, APTCMD_STATUS requests are treated as an error by the
apt-worker.
Logging and debug output, and output from dpkg and the maintainer
scripts appears normally on stdout and stderr of the apt-worker
process.
*/
int input_fd, output_fd, status_fd, cancel_fd;
/* MUST_READ and MUST_WRITE read and write blocks of raw bytes from
INPUT_FD and to OUTPUT_FD. If they return, they have succeeded and
read or written the whole block.
*/
void
must_read (void *buf, size_t n)
{
int r;
while (n > 0)
{
r = read (input_fd, buf, n);
if (r < 0)
{
perror ("apt-worker read");
exit (1);
}
else if (r == 0)
{
DBG ("exiting");
exit (0);
}
n -= r;
buf = ((char *)buf) + r;
}
}
static void
must_write (void *buf, ssize_t n)
{
if (n > 0 && write (output_fd, buf, n) != n)
{
perror ("apt-worker write");
exit (1);
}
}
/* This function sends a response on OUTPUT_FD with the given CMD and
SEQ. It either succeeds or does not return.
*/
void
send_response_raw (int cmd, int seq, void *response, size_t len)
{
apt_response_header res = { cmd, seq, len };
must_write (&res, sizeof (res));
must_write (response, len);
}
/* Fabricate and send a APTCMD_STATUS response. Parameters OP,
ALREADY, and TOTAL are as specified in apt-worker-proto.h.
A status response is only sent when there is enough change since
the last time. The following counts as 'enough': ALREADY has
decreased, it has increased by more than MIN_CHANGE, it is equal to
-1, LAST_TOTAL has changed, or OP has changed.
*/
void
send_status (int op, int already, int total, int min_change)
{
static apt_proto_encoder status_response;
static int last_op;
static int last_already;
static int last_total;
if (already == -1
|| already < last_already
|| already >= last_already + min_change
|| total != last_total
|| op != last_op)
{
last_already = already;
last_total = total;
last_op = op;
status_response.reset ();
status_response.encode_int (op);
status_response.encode_int (already);
status_response.encode_int (total);
send_response_raw (APTCMD_STATUS, -1,
status_response.get_buf (),
status_response.get_len ());
}
}
/** STARTUP AND COMMAND DISPATCHER.
*/
/* Since the apt-worker only works on a single command at a time, we
use two global encoder and decoder engines that manage the
parameters of the request and the result values of the response.
Handlers of specific commands will read the parameters from REQUEST
and put the results into RESPONSE. The command dispatcher will
prepare REQUEST before calling the command handler and ship out
RESPONSE after it returned.
*/
apt_proto_decoder request;
apt_proto_encoder response;
void cmd_get_package_list ();
void cmd_get_package_info ();
void cmd_get_package_details ();
int cmd_check_updates (bool with_status = true);
void cmd_get_catalogues ();
void cmd_set_catalogues ();
void cmd_add_temp_catalogues ();
void cmd_rm_temp_catalogues ();
void cmd_get_free_space ();
void cmd_install_check ();
void cmd_download_package ();
void cmd_install_package ();
void cmd_remove_check ();
void cmd_remove_package ();
void cmd_clean ();
void cmd_get_file_details ();
void cmd_install_file ();
void cmd_save_backup_data ();
void cmd_get_system_update_packages ();