]>
Commit | Line | Data |
---|---|---|
578bfd0a AL |
1 | // -*- mode: cpp; mode: fold -*- |
2 | // Description /*{{{*/ | |
578bfd0a AL |
3 | /* ###################################################################### |
4 | ||
5 | File Utilities | |
6 | ||
7 | CopyFile - Buffered copy of a single file | |
8 | GetLock - dpkg compatible lock file manipulation (fcntl) | |
9 | ||
614adaa0 MV |
10 | Most of this source is placed in the Public Domain, do with it what |
11 | you will | |
7da2b375 | 12 | It was originally written by Jason Gunthorpe <jgg@debian.org>. |
a3a03f5d | 13 | FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com> |
578bfd0a | 14 | |
614adaa0 MV |
15 | The exception is RunScripts() it is under the GPLv2 |
16 | ||
578bfd0a AL |
17 | ##################################################################### */ |
18 | /*}}}*/ | |
19 | // Include Files /*{{{*/ | |
ea542140 DK |
20 | #include <config.h> |
21 | ||
094a497d | 22 | #include <apt-pkg/fileutl.h> |
1cd1c398 | 23 | #include <apt-pkg/strutl.h> |
094a497d | 24 | #include <apt-pkg/error.h> |
b2e465d6 | 25 | #include <apt-pkg/sptr.h> |
468720c5 | 26 | #include <apt-pkg/aptconfiguration.h> |
75ef8f14 | 27 | #include <apt-pkg/configuration.h> |
453b82a3 | 28 | #include <apt-pkg/macros.h> |
b2e465d6 | 29 | |
453b82a3 DK |
30 | #include <ctype.h> |
31 | #include <stdarg.h> | |
32 | #include <stddef.h> | |
33 | #include <sys/select.h> | |
34 | #include <time.h> | |
35 | #include <string> | |
36 | #include <vector> | |
152ab79e | 37 | #include <cstdlib> |
4f333a8b | 38 | #include <cstring> |
3010fb0e | 39 | #include <cstdio> |
4d055c05 | 40 | #include <iostream> |
578bfd0a | 41 | #include <unistd.h> |
2c206aa4 | 42 | #include <fcntl.h> |
578bfd0a | 43 | #include <sys/stat.h> |
cc2313b7 | 44 | #include <sys/time.h> |
1ae93c94 | 45 | #include <sys/wait.h> |
46e39c8e | 46 | #include <dirent.h> |
54676e1a | 47 | #include <signal.h> |
65a1e968 | 48 | #include <errno.h> |
8d01b9d6 | 49 | #include <glob.h> |
fc1a78d8 | 50 | #include <pwd.h> |
3927c6da | 51 | #include <grp.h> |
8d01b9d6 | 52 | |
75ef8f14 | 53 | #include <set> |
46e39c8e | 54 | #include <algorithm> |
98cc7fd2 | 55 | #include <memory> |
2cae0ccb | 56 | |
7efb8c8e DK |
57 | #ifdef HAVE_ZLIB |
58 | #include <zlib.h> | |
699b209e | 59 | #endif |
c4997486 DK |
60 | #ifdef HAVE_BZ2 |
61 | #include <bzlib.h> | |
62 | #endif | |
7f350a37 DK |
63 | #ifdef HAVE_LZMA |
64 | #include <lzma.h> | |
2cae0ccb | 65 | #endif |
e3fbd54c JAK |
66 | #ifdef HAVE_LZ4 |
67 | #include <lz4frame.h> | |
68 | #endif | |
05eab8af AC |
69 | #include <endian.h> |
70 | #include <stdint.h> | |
ea542140 | 71 | |
3927c6da MV |
72 | #if __gnu_linux__ |
73 | #include <sys/prctl.h> | |
74 | #endif | |
75 | ||
ea542140 | 76 | #include <apti18n.h> |
578bfd0a AL |
77 | /*}}}*/ |
78 | ||
4d055c05 AL |
79 | using namespace std; |
80 | ||
614adaa0 MV |
81 | // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/ |
82 | // --------------------------------------------------------------------- | |
83 | /* */ | |
84 | bool RunScripts(const char *Cnf) | |
85 | { | |
86 | Configuration::Item const *Opts = _config->Tree(Cnf); | |
87 | if (Opts == 0 || Opts->Child == 0) | |
88 | return true; | |
89 | Opts = Opts->Child; | |
90 | ||
91 | // Fork for running the system calls | |
92 | pid_t Child = ExecFork(); | |
93 | ||
94 | // This is the child | |
95 | if (Child == 0) | |
96 | { | |
cfba4f69 MV |
97 | if (_config->FindDir("DPkg::Chroot-Directory","/") != "/") |
98 | { | |
99 | std::cerr << "Chrooting into " | |
100 | << _config->FindDir("DPkg::Chroot-Directory") | |
101 | << std::endl; | |
102 | if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0) | |
103 | _exit(100); | |
104 | } | |
105 | ||
614adaa0 MV |
106 | if (chdir("/tmp/") != 0) |
107 | _exit(100); | |
108 | ||
109 | unsigned int Count = 1; | |
110 | for (; Opts != 0; Opts = Opts->Next, Count++) | |
111 | { | |
112 | if (Opts->Value.empty() == true) | |
113 | continue; | |
e5b7e019 MV |
114 | |
115 | if(_config->FindB("Debug::RunScripts", false) == true) | |
116 | std::clog << "Running external script: '" | |
117 | << Opts->Value << "'" << std::endl; | |
118 | ||
614adaa0 MV |
119 | if (system(Opts->Value.c_str()) != 0) |
120 | _exit(100+Count); | |
121 | } | |
122 | _exit(0); | |
123 | } | |
124 | ||
125 | // Wait for the child | |
126 | int Status = 0; | |
127 | while (waitpid(Child,&Status,0) != Child) | |
128 | { | |
129 | if (errno == EINTR) | |
130 | continue; | |
131 | return _error->Errno("waitpid","Couldn't wait for subprocess"); | |
132 | } | |
133 | ||
134 | // Restore sig int/quit | |
135 | signal(SIGQUIT,SIG_DFL); | |
136 | signal(SIGINT,SIG_DFL); | |
137 | ||
138 | // Check for an error code. | |
139 | if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0) | |
140 | { | |
141 | unsigned int Count = WEXITSTATUS(Status); | |
142 | if (Count > 100) | |
143 | { | |
144 | Count -= 100; | |
145 | for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--); | |
146 | _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str()); | |
147 | } | |
148 | ||
149 | return _error->Error("Sub-process returned an error code"); | |
150 | } | |
151 | ||
152 | return true; | |
153 | } | |
154 | /*}}}*/ | |
155 | ||
578bfd0a AL |
156 | // CopyFile - Buffered copy of a file /*{{{*/ |
157 | // --------------------------------------------------------------------- | |
158 | /* The caller is expected to set things so that failure causes erasure */ | |
8b89e57f | 159 | bool CopyFile(FileFd &From,FileFd &To) |
578bfd0a | 160 | { |
2128d3fc DK |
161 | if (From.IsOpen() == false || To.IsOpen() == false || |
162 | From.Failed() == true || To.Failed() == true) | |
578bfd0a | 163 | return false; |
e977b8b9 | 164 | |
578bfd0a | 165 | // Buffered copy between fds |
0c93e388 PT |
166 | constexpr size_t BufSize = 64000; |
167 | std::unique_ptr<unsigned char[]> Buf(new unsigned char[BufSize]); | |
e977b8b9 DK |
168 | unsigned long long ToRead = 0; |
169 | do { | |
170 | if (From.Read(Buf.get(),BufSize, &ToRead) == false || | |
5df91bc7 | 171 | To.Write(Buf.get(),ToRead) == false) |
578bfd0a | 172 | return false; |
e977b8b9 | 173 | } while (ToRead != 0); |
578bfd0a | 174 | |
ce1f3a2c DK |
175 | return true; |
176 | } | |
177 | /*}}}*/ | |
178 | bool RemoveFile(char const * const Function, std::string const &FileName)/*{{{*/ | |
179 | { | |
180 | if (FileName == "/dev/null") | |
181 | return true; | |
182 | errno = 0; | |
183 | if (unlink(FileName.c_str()) != 0) | |
184 | { | |
185 | if (errno == ENOENT) | |
186 | return true; | |
187 | ||
188 | return _error->WarningE(Function,_("Problem unlinking the file %s"), FileName.c_str()); | |
189 | } | |
e977b8b9 | 190 | return true; |
578bfd0a AL |
191 | } |
192 | /*}}}*/ | |
193 | // GetLock - Gets a lock file /*{{{*/ | |
194 | // --------------------------------------------------------------------- | |
195 | /* This will create an empty file of the given name and lock it. Once this | |
196 | is done all other calls to GetLock in any other process will fail with | |
197 | -1. The return result is the fd of the file, the call should call | |
198 | close at some time. */ | |
199 | int GetLock(string File,bool Errors) | |
200 | { | |
f659b39a OS |
201 | // GetLock() is used in aptitude on directories with public-write access |
202 | // Use O_NOFOLLOW here to prevent symlink traversal attacks | |
203 | int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640); | |
578bfd0a AL |
204 | if (FD < 0) |
205 | { | |
1e3f4083 | 206 | // Read only .. can't have locking problems there. |
b2e465d6 AL |
207 | if (errno == EROFS) |
208 | { | |
209 | _error->Warning(_("Not using locking for read only lock file %s"),File.c_str()); | |
210 | return dup(0); // Need something for the caller to close | |
211 | } | |
212 | ||
578bfd0a | 213 | if (Errors == true) |
b2e465d6 AL |
214 | _error->Errno("open",_("Could not open lock file %s"),File.c_str()); |
215 | ||
216 | // Feh.. We do this to distinguish the lock vs open case.. | |
217 | errno = EPERM; | |
578bfd0a AL |
218 | return -1; |
219 | } | |
b2e465d6 AL |
220 | SetCloseExec(FD,true); |
221 | ||
1e3f4083 | 222 | // Acquire a write lock |
578bfd0a | 223 | struct flock fl; |
c71bc556 AL |
224 | fl.l_type = F_WRLCK; |
225 | fl.l_whence = SEEK_SET; | |
226 | fl.l_start = 0; | |
227 | fl.l_len = 0; | |
578bfd0a AL |
228 | if (fcntl(FD,F_SETLK,&fl) == -1) |
229 | { | |
3d165906 MV |
230 | // always close to not leak resources |
231 | int Tmp = errno; | |
232 | close(FD); | |
233 | errno = Tmp; | |
234 | ||
d89df07a AL |
235 | if (errno == ENOLCK) |
236 | { | |
b2e465d6 AL |
237 | _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str()); |
238 | return dup(0); // Need something for the caller to close | |
3d165906 MV |
239 | } |
240 | ||
578bfd0a | 241 | if (Errors == true) |
b2e465d6 AL |
242 | _error->Errno("open",_("Could not get lock %s"),File.c_str()); |
243 | ||
578bfd0a AL |
244 | return -1; |
245 | } | |
246 | ||
247 | return FD; | |
248 | } | |
249 | /*}}}*/ | |
250 | // FileExists - Check if a file exists /*{{{*/ | |
251 | // --------------------------------------------------------------------- | |
36f1098a | 252 | /* Beware: Directories are also files! */ |
578bfd0a AL |
253 | bool FileExists(string File) |
254 | { | |
255 | struct stat Buf; | |
256 | if (stat(File.c_str(),&Buf) != 0) | |
257 | return false; | |
258 | return true; | |
259 | } | |
260 | /*}}}*/ | |
36f1098a DK |
261 | // RealFileExists - Check if a file exists and if it is really a file /*{{{*/ |
262 | // --------------------------------------------------------------------- | |
263 | /* */ | |
264 | bool RealFileExists(string File) | |
265 | { | |
266 | struct stat Buf; | |
267 | if (stat(File.c_str(),&Buf) != 0) | |
268 | return false; | |
269 | return ((Buf.st_mode & S_IFREG) != 0); | |
270 | } | |
271 | /*}}}*/ | |
1cd1c398 DK |
272 | // DirectoryExists - Check if a directory exists and is really one /*{{{*/ |
273 | // --------------------------------------------------------------------- | |
274 | /* */ | |
275 | bool DirectoryExists(string const &Path) | |
276 | { | |
277 | struct stat Buf; | |
278 | if (stat(Path.c_str(),&Buf) != 0) | |
279 | return false; | |
280 | return ((Buf.st_mode & S_IFDIR) != 0); | |
281 | } | |
282 | /*}}}*/ | |
283 | // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/ | |
284 | // --------------------------------------------------------------------- | |
285 | /* This method will create all directories needed for path in good old | |
286 | mkdir -p style but refuses to do this if Parent is not a prefix of | |
287 | this Path. Example: /var/cache/ and /var/cache/apt/archives are given, | |
288 | so it will create apt/archives if /var/cache exists - on the other | |
289 | hand if the parent is /var/lib the creation will fail as this path | |
290 | is not a parent of the path to be generated. */ | |
291 | bool CreateDirectory(string const &Parent, string const &Path) | |
292 | { | |
293 | if (Parent.empty() == true || Path.empty() == true) | |
294 | return false; | |
295 | ||
296 | if (DirectoryExists(Path) == true) | |
297 | return true; | |
298 | ||
299 | if (DirectoryExists(Parent) == false) | |
300 | return false; | |
301 | ||
302 | // we are not going to create directories "into the blue" | |
9ce3cfc9 | 303 | if (Path.compare(0, Parent.length(), Parent) != 0) |
1cd1c398 DK |
304 | return false; |
305 | ||
306 | vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/'); | |
307 | string progress = Parent; | |
308 | for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d) | |
309 | { | |
310 | if (d->empty() == true) | |
311 | continue; | |
312 | ||
313 | progress.append("/").append(*d); | |
314 | if (DirectoryExists(progress) == true) | |
315 | continue; | |
316 | ||
317 | if (mkdir(progress.c_str(), 0755) != 0) | |
318 | return false; | |
319 | } | |
320 | return true; | |
321 | } | |
322 | /*}}}*/ | |
7753e468 | 323 | // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/ |
b29c3712 DK |
324 | // --------------------------------------------------------------------- |
325 | /* a small wrapper around CreateDirectory to check if it exists and to | |
326 | remove the trailing "/apt/" from the parent directory if needed */ | |
7753e468 | 327 | bool CreateAPTDirectoryIfNeeded(string const &Parent, string const &Path) |
b29c3712 DK |
328 | { |
329 | if (DirectoryExists(Path) == true) | |
330 | return true; | |
331 | ||
332 | size_t const len = Parent.size(); | |
333 | if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5) | |
334 | { | |
335 | if (CreateDirectory(Parent.substr(0,len-5), Path) == true) | |
336 | return true; | |
337 | } | |
338 | else if (CreateDirectory(Parent, Path) == true) | |
339 | return true; | |
340 | ||
341 | return false; | |
342 | } | |
343 | /*}}}*/ | |
46e39c8e MV |
344 | // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/ |
345 | // --------------------------------------------------------------------- | |
346 | /* If an extension is given only files with this extension are included | |
347 | in the returned vector, otherwise every "normal" file is included. */ | |
b39c1859 MV |
348 | std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext, |
349 | bool const &SortList, bool const &AllowNoExt) | |
350 | { | |
351 | std::vector<string> ext; | |
352 | ext.reserve(2); | |
353 | if (Ext.empty() == false) | |
354 | ext.push_back(Ext); | |
355 | if (AllowNoExt == true && ext.empty() == false) | |
356 | ext.push_back(""); | |
357 | return GetListOfFilesInDir(Dir, ext, SortList); | |
358 | } | |
359 | std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext, | |
360 | bool const &SortList) | |
361 | { | |
362 | // Attention debuggers: need to be set with the environment config file! | |
363 | bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false); | |
364 | if (Debug == true) | |
365 | { | |
366 | std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl; | |
367 | if (Ext.empty() == true) | |
368 | std::clog << "\tNO extension" << std::endl; | |
369 | else | |
370 | for (std::vector<string>::const_iterator e = Ext.begin(); | |
371 | e != Ext.end(); ++e) | |
372 | std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl; | |
373 | } | |
374 | ||
46e39c8e | 375 | std::vector<string> List; |
36f1098a | 376 | |
69c2ecbd | 377 | if (DirectoryExists(Dir) == false) |
36f1098a DK |
378 | { |
379 | _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str()); | |
380 | return List; | |
381 | } | |
382 | ||
1408e219 | 383 | Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently"); |
46e39c8e MV |
384 | DIR *D = opendir(Dir.c_str()); |
385 | if (D == 0) | |
386 | { | |
387 | _error->Errno("opendir",_("Unable to read %s"),Dir.c_str()); | |
388 | return List; | |
389 | } | |
390 | ||
391 | for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) | |
392 | { | |
b39c1859 | 393 | // skip "hidden" files |
46e39c8e MV |
394 | if (Ent->d_name[0] == '.') |
395 | continue; | |
396 | ||
491058e3 DK |
397 | // Make sure it is a file and not something else |
398 | string const File = flCombine(Dir,Ent->d_name); | |
399 | #ifdef _DIRENT_HAVE_D_TYPE | |
400 | if (Ent->d_type != DT_REG) | |
401 | #endif | |
402 | { | |
69c2ecbd | 403 | if (RealFileExists(File) == false) |
491058e3 | 404 | { |
84e254d6 DK |
405 | // do not show ignoration warnings for directories |
406 | if ( | |
407 | #ifdef _DIRENT_HAVE_D_TYPE | |
408 | Ent->d_type == DT_DIR || | |
409 | #endif | |
69c2ecbd | 410 | DirectoryExists(File) == true) |
84e254d6 | 411 | continue; |
491058e3 DK |
412 | if (SilentIgnore.Match(Ent->d_name) == false) |
413 | _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str()); | |
414 | continue; | |
415 | } | |
416 | } | |
417 | ||
b39c1859 MV |
418 | // check for accepted extension: |
419 | // no extension given -> periods are bad as hell! | |
420 | // extensions given -> "" extension allows no extension | |
421 | if (Ext.empty() == false) | |
422 | { | |
423 | string d_ext = flExtension(Ent->d_name); | |
424 | if (d_ext == Ent->d_name) // no extension | |
425 | { | |
426 | if (std::find(Ext.begin(), Ext.end(), "") == Ext.end()) | |
427 | { | |
428 | if (Debug == true) | |
429 | std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl; | |
5edc3966 | 430 | if (SilentIgnore.Match(Ent->d_name) == false) |
491058e3 | 431 | _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str()); |
b39c1859 MV |
432 | continue; |
433 | } | |
434 | } | |
435 | else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end()) | |
436 | { | |
437 | if (Debug == true) | |
438 | std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl; | |
1408e219 | 439 | if (SilentIgnore.Match(Ent->d_name) == false) |
491058e3 | 440 | _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str()); |
b39c1859 MV |
441 | continue; |
442 | } | |
443 | } | |
46e39c8e | 444 | |
b39c1859 | 445 | // Skip bad filenames ala run-parts |
46e39c8e MV |
446 | const char *C = Ent->d_name; |
447 | for (; *C != 0; ++C) | |
448 | if (isalpha(*C) == 0 && isdigit(*C) == 0 | |
9d39208a | 449 | && *C != '_' && *C != '-' && *C != ':') { |
b39c1859 MV |
450 | // no required extension -> dot is a bad character |
451 | if (*C == '.' && Ext.empty() == false) | |
452 | continue; | |
46e39c8e | 453 | break; |
b39c1859 | 454 | } |
46e39c8e | 455 | |
b39c1859 | 456 | // we don't reach the end of the name -> bad character included |
46e39c8e | 457 | if (*C != 0) |
b39c1859 MV |
458 | { |
459 | if (Debug == true) | |
460 | std::clog << "Bad file: " << Ent->d_name << " → bad character »" | |
461 | << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl; | |
462 | continue; | |
463 | } | |
464 | ||
fbb2c7e0 DK |
465 | // skip filenames which end with a period. These are never valid |
466 | if (*(C - 1) == '.') | |
467 | { | |
468 | if (Debug == true) | |
469 | std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl; | |
470 | continue; | |
471 | } | |
472 | ||
473 | if (Debug == true) | |
474 | std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl; | |
475 | List.push_back(File); | |
476 | } | |
477 | closedir(D); | |
478 | ||
479 | if (SortList == true) | |
480 | std::sort(List.begin(),List.end()); | |
481 | return List; | |
482 | } | |
483 | std::vector<string> GetListOfFilesInDir(string const &Dir, bool SortList) | |
484 | { | |
485 | bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false); | |
486 | if (Debug == true) | |
487 | std::clog << "Accept in " << Dir << " all regular files" << std::endl; | |
488 | ||
489 | std::vector<string> List; | |
490 | ||
69c2ecbd | 491 | if (DirectoryExists(Dir) == false) |
fbb2c7e0 DK |
492 | { |
493 | _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str()); | |
494 | return List; | |
495 | } | |
496 | ||
497 | DIR *D = opendir(Dir.c_str()); | |
498 | if (D == 0) | |
499 | { | |
500 | _error->Errno("opendir",_("Unable to read %s"),Dir.c_str()); | |
501 | return List; | |
502 | } | |
503 | ||
504 | for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) | |
505 | { | |
506 | // skip "hidden" files | |
507 | if (Ent->d_name[0] == '.') | |
508 | continue; | |
509 | ||
510 | // Make sure it is a file and not something else | |
511 | string const File = flCombine(Dir,Ent->d_name); | |
512 | #ifdef _DIRENT_HAVE_D_TYPE | |
513 | if (Ent->d_type != DT_REG) | |
514 | #endif | |
515 | { | |
69c2ecbd | 516 | if (RealFileExists(File) == false) |
fbb2c7e0 DK |
517 | { |
518 | if (Debug == true) | |
519 | std::clog << "Bad file: " << Ent->d_name << " → it is not a real file" << std::endl; | |
520 | continue; | |
521 | } | |
522 | } | |
523 | ||
524 | // Skip bad filenames ala run-parts | |
525 | const char *C = Ent->d_name; | |
526 | for (; *C != 0; ++C) | |
527 | if (isalpha(*C) == 0 && isdigit(*C) == 0 | |
528 | && *C != '_' && *C != '-' && *C != '.') | |
529 | break; | |
530 | ||
531 | // we don't reach the end of the name -> bad character included | |
532 | if (*C != 0) | |
533 | { | |
534 | if (Debug == true) | |
535 | std::clog << "Bad file: " << Ent->d_name << " → bad character »" << *C << "« in filename" << std::endl; | |
536 | continue; | |
537 | } | |
538 | ||
b39c1859 MV |
539 | // skip filenames which end with a period. These are never valid |
540 | if (*(C - 1) == '.') | |
541 | { | |
542 | if (Debug == true) | |
543 | std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl; | |
46e39c8e | 544 | continue; |
b39c1859 | 545 | } |
46e39c8e | 546 | |
b39c1859 MV |
547 | if (Debug == true) |
548 | std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl; | |
46e39c8e MV |
549 | List.push_back(File); |
550 | } | |
551 | closedir(D); | |
552 | ||
553 | if (SortList == true) | |
554 | std::sort(List.begin(),List.end()); | |
555 | return List; | |
556 | } | |
557 | /*}}}*/ | |
578bfd0a AL |
558 | // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/ |
559 | // --------------------------------------------------------------------- | |
560 | /* We return / on failure. */ | |
561 | string SafeGetCWD() | |
562 | { | |
563 | // Stash the current dir. | |
564 | char S[300]; | |
565 | S[0] = 0; | |
7f25bdff | 566 | if (getcwd(S,sizeof(S)-2) == 0) |
578bfd0a | 567 | return "/"; |
7f25bdff AL |
568 | unsigned int Len = strlen(S); |
569 | S[Len] = '/'; | |
570 | S[Len+1] = 0; | |
578bfd0a AL |
571 | return S; |
572 | } | |
573 | /*}}}*/ | |
2ec858bc MV |
574 | // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/ |
575 | // --------------------------------------------------------------------- | |
576 | /* We return / on failure. */ | |
577 | time_t GetModificationTime(string const &Path) | |
578 | { | |
579 | struct stat St; | |
580 | if (stat(Path.c_str(), &St) < 0) | |
581 | return -1; | |
582 | return St.st_mtime; | |
583 | } | |
584 | /*}}}*/ | |
8ce4327b AL |
585 | // flNotDir - Strip the directory from the filename /*{{{*/ |
586 | // --------------------------------------------------------------------- | |
587 | /* */ | |
588 | string flNotDir(string File) | |
589 | { | |
590 | string::size_type Res = File.rfind('/'); | |
591 | if (Res == string::npos) | |
592 | return File; | |
593 | Res++; | |
594 | return string(File,Res,Res - File.length()); | |
595 | } | |
596 | /*}}}*/ | |
d38b7b3d AL |
597 | // flNotFile - Strip the file from the directory name /*{{{*/ |
598 | // --------------------------------------------------------------------- | |
171c45bc | 599 | /* Result ends in a / */ |
d38b7b3d AL |
600 | string flNotFile(string File) |
601 | { | |
602 | string::size_type Res = File.rfind('/'); | |
603 | if (Res == string::npos) | |
171c45bc | 604 | return "./"; |
d38b7b3d AL |
605 | Res++; |
606 | return string(File,0,Res); | |
607 | } | |
608 | /*}}}*/ | |
b2e465d6 AL |
609 | // flExtension - Return the extension for the file /*{{{*/ |
610 | // --------------------------------------------------------------------- | |
611 | /* */ | |
612 | string flExtension(string File) | |
613 | { | |
614 | string::size_type Res = File.rfind('.'); | |
615 | if (Res == string::npos) | |
616 | return File; | |
617 | Res++; | |
618 | return string(File,Res,Res - File.length()); | |
619 | } | |
620 | /*}}}*/ | |
421c8d10 AL |
621 | // flNoLink - If file is a symlink then deref it /*{{{*/ |
622 | // --------------------------------------------------------------------- | |
623 | /* If the name is not a link then the returned path is the input. */ | |
624 | string flNoLink(string File) | |
625 | { | |
626 | struct stat St; | |
627 | if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0) | |
628 | return File; | |
629 | if (stat(File.c_str(),&St) != 0) | |
630 | return File; | |
631 | ||
632 | /* Loop resolving the link. There is no need to limit the number of | |
633 | loops because the stat call above ensures that the symlink is not | |
634 | circular */ | |
635 | char Buffer[1024]; | |
636 | string NFile = File; | |
637 | while (1) | |
638 | { | |
639 | // Read the link | |
3286ad13 | 640 | ssize_t Res; |
421c8d10 | 641 | if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 || |
3286ad13 | 642 | (size_t)Res >= sizeof(Buffer)) |
421c8d10 AL |
643 | return File; |
644 | ||
645 | // Append or replace the previous path | |
646 | Buffer[Res] = 0; | |
647 | if (Buffer[0] == '/') | |
648 | NFile = Buffer; | |
649 | else | |
650 | NFile = flNotFile(NFile) + Buffer; | |
651 | ||
652 | // See if we are done | |
653 | if (lstat(NFile.c_str(),&St) != 0) | |
654 | return File; | |
655 | if (S_ISLNK(St.st_mode) == 0) | |
656 | return NFile; | |
657 | } | |
658 | } | |
659 | /*}}}*/ | |
b2e465d6 AL |
660 | // flCombine - Combine a file and a directory /*{{{*/ |
661 | // --------------------------------------------------------------------- | |
662 | /* If the file is an absolute path then it is just returned, otherwise | |
663 | the directory is pre-pended to it. */ | |
664 | string flCombine(string Dir,string File) | |
665 | { | |
666 | if (File.empty() == true) | |
667 | return string(); | |
668 | ||
669 | if (File[0] == '/' || Dir.empty() == true) | |
670 | return File; | |
671 | if (File.length() >= 2 && File[0] == '.' && File[1] == '/') | |
672 | return File; | |
673 | if (Dir[Dir.length()-1] == '/') | |
674 | return Dir + File; | |
675 | return Dir + '/' + File; | |
676 | } | |
677 | /*}}}*/ | |
53ac87ac MV |
678 | // flAbsPath - Return the absolute path of the filename /*{{{*/ |
679 | // --------------------------------------------------------------------- | |
680 | /* */ | |
681 | string flAbsPath(string File) | |
682 | { | |
683 | char *p = realpath(File.c_str(), NULL); | |
684 | if (p == NULL) | |
685 | { | |
95278287 | 686 | _error->Errno("realpath", "flAbsPath on %s failed", File.c_str()); |
53ac87ac MV |
687 | return ""; |
688 | } | |
689 | std::string AbsPath(p); | |
690 | free(p); | |
691 | return AbsPath; | |
692 | } | |
693 | /*}}}*/ | |
3b5421b4 AL |
694 | // SetCloseExec - Set the close on exec flag /*{{{*/ |
695 | // --------------------------------------------------------------------- | |
696 | /* */ | |
697 | void SetCloseExec(int Fd,bool Close) | |
698 | { | |
699 | if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0) | |
700 | { | |
701 | cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl; | |
702 | exit(100); | |
703 | } | |
704 | } | |
705 | /*}}}*/ | |
706 | // SetNonBlock - Set the nonblocking flag /*{{{*/ | |
707 | // --------------------------------------------------------------------- | |
708 | /* */ | |
709 | void SetNonBlock(int Fd,bool Block) | |
710 | { | |
0a8a80e5 AL |
711 | int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK); |
712 | if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0) | |
3b5421b4 AL |
713 | { |
714 | cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl; | |
715 | exit(100); | |
716 | } | |
717 | } | |
718 | /*}}}*/ | |
719 | // WaitFd - Wait for a FD to become readable /*{{{*/ | |
720 | // --------------------------------------------------------------------- | |
b2e465d6 | 721 | /* This waits for a FD to become readable using select. It is useful for |
6d5dd02a AL |
722 | applications making use of non-blocking sockets. The timeout is |
723 | in seconds. */ | |
1084d58a | 724 | bool WaitFd(int Fd,bool write,unsigned long timeout) |
3b5421b4 AL |
725 | { |
726 | fd_set Set; | |
cc2313b7 | 727 | struct timeval tv; |
3b5421b4 AL |
728 | FD_ZERO(&Set); |
729 | FD_SET(Fd,&Set); | |
6d5dd02a AL |
730 | tv.tv_sec = timeout; |
731 | tv.tv_usec = 0; | |
1084d58a | 732 | if (write == true) |
b0db36b1 AL |
733 | { |
734 | int Res; | |
735 | do | |
736 | { | |
737 | Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0)); | |
738 | } | |
739 | while (Res < 0 && errno == EINTR); | |
740 | ||
741 | if (Res <= 0) | |
742 | return false; | |
1084d58a AL |
743 | } |
744 | else | |
745 | { | |
b0db36b1 AL |
746 | int Res; |
747 | do | |
748 | { | |
749 | Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0)); | |
750 | } | |
751 | while (Res < 0 && errno == EINTR); | |
752 | ||
753 | if (Res <= 0) | |
754 | return false; | |
cc2313b7 | 755 | } |
1084d58a | 756 | |
3b5421b4 AL |
757 | return true; |
758 | } | |
759 | /*}}}*/ | |
96ae6de5 | 760 | // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/ |
54676e1a | 761 | // --------------------------------------------------------------------- |
96ae6de5 MV |
762 | /* This is used to merge the APT::Keep-Fds with the provided KeepFDs |
763 | * set. | |
764 | */ | |
765 | void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs) | |
e45c4617 | 766 | { |
e45c4617 MV |
767 | Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds"); |
768 | if (Opts != 0 && Opts->Child != 0) | |
769 | { | |
770 | Opts = Opts->Child; | |
771 | for (; Opts != 0; Opts = Opts->Next) | |
772 | { | |
773 | if (Opts->Value.empty() == true) | |
774 | continue; | |
775 | int fd = atoi(Opts->Value.c_str()); | |
776 | KeepFDs.insert(fd); | |
777 | } | |
778 | } | |
96ae6de5 MV |
779 | } |
780 | /*}}}*/ | |
54676e1a AL |
781 | // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/ |
782 | // --------------------------------------------------------------------- | |
783 | /* This is used if you want to cleanse the environment for the forked | |
784 | child, it fixes up the important signals and nukes all of the fds, | |
785 | otherwise acts like normal fork. */ | |
75ef8f14 | 786 | pid_t ExecFork() |
96ae6de5 MV |
787 | { |
788 | set<int> KeepFDs; | |
789 | // we need to merge the Keep-Fds as external tools like | |
790 | // debconf-apt-progress use it | |
791 | MergeKeepFdsFromConfiguration(KeepFDs); | |
e45c4617 MV |
792 | return ExecFork(KeepFDs); |
793 | } | |
794 | ||
795 | pid_t ExecFork(std::set<int> KeepFDs) | |
54676e1a AL |
796 | { |
797 | // Fork off the process | |
798 | pid_t Process = fork(); | |
799 | if (Process < 0) | |
800 | { | |
801 | cerr << "FATAL -> Failed to fork." << endl; | |
802 | exit(100); | |
803 | } | |
804 | ||
805 | // Spawn the subprocess | |
806 | if (Process == 0) | |
807 | { | |
808 | // Setup the signals | |
809 | signal(SIGPIPE,SIG_DFL); | |
810 | signal(SIGQUIT,SIG_DFL); | |
811 | signal(SIGINT,SIG_DFL); | |
812 | signal(SIGWINCH,SIG_DFL); | |
813 | signal(SIGCONT,SIG_DFL); | |
814 | signal(SIGTSTP,SIG_DFL); | |
75ef8f14 | 815 | |
be4d908f JAK |
816 | DIR *dir = opendir("/proc/self/fd"); |
817 | if (dir != NULL) | |
75ef8f14 | 818 | { |
be4d908f JAK |
819 | struct dirent *ent; |
820 | while ((ent = readdir(dir))) | |
821 | { | |
822 | int fd = atoi(ent->d_name); | |
823 | // If fd > 0, it was a fd number and not . or .. | |
824 | if (fd >= 3 && KeepFDs.find(fd) == KeepFDs.end()) | |
825 | fcntl(fd,F_SETFD,FD_CLOEXEC); | |
826 | } | |
827 | closedir(dir); | |
828 | } else { | |
829 | long ScOpenMax = sysconf(_SC_OPEN_MAX); | |
830 | // Close all of our FDs - just in case | |
831 | for (int K = 3; K != ScOpenMax; K++) | |
832 | { | |
833 | if(KeepFDs.find(K) == KeepFDs.end()) | |
834 | fcntl(K,F_SETFD,FD_CLOEXEC); | |
835 | } | |
75ef8f14 | 836 | } |
54676e1a AL |
837 | } |
838 | ||
839 | return Process; | |
840 | } | |
841 | /*}}}*/ | |
ddc1d8d0 AL |
842 | // ExecWait - Fancy waitpid /*{{{*/ |
843 | // --------------------------------------------------------------------- | |
2c9a72d1 | 844 | /* Waits for the given sub process. If Reap is set then no errors are |
ddc1d8d0 AL |
845 | generated. Otherwise a failed subprocess will generate a proper descriptive |
846 | message */ | |
3826564e | 847 | bool ExecWait(pid_t Pid,const char *Name,bool Reap) |
ddc1d8d0 AL |
848 | { |
849 | if (Pid <= 1) | |
850 | return true; | |
851 | ||
852 | // Wait and collect the error code | |
853 | int Status; | |
854 | while (waitpid(Pid,&Status,0) != Pid) | |
855 | { | |
856 | if (errno == EINTR) | |
857 | continue; | |
858 | ||
859 | if (Reap == true) | |
860 | return false; | |
861 | ||
db0db9fe | 862 | return _error->Error(_("Waited for %s but it wasn't there"),Name); |
ddc1d8d0 AL |
863 | } |
864 | ||
865 | ||
866 | // Check for an error code. | |
867 | if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0) | |
868 | { | |
869 | if (Reap == true) | |
870 | return false; | |
ab7f4d7c | 871 | if (WIFSIGNALED(Status) != 0) |
40e7fe0e | 872 | { |
ab7f4d7c MV |
873 | if( WTERMSIG(Status) == SIGSEGV) |
874 | return _error->Error(_("Sub-process %s received a segmentation fault."),Name); | |
875 | else | |
876 | return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status)); | |
40e7fe0e | 877 | } |
ddc1d8d0 AL |
878 | |
879 | if (WIFEXITED(Status) != 0) | |
b2e465d6 | 880 | return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status)); |
ddc1d8d0 | 881 | |
b2e465d6 | 882 | return _error->Error(_("Sub-process %s exited unexpectedly"),Name); |
ddc1d8d0 AL |
883 | } |
884 | ||
885 | return true; | |
886 | } | |
887 | /*}}}*/ | |
f8aba23f | 888 | // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/ |
fe5804fc | 889 | bool StartsWithGPGClearTextSignature(string const &FileName) |
0854ad8b MV |
890 | { |
891 | static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n"; | |
1c89c98a | 892 | char buffer[strlen(SIGMSG)+1]; |
0854ad8b MV |
893 | FILE* gpg = fopen(FileName.c_str(), "r"); |
894 | if (gpg == NULL) | |
895 | return false; | |
896 | ||
897 | char const * const test = fgets(buffer, sizeof(buffer), gpg); | |
898 | fclose(gpg); | |
899 | if (test == NULL || strcmp(buffer, SIGMSG) != 0) | |
900 | return false; | |
901 | ||
902 | return true; | |
903 | } | |
f8aba23f | 904 | /*}}}*/ |
d84da499 DK |
905 | // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/ |
906 | bool ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode) | |
907 | { | |
908 | if (strcmp(file, "/dev/null") == 0) | |
909 | return true; | |
910 | bool Res = true; | |
911 | if (getuid() == 0 && strlen(user) != 0 && strlen(group) != 0) // if we aren't root, we can't chown, so don't try it | |
912 | { | |
913 | // ensure the file is owned by root and has good permissions | |
914 | struct passwd const * const pw = getpwnam(user); | |
915 | struct group const * const gr = getgrnam(group); | |
916 | if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0) | |
917 | Res &= _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file); | |
918 | } | |
919 | if (chmod(file, mode) != 0) | |
920 | Res &= _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file); | |
921 | return Res; | |
922 | } | |
923 | /*}}}*/ | |
0854ad8b | 924 | |
38dba8cd | 925 | struct APT_HIDDEN simple_buffer { /*{{{*/ |
5bdba2ca | 926 | size_t buffersize_max = 0; |
38dba8cd JAK |
927 | unsigned long long bufferstart = 0; |
928 | unsigned long long bufferend = 0; | |
5bdba2ca JAK |
929 | char *buffer = nullptr; |
930 | ||
931 | simple_buffer() { | |
932 | reset(4096); | |
933 | } | |
934 | ~simple_buffer() { | |
935 | delete buffer; | |
936 | } | |
38dba8cd | 937 | |
ea58d39e | 938 | const char *get() const { return buffer + bufferstart; } |
38dba8cd | 939 | char *get() { return buffer + bufferstart; } |
f1b9bf7a JAK |
940 | const char *getend() const { return buffer + bufferend; } |
941 | char *getend() { return buffer + bufferend; } | |
ea58d39e | 942 | bool empty() const { return bufferend <= bufferstart; } |
c368b3ab | 943 | bool full() const { return bufferend == buffersize_max; } |
f1b9bf7a | 944 | unsigned long long free() const { return buffersize_max - bufferend; } |
ea58d39e | 945 | unsigned long long size() const { return bufferend-bufferstart; } |
5bdba2ca JAK |
946 | void reset(size_t size) |
947 | { | |
948 | if (size > buffersize_max) { | |
949 | delete[] buffer; | |
950 | buffersize_max = size; | |
951 | buffer = new char[size]; | |
952 | } | |
953 | reset(); | |
954 | } | |
38dba8cd JAK |
955 | void reset() { bufferend = bufferstart = 0; } |
956 | ssize_t read(void *to, unsigned long long requested_size) APT_MUSTCHECK | |
957 | { | |
958 | if (size() < requested_size) | |
959 | requested_size = size(); | |
960 | memcpy(to, buffer + bufferstart, requested_size); | |
961 | bufferstart += requested_size; | |
962 | if (bufferstart == bufferend) | |
963 | bufferstart = bufferend = 0; | |
964 | return requested_size; | |
965 | } | |
c368b3ab JAK |
966 | ssize_t write(const void *from, unsigned long long requested_size) APT_MUSTCHECK |
967 | { | |
968 | if (buffersize_max - size() < requested_size) | |
969 | requested_size = buffersize_max - size(); | |
970 | memcpy(buffer + bufferend, from, requested_size); | |
971 | bufferend += requested_size; | |
972 | if (bufferstart == bufferend) | |
973 | bufferstart = bufferend = 0; | |
974 | return requested_size; | |
975 | } | |
38dba8cd JAK |
976 | }; |
977 | /*}}}*/ | |
978 | ||
65ac6aad | 979 | class APT_HIDDEN FileFdPrivate { /*{{{*/ |
88749b5d | 980 | friend class BufferedWriteFileFdPrivate; |
fa89055f DK |
981 | protected: |
982 | FileFd * const filefd; | |
38dba8cd | 983 | simple_buffer buffer; |
fa89055f DK |
984 | int compressed_fd; |
985 | pid_t compressor_pid; | |
986 | bool is_pipe; | |
987 | APT::Configuration::Compressor compressor; | |
988 | unsigned int openmode; | |
989 | unsigned long long seekpos; | |
1d68256d JAK |
990 | public: |
991 | ||
83e22e26 | 992 | explicit FileFdPrivate(FileFd * const pfilefd) : filefd(pfilefd), |
fa89055f DK |
993 | compressed_fd(-1), compressor_pid(-1), is_pipe(false), |
994 | openmode(0), seekpos(0) {}; | |
1d68256d JAK |
995 | virtual APT::Configuration::Compressor get_compressor() const |
996 | { | |
997 | return compressor; | |
998 | } | |
999 | virtual void set_compressor(APT::Configuration::Compressor const &compressor) | |
1000 | { | |
1001 | this->compressor = compressor; | |
1002 | } | |
1003 | virtual unsigned int get_openmode() const | |
1004 | { | |
1005 | return openmode; | |
1006 | } | |
1007 | virtual void set_openmode(unsigned int openmode) | |
1008 | { | |
1009 | this->openmode = openmode; | |
1010 | } | |
1011 | virtual bool get_is_pipe() const | |
1012 | { | |
1013 | return is_pipe; | |
1014 | } | |
1015 | virtual void set_is_pipe(bool is_pipe) | |
1016 | { | |
1017 | this->is_pipe = is_pipe; | |
1018 | } | |
1019 | virtual unsigned long long get_seekpos() const | |
1020 | { | |
1021 | return seekpos; | |
1022 | } | |
1023 | virtual void set_seekpos(unsigned long long seekpos) | |
1024 | { | |
1025 | this->seekpos = seekpos; | |
1026 | } | |
fa89055f DK |
1027 | |
1028 | virtual bool InternalOpen(int const iFd, unsigned int const Mode) = 0; | |
f63123c3 | 1029 | ssize_t InternalRead(void * To, unsigned long long Size) |
fa89055f | 1030 | { |
83e22e26 JAK |
1031 | // Drain the buffer if needed. |
1032 | if (buffer.empty() == false) | |
fa89055f | 1033 | { |
83e22e26 | 1034 | return buffer.read(To, Size); |
fa89055f | 1035 | } |
83e22e26 | 1036 | return InternalUnbufferedRead(To, Size); |
f63123c3 DK |
1037 | } |
1038 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) = 0; | |
1039 | virtual bool InternalReadError() { return filefd->FileFdErrno("read",_("Read error")); } | |
1040 | virtual char * InternalReadLine(char * To, unsigned long long Size) | |
1041 | { | |
1042 | if (unlikely(Size == 0)) | |
1043 | return nullptr; | |
01152444 | 1044 | // Read one byte less than buffer size to have space for trailing 0. |
f63123c3 | 1045 | --Size; |
01152444 | 1046 | |
f63123c3 DK |
1047 | char * const InitialTo = To; |
1048 | ||
01152444 | 1049 | while (Size > 0) { |
83e22e26 | 1050 | if (buffer.empty() == true) |
f63123c3 | 1051 | { |
83e22e26 | 1052 | buffer.reset(); |
f63123c3 | 1053 | unsigned long long actualread = 0; |
83e22e26 | 1054 | if (filefd->Read(buffer.get(), buffer.buffersize_max, &actualread) == false) |
f63123c3 | 1055 | return nullptr; |
83e22e26 JAK |
1056 | buffer.bufferend = actualread; |
1057 | if (buffer.size() == 0) | |
f63123c3 DK |
1058 | { |
1059 | if (To == InitialTo) | |
1060 | return nullptr; | |
1061 | break; | |
1062 | } | |
1063 | filefd->Flags &= ~FileFd::HitEof; | |
1064 | } | |
1065 | ||
83e22e26 | 1066 | unsigned long long const OutputSize = std::min(Size, buffer.size()); |
b3db9d81 | 1067 | char const * const newline = static_cast<char const * const>(memchr(buffer.get(), '\n', OutputSize)); |
a9024b1b JAK |
1068 | // Read until end of line or up to Size bytes from the buffer. |
1069 | unsigned long long actualread = buffer.read(To, | |
1070 | (newline != nullptr) | |
1071 | ? (newline - buffer.get()) + 1 | |
1072 | : OutputSize); | |
1073 | To += actualread; | |
1074 | Size -= actualread; | |
f63123c3 | 1075 | if (newline != nullptr) |
f63123c3 | 1076 | break; |
01152444 | 1077 | } |
f63123c3 DK |
1078 | *To = '\0'; |
1079 | return InitialTo; | |
fa89055f | 1080 | } |
766761fd JAK |
1081 | virtual bool InternalFlush() |
1082 | { | |
1083 | return true; | |
1084 | } | |
fa89055f DK |
1085 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) = 0; |
1086 | virtual bool InternalWriteError() { return filefd->FileFdErrno("write",_("Write error")); } | |
1087 | virtual bool InternalSeek(unsigned long long const To) | |
1088 | { | |
1089 | // Our poor man seeking is costly, so try to avoid it | |
1090 | unsigned long long const iseekpos = filefd->Tell(); | |
1091 | if (iseekpos == To) | |
1092 | return true; | |
1093 | else if (iseekpos < To) | |
1094 | return filefd->Skip(To - iseekpos); | |
1095 | ||
1096 | if ((openmode & FileFd::ReadOnly) != FileFd::ReadOnly) | |
1097 | return filefd->FileFdError("Reopen is only implemented for read-only files!"); | |
1098 | InternalClose(filefd->FileName); | |
1099 | if (filefd->iFd != -1) | |
1100 | close(filefd->iFd); | |
1101 | filefd->iFd = -1; | |
1102 | if (filefd->TemporaryFileName.empty() == false) | |
1103 | filefd->iFd = open(filefd->TemporaryFileName.c_str(), O_RDONLY); | |
1104 | else if (filefd->FileName.empty() == false) | |
1105 | filefd->iFd = open(filefd->FileName.c_str(), O_RDONLY); | |
1106 | else | |
1107 | { | |
1108 | if (compressed_fd > 0) | |
1109 | if (lseek(compressed_fd, 0, SEEK_SET) != 0) | |
1110 | filefd->iFd = compressed_fd; | |
1111 | if (filefd->iFd < 0) | |
1112 | return filefd->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!"); | |
1113 | } | |
1114 | ||
1115 | if (filefd->OpenInternDescriptor(openmode, compressor) == false) | |
1116 | return filefd->FileFdError("Seek on file %s because it couldn't be reopened", filefd->FileName.c_str()); | |
1117 | ||
83e22e26 | 1118 | buffer.reset(); |
fa89055f DK |
1119 | if (To != 0) |
1120 | return filefd->Skip(To); | |
1121 | ||
1122 | seekpos = To; | |
1123 | return true; | |
1124 | } | |
1125 | virtual bool InternalSkip(unsigned long long Over) | |
1126 | { | |
1127 | unsigned long long constexpr buffersize = 1024; | |
1128 | char buffer[buffersize]; | |
1129 | while (Over != 0) | |
1130 | { | |
1131 | unsigned long long toread = std::min(buffersize, Over); | |
1132 | if (filefd->Read(buffer, toread) == false) | |
1133 | return filefd->FileFdError("Unable to seek ahead %llu",Over); | |
1134 | Over -= toread; | |
1135 | } | |
1136 | return true; | |
1137 | } | |
1138 | virtual bool InternalTruncate(unsigned long long const) | |
1139 | { | |
1140 | return filefd->FileFdError("Truncating compressed files is not implemented (%s)", filefd->FileName.c_str()); | |
1141 | } | |
1142 | virtual unsigned long long InternalTell() | |
1143 | { | |
1144 | // In theory, we could just return seekpos here always instead of | |
1145 | // seeking around, but not all users of FileFd use always Seek() and co | |
1146 | // so d->seekpos isn't always true and we can just use it as a hint if | |
1147 | // we have nothing else, but not always as an authority… | |
83e22e26 | 1148 | return seekpos - buffer.size(); |
fa89055f DK |
1149 | } |
1150 | virtual unsigned long long InternalSize() | |
1151 | { | |
1152 | unsigned long long size = 0; | |
1153 | unsigned long long const oldSeek = filefd->Tell(); | |
1154 | unsigned long long constexpr ignoresize = 1024; | |
1155 | char ignore[ignoresize]; | |
1156 | unsigned long long read = 0; | |
1157 | do { | |
1158 | if (filefd->Read(ignore, ignoresize, &read) == false) | |
1159 | { | |
1160 | filefd->Seek(oldSeek); | |
1161 | return 0; | |
1162 | } | |
1163 | } while(read != 0); | |
1164 | size = filefd->Tell(); | |
1165 | filefd->Seek(oldSeek); | |
1166 | return size; | |
1167 | } | |
1168 | virtual bool InternalClose(std::string const &FileName) = 0; | |
1169 | virtual bool InternalStream() const { return false; } | |
1170 | virtual bool InternalAlwaysAutoClose() const { return true; } | |
1171 | ||
1172 | virtual ~FileFdPrivate() {} | |
1173 | }; | |
1174 | /*}}}*/ | |
88749b5d JAK |
1175 | class APT_HIDDEN BufferedWriteFileFdPrivate : public FileFdPrivate { /*{{{*/ |
1176 | protected: | |
1177 | FileFdPrivate *wrapped; | |
1178 | simple_buffer writebuffer; | |
1179 | ||
1180 | public: | |
1181 | ||
1182 | explicit BufferedWriteFileFdPrivate(FileFdPrivate *Priv) : | |
1183 | FileFdPrivate(Priv->filefd), wrapped(Priv) {}; | |
1184 | ||
1185 | virtual APT::Configuration::Compressor get_compressor() const override | |
1186 | { | |
1187 | return wrapped->get_compressor(); | |
1188 | } | |
1189 | virtual void set_compressor(APT::Configuration::Compressor const &compressor) override | |
1190 | { | |
1191 | return wrapped->set_compressor(compressor); | |
1192 | } | |
1193 | virtual unsigned int get_openmode() const override | |
1194 | { | |
1195 | return wrapped->get_openmode(); | |
1196 | } | |
1197 | virtual void set_openmode(unsigned int openmode) override | |
1198 | { | |
1199 | return wrapped->set_openmode(openmode); | |
1200 | } | |
1201 | virtual bool get_is_pipe() const override | |
1202 | { | |
1203 | return wrapped->get_is_pipe(); | |
1204 | } | |
1205 | virtual void set_is_pipe(bool is_pipe) override | |
1206 | { | |
1207 | FileFdPrivate::set_is_pipe(is_pipe); | |
1208 | wrapped->set_is_pipe(is_pipe); | |
1209 | } | |
1210 | virtual unsigned long long get_seekpos() const override | |
1211 | { | |
1212 | return wrapped->get_seekpos(); | |
1213 | } | |
1214 | virtual void set_seekpos(unsigned long long seekpos) override | |
1215 | { | |
1216 | return wrapped->set_seekpos(seekpos); | |
1217 | } | |
1218 | virtual bool InternalOpen(int const iFd, unsigned int const Mode) override | |
1219 | { | |
1220 | if (InternalFlush() == false) | |
1221 | return false; | |
1222 | return wrapped->InternalOpen(iFd, Mode); | |
1223 | } | |
1224 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override | |
1225 | { | |
1226 | if (InternalFlush() == false) | |
1227 | return -1; | |
1228 | return wrapped->InternalUnbufferedRead(To, Size); | |
1229 | ||
1230 | } | |
1231 | virtual bool InternalReadError() override | |
1232 | { | |
1233 | return wrapped->InternalReadError(); | |
1234 | } | |
1235 | virtual char * InternalReadLine(char * To, unsigned long long Size) override | |
1236 | { | |
1237 | if (InternalFlush() == false) | |
1238 | return nullptr; | |
1239 | return wrapped->InternalReadLine(To, Size); | |
1240 | } | |
1241 | virtual bool InternalFlush() override | |
1242 | { | |
1f5062f6 JAK |
1243 | while (writebuffer.empty() == false) { |
1244 | auto written = wrapped->InternalWrite(writebuffer.get(), | |
1245 | writebuffer.size()); | |
1246 | // Ignore interrupted syscalls | |
1247 | if (written < 0 && errno == EINTR) | |
1248 | continue; | |
1249 | if (written < 0) | |
88749b5d | 1250 | return false; |
88749b5d | 1251 | |
1f5062f6 | 1252 | writebuffer.bufferstart += written; |
88749b5d JAK |
1253 | } |
1254 | ||
1255 | writebuffer.reset(); | |
1256 | return true; | |
1257 | } | |
1258 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override | |
1259 | { | |
1260 | size_t written = 0; | |
1261 | ||
1262 | while (written < Size) { | |
1263 | auto buffered = writebuffer.write(static_cast<char const*>(From) + written, Size - written); | |
1264 | ||
1265 | written += buffered; | |
1266 | ||
1267 | if (writebuffer.full() && InternalFlush() == false) | |
1268 | return -1; | |
1269 | } | |
1270 | ||
1271 | return written; | |
1272 | } | |
1273 | virtual bool InternalWriteError() | |
1274 | { | |
1275 | return wrapped->InternalWriteError(); | |
1276 | } | |
1277 | virtual bool InternalSeek(unsigned long long const To) | |
1278 | { | |
1279 | if (InternalFlush() == false) | |
1280 | return false; | |
1281 | return wrapped->InternalSeek(To); | |
1282 | } | |
1283 | virtual bool InternalSkip(unsigned long long Over) | |
1284 | { | |
1285 | if (InternalFlush() == false) | |
1286 | return false; | |
1287 | return wrapped->InternalSkip(Over); | |
1288 | } | |
1289 | virtual bool InternalTruncate(unsigned long long const Size) | |
1290 | { | |
1291 | if (InternalFlush() == false) | |
1292 | return false; | |
1293 | return wrapped->InternalTruncate(Size); | |
1294 | } | |
1295 | virtual unsigned long long InternalTell() | |
1296 | { | |
1297 | if (InternalFlush() == false) | |
1298 | return -1; | |
1299 | return wrapped->InternalTell(); | |
1300 | } | |
1301 | virtual unsigned long long InternalSize() | |
1302 | { | |
1303 | if (InternalFlush() == false) | |
1304 | return -1; | |
1305 | return wrapped->InternalSize(); | |
1306 | } | |
1307 | virtual bool InternalClose(std::string const &FileName) | |
1308 | { | |
1309 | return wrapped->InternalClose(FileName); | |
1310 | } | |
1311 | virtual bool InternalAlwaysAutoClose() const | |
1312 | { | |
1313 | return wrapped->InternalAlwaysAutoClose(); | |
1314 | } | |
1315 | virtual ~BufferedWriteFileFdPrivate() | |
1316 | { | |
1317 | delete wrapped; | |
1318 | } | |
1319 | }; | |
1320 | /*}}}*/ | |
65ac6aad | 1321 | class APT_HIDDEN GzipFileFdPrivate: public FileFdPrivate { /*{{{*/ |
4239dbca | 1322 | #ifdef HAVE_ZLIB |
fa89055f DK |
1323 | public: |
1324 | gzFile gz; | |
1325 | virtual bool InternalOpen(int const iFd, unsigned int const Mode) override | |
1326 | { | |
1327 | if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite) | |
1328 | gz = gzdopen(iFd, "r+"); | |
1329 | else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) | |
1330 | gz = gzdopen(iFd, "w"); | |
1331 | else | |
1332 | gz = gzdopen(iFd, "r"); | |
1333 | filefd->Flags |= FileFd::Compressed; | |
1334 | return gz != nullptr; | |
1335 | } | |
f63123c3 | 1336 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override |
fa89055f DK |
1337 | { |
1338 | return gzread(gz, To, Size); | |
1339 | } | |
1340 | virtual bool InternalReadError() override | |
1341 | { | |
1342 | int err; | |
1343 | char const * const errmsg = gzerror(gz, &err); | |
1344 | if (err != Z_ERRNO) | |
1345 | return filefd->FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg); | |
1346 | return FileFdPrivate::InternalReadError(); | |
1347 | } | |
f63123c3 | 1348 | virtual char * InternalReadLine(char * To, unsigned long long Size) override |
fa89055f DK |
1349 | { |
1350 | return gzgets(gz, To, Size); | |
1351 | } | |
1352 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override | |
1353 | { | |
1354 | return gzwrite(gz,From,Size); | |
1355 | } | |
1356 | virtual bool InternalWriteError() override | |
1357 | { | |
1358 | int err; | |
1359 | char const * const errmsg = gzerror(gz, &err); | |
1360 | if (err != Z_ERRNO) | |
1361 | return filefd->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg); | |
1362 | return FileFdPrivate::InternalWriteError(); | |
1363 | } | |
1364 | virtual bool InternalSeek(unsigned long long const To) override | |
1365 | { | |
1366 | off_t const res = gzseek(gz, To, SEEK_SET); | |
1367 | if (res != (off_t)To) | |
1368 | return filefd->FileFdError("Unable to seek to %llu", To); | |
fa89055f | 1369 | seekpos = To; |
83e22e26 | 1370 | buffer.reset(); |
fa89055f DK |
1371 | return true; |
1372 | } | |
1373 | virtual bool InternalSkip(unsigned long long Over) override | |
1374 | { | |
83e22e26 | 1375 | if (Over >= buffer.size()) |
f63123c3 | 1376 | { |
83e22e26 JAK |
1377 | Over -= buffer.size(); |
1378 | buffer.reset(); | |
f63123c3 DK |
1379 | } |
1380 | else | |
1381 | { | |
83e22e26 | 1382 | buffer.bufferstart += Over; |
f63123c3 DK |
1383 | return true; |
1384 | } | |
1385 | if (Over == 0) | |
1386 | return true; | |
fa89055f DK |
1387 | off_t const res = gzseek(gz, Over, SEEK_CUR); |
1388 | if (res < 0) | |
1389 | return filefd->FileFdError("Unable to seek ahead %llu",Over); | |
1390 | seekpos = res; | |
1391 | return true; | |
1392 | } | |
1393 | virtual unsigned long long InternalTell() override | |
1394 | { | |
83e22e26 | 1395 | return gztell(gz) - buffer.size(); |
fa89055f DK |
1396 | } |
1397 | virtual unsigned long long InternalSize() override | |
1398 | { | |
1399 | unsigned long long filesize = FileFdPrivate::InternalSize(); | |
1400 | // only check gzsize if we are actually a gzip file, just checking for | |
1401 | // "gz" is not sufficient as uncompressed files could be opened with | |
1402 | // gzopen in "direct" mode as well | |
1403 | if (filesize == 0 || gzdirect(gz)) | |
1404 | return filesize; | |
1405 | ||
1406 | off_t const oldPos = lseek(filefd->iFd, 0, SEEK_CUR); | |
1407 | /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do | |
1408 | * this ourselves; the original (uncompressed) file size is the last 32 | |
1409 | * bits of the file */ | |
1410 | // FIXME: Size for gz-files is limited by 32bit… no largefile support | |
1411 | if (lseek(filefd->iFd, -4, SEEK_END) < 0) | |
1412 | { | |
1413 | filefd->FileFdErrno("lseek","Unable to seek to end of gzipped file"); | |
1414 | return 0; | |
1415 | } | |
1416 | uint32_t size = 0; | |
1417 | if (read(filefd->iFd, &size, 4) != 4) | |
1418 | { | |
1419 | filefd->FileFdErrno("read","Unable to read original size of gzipped file"); | |
1420 | return 0; | |
1421 | } | |
1422 | size = le32toh(size); | |
1423 | ||
1424 | if (lseek(filefd->iFd, oldPos, SEEK_SET) < 0) | |
1425 | { | |
1426 | filefd->FileFdErrno("lseek","Unable to seek in gzipped file"); | |
1427 | return 0; | |
1428 | } | |
1429 | return size; | |
1430 | } | |
1431 | virtual bool InternalClose(std::string const &FileName) override | |
1432 | { | |
1433 | if (gz == nullptr) | |
1434 | return true; | |
1435 | int const e = gzclose(gz); | |
1436 | gz = nullptr; | |
1437 | // gzdclose() on empty files always fails with "buffer error" here, ignore that | |
1438 | if (e != 0 && e != Z_BUF_ERROR) | |
1439 | return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str()); | |
1440 | return true; | |
1441 | } | |
1442 | ||
11755147 | 1443 | explicit GzipFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), gz(nullptr) {} |
fa89055f | 1444 | virtual ~GzipFileFdPrivate() { InternalClose(""); } |
4239dbca | 1445 | #endif |
fa89055f DK |
1446 | }; |
1447 | /*}}}*/ | |
65ac6aad | 1448 | class APT_HIDDEN Bz2FileFdPrivate: public FileFdPrivate { /*{{{*/ |
4239dbca | 1449 | #ifdef HAVE_BZ2 |
fa89055f DK |
1450 | BZFILE* bz2; |
1451 | public: | |
1452 | virtual bool InternalOpen(int const iFd, unsigned int const Mode) override | |
1453 | { | |
1454 | if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite) | |
1455 | bz2 = BZ2_bzdopen(iFd, "r+"); | |
1456 | else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) | |
1457 | bz2 = BZ2_bzdopen(iFd, "w"); | |
1458 | else | |
1459 | bz2 = BZ2_bzdopen(iFd, "r"); | |
1460 | filefd->Flags |= FileFd::Compressed; | |
1461 | return bz2 != nullptr; | |
1462 | } | |
f63123c3 | 1463 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override |
fa89055f DK |
1464 | { |
1465 | return BZ2_bzread(bz2, To, Size); | |
1466 | } | |
1467 | virtual bool InternalReadError() override | |
1468 | { | |
1469 | int err; | |
1470 | char const * const errmsg = BZ2_bzerror(bz2, &err); | |
1471 | if (err != BZ_IO_ERROR) | |
1472 | return filefd->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd->FileName.c_str(), _("Read error"), err, errmsg); | |
1473 | return FileFdPrivate::InternalReadError(); | |
1474 | } | |
1475 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override | |
1476 | { | |
1477 | return BZ2_bzwrite(bz2, (void*)From, Size); | |
1478 | } | |
1479 | virtual bool InternalWriteError() override | |
1480 | { | |
1481 | int err; | |
1482 | char const * const errmsg = BZ2_bzerror(bz2, &err); | |
1483 | if (err != BZ_IO_ERROR) | |
1484 | return filefd->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd->FileName.c_str(), _("Write error"), err, errmsg); | |
1485 | return FileFdPrivate::InternalWriteError(); | |
1486 | } | |
1487 | virtual bool InternalStream() const override { return true; } | |
1488 | virtual bool InternalClose(std::string const &) override | |
1489 | { | |
1490 | if (bz2 == nullptr) | |
1491 | return true; | |
1492 | BZ2_bzclose(bz2); | |
1493 | bz2 = nullptr; | |
1494 | return true; | |
1495 | } | |
1496 | ||
11755147 | 1497 | explicit Bz2FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), bz2(nullptr) {} |
fa89055f | 1498 | virtual ~Bz2FileFdPrivate() { InternalClose(""); } |
4239dbca | 1499 | #endif |
e3fbd54c JAK |
1500 | }; |
1501 | /*}}}*/ | |
1502 | class APT_HIDDEN Lz4FileFdPrivate: public FileFdPrivate { /*{{{*/ | |
1503 | static constexpr unsigned long long BLK_SIZE = 64 * 1024; | |
1504 | static constexpr unsigned long long LZ4_HEADER_SIZE = 19; | |
1505 | static constexpr unsigned long long LZ4_FOOTER_SIZE = 4; | |
1506 | #ifdef HAVE_LZ4 | |
1507 | LZ4F_decompressionContext_t dctx; | |
1508 | LZ4F_compressionContext_t cctx; | |
1509 | LZ4F_errorCode_t res; | |
1510 | FileFd backend; | |
1511 | simple_buffer lz4_buffer; | |
1512 | // Count of bytes that the decompressor expects to read next, or buffer size. | |
1513 | size_t next_to_load = BLK_SIZE; | |
1514 | public: | |
1515 | virtual bool InternalOpen(int const iFd, unsigned int const Mode) override | |
1516 | { | |
1517 | if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite) | |
1518 | return _error->Error("lz4 only supports write or read mode"); | |
1519 | ||
1520 | if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) { | |
1521 | res = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION); | |
1522 | lz4_buffer.reset(LZ4F_compressBound(BLK_SIZE, nullptr) | |
1523 | + LZ4_HEADER_SIZE + LZ4_FOOTER_SIZE); | |
1524 | } else { | |
1525 | res = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); | |
1526 | lz4_buffer.reset(64 * 1024); | |
1527 | } | |
1528 | ||
1529 | filefd->Flags |= FileFd::Compressed; | |
1530 | ||
1531 | if (LZ4F_isError(res)) | |
1532 | return false; | |
1533 | ||
1534 | unsigned int flags = (Mode & (FileFd::WriteOnly|FileFd::ReadOnly)); | |
1535 | if (backend.OpenDescriptor(iFd, flags) == false) | |
1536 | return false; | |
1537 | ||
1538 | // Write the file header | |
1539 | if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) | |
1540 | { | |
1541 | res = LZ4F_compressBegin(cctx, lz4_buffer.buffer, lz4_buffer.buffersize_max, nullptr); | |
1542 | if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false) | |
1543 | return false; | |
1544 | } | |
1545 | ||
1546 | return true; | |
1547 | } | |
1548 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override | |
1549 | { | |
1550 | /* Keep reading as long as the compressor still wants to read */ | |
1551 | while (next_to_load) { | |
1552 | // Fill compressed buffer; | |
1553 | if (lz4_buffer.empty()) { | |
1554 | unsigned long long read; | |
1555 | /* Reset - if LZ4 decompressor wants to read more, allocate more */ | |
1556 | lz4_buffer.reset(next_to_load); | |
1557 | if (backend.Read(lz4_buffer.getend(), lz4_buffer.free(), &read) == false) | |
1558 | return -1; | |
1559 | lz4_buffer.bufferend += read; | |
1560 | ||
1561 | /* Expected EOF */ | |
1562 | if (read == 0) { | |
1563 | res = -1; | |
1564 | return filefd->FileFdError("LZ4F: %s %s", | |
1565 | filefd->FileName.c_str(), | |
1566 | _("Unexpected end of file")), -1; | |
1567 | } | |
1568 | } | |
1569 | // Drain compressed buffer as far as possible. | |
1570 | size_t in = lz4_buffer.size(); | |
1571 | size_t out = Size; | |
1572 | ||
1573 | res = LZ4F_decompress(dctx, To, &out, lz4_buffer.get(), &in, nullptr); | |
1574 | if (LZ4F_isError(res)) | |
1575 | return -1; | |
1576 | ||
1577 | next_to_load = res; | |
1578 | lz4_buffer.bufferstart += in; | |
1579 | ||
1580 | if (out != 0) | |
1581 | return out; | |
1582 | } | |
1583 | ||
1584 | return 0; | |
1585 | } | |
1586 | virtual bool InternalReadError() override | |
1587 | { | |
1588 | char const * const errmsg = LZ4F_getErrorName(res); | |
1589 | ||
1590 | return filefd->FileFdError("LZ4F: %s %s (%zu: %s)", filefd->FileName.c_str(), _("Read error"), res, errmsg); | |
1591 | } | |
1592 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override | |
1593 | { | |
1594 | unsigned long long const towrite = std::min(BLK_SIZE, Size); | |
1595 | ||
1596 | res = LZ4F_compressUpdate(cctx, | |
1597 | lz4_buffer.buffer, lz4_buffer.buffersize_max, | |
1598 | From, towrite, nullptr); | |
1599 | ||
1600 | if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false) | |
1601 | return -1; | |
1602 | ||
1603 | return towrite; | |
1604 | } | |
1605 | virtual bool InternalWriteError() override | |
1606 | { | |
1607 | char const * const errmsg = LZ4F_getErrorName(res); | |
1608 | ||
1609 | return filefd->FileFdError("LZ4F: %s %s (%zu: %s)", filefd->FileName.c_str(), _("Write error"), res, errmsg); | |
1610 | } | |
1611 | virtual bool InternalStream() const override { return true; } | |
1612 | ||
1613 | virtual bool InternalFlush() override | |
1614 | { | |
1615 | return backend.Flush(); | |
1616 | } | |
1617 | ||
1618 | virtual bool InternalClose(std::string const &) override | |
1619 | { | |
1620 | /* Reset variables */ | |
1621 | res = 0; | |
1622 | next_to_load = BLK_SIZE; | |
1623 | ||
1624 | if (cctx != nullptr) | |
1625 | { | |
1626 | res = LZ4F_compressEnd(cctx, lz4_buffer.buffer, lz4_buffer.buffersize_max, nullptr); | |
1627 | if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false) | |
1628 | return false; | |
1629 | if (!backend.Flush()) | |
1630 | return false; | |
1631 | if (!backend.Close()) | |
1632 | return false; | |
1633 | ||
1634 | res = LZ4F_freeCompressionContext(cctx); | |
1635 | cctx = nullptr; | |
1636 | } | |
1637 | ||
1638 | if (dctx != nullptr) | |
1639 | { | |
1640 | res = LZ4F_freeDecompressionContext(dctx); | |
1641 | dctx = nullptr; | |
1642 | } | |
1643 | ||
1644 | return LZ4F_isError(res) == false; | |
1645 | } | |
1646 | ||
1647 | explicit Lz4FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), dctx(nullptr), cctx(nullptr) {} | |
1648 | virtual ~Lz4FileFdPrivate() { | |
1649 | InternalClose(""); | |
1650 | } | |
1651 | #endif | |
fa89055f DK |
1652 | }; |
1653 | /*}}}*/ | |
65ac6aad | 1654 | class APT_HIDDEN LzmaFileFdPrivate: public FileFdPrivate { /*{{{*/ |
4239dbca | 1655 | #ifdef HAVE_LZMA |
fa89055f DK |
1656 | struct LZMAFILE { |
1657 | FILE* file; | |
1658 | uint8_t buffer[4096]; | |
1659 | lzma_stream stream; | |
1660 | lzma_ret err; | |
1661 | bool eof; | |
1662 | bool compressing; | |
1663 | ||
1664 | LZMAFILE() : file(nullptr), eof(false), compressing(false) { buffer[0] = '\0'; } | |
1665 | ~LZMAFILE() | |
1666 | { | |
1667 | if (compressing == true) | |
1668 | { | |
1669 | size_t constexpr buffersize = sizeof(buffer)/sizeof(buffer[0]); | |
1670 | while(true) | |
1671 | { | |
1672 | stream.avail_out = buffersize; | |
1673 | stream.next_out = buffer; | |
1674 | err = lzma_code(&stream, LZMA_FINISH); | |
1675 | if (err != LZMA_OK && err != LZMA_STREAM_END) | |
1676 | { | |
1677 | _error->Error("~LZMAFILE: Compress finalisation failed"); | |
1678 | break; | |
1679 | } | |
1680 | size_t const n = buffersize - stream.avail_out; | |
1681 | if (n && fwrite(buffer, 1, n, file) != n) | |
1682 | { | |
1683 | _error->Errno("~LZMAFILE",_("Write error")); | |
1684 | break; | |
1685 | } | |
1686 | if (err == LZMA_STREAM_END) | |
1687 | break; | |
1688 | } | |
1689 | } | |
1690 | lzma_end(&stream); | |
1691 | fclose(file); | |
1692 | } | |
1693 | }; | |
1694 | LZMAFILE* lzma; | |
7a68effc DK |
1695 | static uint32_t findXZlevel(std::vector<std::string> const &Args) |
1696 | { | |
1697 | for (auto a = Args.rbegin(); a != Args.rend(); ++a) | |
1698 | if (a->empty() == false && (*a)[0] == '-' && (*a)[1] != '-') | |
1699 | { | |
1700 | auto const number = a->find_last_of("0123456789"); | |
1701 | if (number == std::string::npos) | |
1702 | continue; | |
1703 | auto const extreme = a->find("e", number); | |
1704 | uint32_t level = (extreme != std::string::npos) ? LZMA_PRESET_EXTREME : 0; | |
1705 | switch ((*a)[number]) | |
1706 | { | |
1707 | case '0': return level | 0; | |
1708 | case '1': return level | 1; | |
1709 | case '2': return level | 2; | |
1710 | case '3': return level | 3; | |
1711 | case '4': return level | 4; | |
1712 | case '5': return level | 5; | |
1713 | case '6': return level | 6; | |
1714 | case '7': return level | 7; | |
1715 | case '8': return level | 8; | |
1716 | case '9': return level | 9; | |
1717 | } | |
1718 | } | |
1719 | return 6; | |
1720 | } | |
fa89055f DK |
1721 | public: |
1722 | virtual bool InternalOpen(int const iFd, unsigned int const Mode) override | |
1723 | { | |
1724 | if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite) | |
1725 | return filefd->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd->FileName.c_str()); | |
1726 | ||
1727 | if (lzma == nullptr) | |
1728 | lzma = new LzmaFileFdPrivate::LZMAFILE; | |
1729 | if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) | |
1730 | lzma->file = fdopen(iFd, "w"); | |
1731 | else | |
1732 | lzma->file = fdopen(iFd, "r"); | |
1733 | filefd->Flags |= FileFd::Compressed; | |
1734 | if (lzma->file == nullptr) | |
1735 | return false; | |
1736 | ||
fa89055f DK |
1737 | lzma_stream tmp_stream = LZMA_STREAM_INIT; |
1738 | lzma->stream = tmp_stream; | |
1739 | ||
1740 | if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) | |
1741 | { | |
7a68effc | 1742 | uint32_t const xzlevel = findXZlevel(compressor.CompressArgs); |
fa89055f DK |
1743 | if (compressor.Name == "xz") |
1744 | { | |
885a1ffd | 1745 | if (lzma_easy_encoder(&lzma->stream, xzlevel, LZMA_CHECK_CRC64) != LZMA_OK) |
fa89055f DK |
1746 | return false; |
1747 | } | |
1748 | else | |
1749 | { | |
1750 | lzma_options_lzma options; | |
1751 | lzma_lzma_preset(&options, xzlevel); | |
1752 | if (lzma_alone_encoder(&lzma->stream, &options) != LZMA_OK) | |
1753 | return false; | |
1754 | } | |
1755 | lzma->compressing = true; | |
1756 | } | |
1757 | else | |
1758 | { | |
7a68effc | 1759 | uint64_t const memlimit = UINT64_MAX; |
fa89055f DK |
1760 | if (compressor.Name == "xz") |
1761 | { | |
1762 | if (lzma_auto_decoder(&lzma->stream, memlimit, 0) != LZMA_OK) | |
1763 | return false; | |
1764 | } | |
1765 | else | |
1766 | { | |
1767 | if (lzma_alone_decoder(&lzma->stream, memlimit) != LZMA_OK) | |
1768 | return false; | |
1769 | } | |
1770 | lzma->compressing = false; | |
1771 | } | |
1772 | return true; | |
1773 | } | |
f63123c3 | 1774 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override |
fa89055f DK |
1775 | { |
1776 | ssize_t Res; | |
1777 | if (lzma->eof == true) | |
1778 | return 0; | |
1779 | ||
1780 | lzma->stream.next_out = (uint8_t *) To; | |
1781 | lzma->stream.avail_out = Size; | |
1782 | if (lzma->stream.avail_in == 0) | |
1783 | { | |
1784 | lzma->stream.next_in = lzma->buffer; | |
1785 | lzma->stream.avail_in = fread(lzma->buffer, 1, sizeof(lzma->buffer)/sizeof(lzma->buffer[0]), lzma->file); | |
1786 | } | |
1787 | lzma->err = lzma_code(&lzma->stream, LZMA_RUN); | |
1788 | if (lzma->err == LZMA_STREAM_END) | |
1789 | { | |
1790 | lzma->eof = true; | |
1791 | Res = Size - lzma->stream.avail_out; | |
1792 | } | |
1793 | else if (lzma->err != LZMA_OK) | |
1794 | { | |
1795 | Res = -1; | |
1796 | errno = 0; | |
1797 | } | |
1798 | else | |
1799 | { | |
1800 | Res = Size - lzma->stream.avail_out; | |
1801 | if (Res == 0) | |
1802 | { | |
1803 | // lzma run was okay, but produced no output… | |
1804 | Res = -1; | |
1805 | errno = EINTR; | |
1806 | } | |
1807 | } | |
1808 | return Res; | |
1809 | } | |
1810 | virtual bool InternalReadError() override | |
1811 | { | |
1812 | return filefd->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma->err); | |
1813 | } | |
1814 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override | |
1815 | { | |
1816 | lzma->stream.next_in = (uint8_t *)From; | |
1817 | lzma->stream.avail_in = Size; | |
1818 | lzma->stream.next_out = lzma->buffer; | |
1819 | lzma->stream.avail_out = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]); | |
1820 | lzma->err = lzma_code(&lzma->stream, LZMA_RUN); | |
1821 | if (lzma->err != LZMA_OK) | |
1822 | return -1; | |
1823 | size_t const n = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]) - lzma->stream.avail_out; | |
1824 | size_t const m = (n == 0) ? 0 : fwrite(lzma->buffer, 1, n, lzma->file); | |
1825 | if (m != n) | |
1826 | return -1; | |
1827 | else | |
1828 | return Size - lzma->stream.avail_in; | |
1829 | } | |
1830 | virtual bool InternalWriteError() override | |
1831 | { | |
1832 | return filefd->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma->err); | |
1833 | } | |
1834 | virtual bool InternalStream() const override { return true; } | |
1835 | virtual bool InternalClose(std::string const &) override | |
1836 | { | |
1837 | delete lzma; | |
1838 | lzma = nullptr; | |
1839 | return true; | |
1840 | } | |
1841 | ||
11755147 | 1842 | explicit LzmaFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), lzma(nullptr) {} |
fa89055f | 1843 | virtual ~LzmaFileFdPrivate() { InternalClose(""); } |
4239dbca | 1844 | #endif |
fa89055f DK |
1845 | }; |
1846 | /*}}}*/ | |
65ac6aad | 1847 | class APT_HIDDEN PipedFileFdPrivate: public FileFdPrivate /*{{{*/ |
fa89055f DK |
1848 | /* if we don't have a specific class dealing with library calls, we (un)compress |
1849 | by executing a specified binary and pipe in/out what we need */ | |
1850 | { | |
1851 | public: | |
1852 | virtual bool InternalOpen(int const, unsigned int const Mode) override | |
1853 | { | |
1854 | // collect zombies here in case we reopen | |
1855 | if (compressor_pid > 0) | |
1856 | ExecWait(compressor_pid, "FileFdCompressor", true); | |
1857 | ||
1858 | if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite) | |
1859 | return filefd->FileFdError("ReadWrite mode is not supported for file %s", filefd->FileName.c_str()); | |
4239dbca | 1860 | |
fa89055f DK |
1861 | bool const Comp = (Mode & FileFd::WriteOnly) == FileFd::WriteOnly; |
1862 | if (Comp == false) | |
1863 | { | |
1864 | // Handle 'decompression' of empty files | |
1865 | struct stat Buf; | |
1866 | fstat(filefd->iFd, &Buf); | |
1867 | if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false) | |
1868 | return true; | |
1869 | ||
1870 | // We don't need the file open - instead let the compressor open it | |
1871 | // as he properly knows better how to efficiently read from 'his' file | |
1872 | if (filefd->FileName.empty() == false) | |
1873 | { | |
1874 | close(filefd->iFd); | |
1875 | filefd->iFd = -1; | |
1876 | } | |
1877 | } | |
1878 | ||
1879 | // Create a data pipe | |
1880 | int Pipe[2] = {-1,-1}; | |
1881 | if (pipe(Pipe) != 0) | |
1882 | return filefd->FileFdErrno("pipe",_("Failed to create subprocess IPC")); | |
1883 | for (int J = 0; J != 2; J++) | |
1884 | SetCloseExec(Pipe[J],true); | |
1885 | ||
1886 | compressed_fd = filefd->iFd; | |
1d68256d | 1887 | set_is_pipe(true); |
fa89055f DK |
1888 | |
1889 | if (Comp == true) | |
1890 | filefd->iFd = Pipe[1]; | |
1891 | else | |
1892 | filefd->iFd = Pipe[0]; | |
1893 | ||
1894 | // The child.. | |
1895 | compressor_pid = ExecFork(); | |
1896 | if (compressor_pid == 0) | |
1897 | { | |
1898 | if (Comp == true) | |
1899 | { | |
1900 | dup2(compressed_fd,STDOUT_FILENO); | |
1901 | dup2(Pipe[0],STDIN_FILENO); | |
1902 | } | |
1903 | else | |
1904 | { | |
1905 | if (compressed_fd != -1) | |
1906 | dup2(compressed_fd,STDIN_FILENO); | |
1907 | dup2(Pipe[1],STDOUT_FILENO); | |
1908 | } | |
1909 | int const nullfd = open("/dev/null", O_WRONLY); | |
1910 | if (nullfd != -1) | |
1911 | { | |
1912 | dup2(nullfd,STDERR_FILENO); | |
1913 | close(nullfd); | |
1914 | } | |
1915 | ||
1916 | SetCloseExec(STDOUT_FILENO,false); | |
1917 | SetCloseExec(STDIN_FILENO,false); | |
1918 | ||
1919 | std::vector<char const*> Args; | |
1920 | Args.push_back(compressor.Binary.c_str()); | |
1921 | std::vector<std::string> const * const addArgs = | |
1922 | (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs); | |
1923 | for (std::vector<std::string>::const_iterator a = addArgs->begin(); | |
1924 | a != addArgs->end(); ++a) | |
1925 | Args.push_back(a->c_str()); | |
1926 | if (Comp == false && filefd->FileName.empty() == false) | |
1927 | { | |
1928 | // commands not needing arguments, do not need to be told about using standard output | |
1929 | // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this | |
1930 | if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false) | |
1931 | Args.push_back("--stdout"); | |
1932 | if (filefd->TemporaryFileName.empty() == false) | |
1933 | Args.push_back(filefd->TemporaryFileName.c_str()); | |
1934 | else | |
1935 | Args.push_back(filefd->FileName.c_str()); | |
1936 | } | |
1937 | Args.push_back(NULL); | |
1938 | ||
1939 | execvp(Args[0],(char **)&Args[0]); | |
1940 | cerr << _("Failed to exec compressor ") << Args[0] << endl; | |
1941 | _exit(100); | |
1942 | } | |
1943 | if (Comp == true) | |
1944 | close(Pipe[0]); | |
1945 | else | |
1946 | close(Pipe[1]); | |
1947 | ||
1948 | return true; | |
1949 | } | |
f63123c3 | 1950 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override |
fa89055f DK |
1951 | { |
1952 | return read(filefd->iFd, To, Size); | |
1953 | } | |
1954 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override | |
1955 | { | |
1956 | return write(filefd->iFd, From, Size); | |
1957 | } | |
1958 | virtual bool InternalClose(std::string const &) override | |
1959 | { | |
1960 | bool Ret = true; | |
1961 | if (compressor_pid > 0) | |
1962 | Ret &= ExecWait(compressor_pid, "FileFdCompressor", true); | |
1963 | compressor_pid = -1; | |
1964 | return Ret; | |
1965 | } | |
11755147 | 1966 | explicit PipedFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {} |
fa89055f DK |
1967 | virtual ~PipedFileFdPrivate() { InternalClose(""); } |
1968 | }; | |
1969 | /*}}}*/ | |
65ac6aad | 1970 | class APT_HIDDEN DirectFileFdPrivate: public FileFdPrivate /*{{{*/ |
fa89055f DK |
1971 | { |
1972 | public: | |
1973 | virtual bool InternalOpen(int const, unsigned int const) override { return true; } | |
f63123c3 | 1974 | virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override |
fa89055f DK |
1975 | { |
1976 | return read(filefd->iFd, To, Size); | |
1977 | } | |
fa89055f DK |
1978 | virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override |
1979 | { | |
f63123c3 | 1980 | // files opened read+write are strange and only really "supported" for direct files |
83e22e26 | 1981 | if (buffer.size() != 0) |
f63123c3 | 1982 | { |
83e22e26 JAK |
1983 | lseek(filefd->iFd, -buffer.size(), SEEK_CUR); |
1984 | buffer.reset(); | |
f63123c3 | 1985 | } |
fa89055f DK |
1986 | return write(filefd->iFd, From, Size); |
1987 | } | |
1988 | virtual bool InternalSeek(unsigned long long const To) override | |
1989 | { | |
1990 | off_t const res = lseek(filefd->iFd, To, SEEK_SET); | |
1991 | if (res != (off_t)To) | |
1992 | return filefd->FileFdError("Unable to seek to %llu", To); | |
1993 | seekpos = To; | |
83e22e26 | 1994 | buffer.reset(); |
fa89055f DK |
1995 | return true; |
1996 | } | |
1997 | virtual bool InternalSkip(unsigned long long Over) override | |
1998 | { | |
83e22e26 | 1999 | if (Over >= buffer.size()) |
f63123c3 | 2000 | { |
83e22e26 JAK |
2001 | Over -= buffer.size(); |
2002 | buffer.reset(); | |
f63123c3 DK |
2003 | } |
2004 | else | |
2005 | { | |
83e22e26 | 2006 | buffer.bufferstart += Over; |
f63123c3 DK |
2007 | return true; |
2008 | } | |
2009 | if (Over == 0) | |
2010 | return true; | |
fa89055f DK |
2011 | off_t const res = lseek(filefd->iFd, Over, SEEK_CUR); |
2012 | if (res < 0) | |
2013 | return filefd->FileFdError("Unable to seek ahead %llu",Over); | |
2014 | seekpos = res; | |
2015 | return true; | |
2016 | } | |
2017 | virtual bool InternalTruncate(unsigned long long const To) override | |
2018 | { | |
83e22e26 | 2019 | if (buffer.size() != 0) |
f63123c3 DK |
2020 | { |
2021 | unsigned long long const seekpos = lseek(filefd->iFd, 0, SEEK_CUR); | |
83e22e26 JAK |
2022 | if ((seekpos - buffer.size()) >= To) |
2023 | buffer.reset(); | |
f63123c3 | 2024 | else if (seekpos >= To) |
83e22e26 | 2025 | buffer.bufferend = (To - seekpos) + buffer.bufferstart; |
f63123c3 | 2026 | else |
83e22e26 | 2027 | buffer.reset(); |
f63123c3 | 2028 | } |
fa89055f DK |
2029 | if (ftruncate(filefd->iFd, To) != 0) |
2030 | return filefd->FileFdError("Unable to truncate to %llu",To); | |
2031 | return true; | |
2032 | } | |
2033 | virtual unsigned long long InternalTell() override | |
2034 | { | |
83e22e26 | 2035 | return lseek(filefd->iFd,0,SEEK_CUR) - buffer.size(); |
fa89055f DK |
2036 | } |
2037 | virtual unsigned long long InternalSize() override | |
2038 | { | |
2039 | return filefd->FileSize(); | |
2040 | } | |
2041 | virtual bool InternalClose(std::string const &) override { return true; } | |
2042 | virtual bool InternalAlwaysAutoClose() const override { return false; } | |
2043 | ||
11755147 | 2044 | explicit DirectFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {} |
fa89055f | 2045 | virtual ~DirectFileFdPrivate() { InternalClose(""); } |
4239dbca DK |
2046 | }; |
2047 | /*}}}*/ | |
6c55f07a DK |
2048 | // FileFd Constructors /*{{{*/ |
2049 | FileFd::FileFd(std::string FileName,unsigned int const Mode,unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL) | |
2050 | { | |
2051 | Open(FileName,Mode, None, AccessMode); | |
2052 | } | |
2053 | FileFd::FileFd(std::string FileName,unsigned int const Mode, CompressMode Compress, unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL) | |
2054 | { | |
2055 | Open(FileName,Mode, Compress, AccessMode); | |
2056 | } | |
2057 | FileFd::FileFd() : iFd(-1), Flags(AutoClose), d(NULL) {} | |
2058 | FileFd::FileFd(int const Fd, unsigned int const Mode, CompressMode Compress) : iFd(-1), Flags(0), d(NULL) | |
2059 | { | |
2060 | OpenDescriptor(Fd, Mode, Compress); | |
2061 | } | |
2062 | FileFd::FileFd(int const Fd, bool const AutoClose) : iFd(-1), Flags(0), d(NULL) | |
2063 | { | |
2064 | OpenDescriptor(Fd, ReadWrite, None, AutoClose); | |
2065 | } | |
2066 | /*}}}*/ | |
13d87e2e | 2067 | // FileFd::Open - Open a file /*{{{*/ |
578bfd0a AL |
2068 | // --------------------------------------------------------------------- |
2069 | /* The most commonly used open mode combinations are given with Mode */ | |
e5f3f8c1 | 2070 | bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode) |
578bfd0a | 2071 | { |
257e8d66 | 2072 | if (Mode == ReadOnlyGzip) |
e5f3f8c1 | 2073 | return Open(FileName, ReadOnly, Gzip, AccessMode); |
257e8d66 | 2074 | |
468720c5 | 2075 | if (Compress == Auto && (Mode & WriteOnly) == WriteOnly) |
ae635e3c | 2076 | return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str()); |
257e8d66 | 2077 | |
468720c5 DK |
2078 | std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors(); |
2079 | std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin(); | |
2080 | if (Compress == Auto) | |
2081 | { | |
468720c5 DK |
2082 | for (; compressor != compressors.end(); ++compressor) |
2083 | { | |
e788a834 | 2084 | std::string file = FileName + compressor->Extension; |
468720c5 DK |
2085 | if (FileExists(file) == false) |
2086 | continue; | |
2087 | FileName = file; | |
468720c5 DK |
2088 | break; |
2089 | } | |
2090 | } | |
2091 | else if (Compress == Extension) | |
2092 | { | |
52b47296 DK |
2093 | std::string::size_type const found = FileName.find_last_of('.'); |
2094 | std::string ext; | |
2095 | if (found != std::string::npos) | |
2096 | { | |
2097 | ext = FileName.substr(found); | |
2098 | if (ext == ".new" || ext == ".bak") | |
2099 | { | |
2100 | std::string::size_type const found2 = FileName.find_last_of('.', found - 1); | |
2101 | if (found2 != std::string::npos) | |
2102 | ext = FileName.substr(found2, found - found2); | |
2103 | else | |
2104 | ext.clear(); | |
2105 | } | |
2106 | } | |
aee1aac6 DK |
2107 | for (; compressor != compressors.end(); ++compressor) |
2108 | if (ext == compressor->Extension) | |
2109 | break; | |
2110 | // no matching extension - assume uncompressed (imagine files like 'example.org_Packages') | |
2111 | if (compressor == compressors.end()) | |
2112 | for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor) | |
2113 | if (compressor->Name == ".") | |
468720c5 | 2114 | break; |
468720c5 | 2115 | } |
aee1aac6 | 2116 | else |
468720c5 DK |
2117 | { |
2118 | std::string name; | |
2119 | switch (Compress) | |
2120 | { | |
aee1aac6 | 2121 | case None: name = "."; break; |
468720c5 DK |
2122 | case Gzip: name = "gzip"; break; |
2123 | case Bzip2: name = "bzip2"; break; | |
2124 | case Lzma: name = "lzma"; break; | |
2125 | case Xz: name = "xz"; break; | |
e3fbd54c | 2126 | case Lz4: name = "lz4"; break; |
aee1aac6 DK |
2127 | case Auto: |
2128 | case Extension: | |
52b47296 | 2129 | // Unreachable |
ae635e3c | 2130 | return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str()); |
468720c5 DK |
2131 | } |
2132 | for (; compressor != compressors.end(); ++compressor) | |
2133 | if (compressor->Name == name) | |
2134 | break; | |
aee1aac6 | 2135 | if (compressor == compressors.end()) |
ae635e3c | 2136 | return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str()); |
468720c5 DK |
2137 | } |
2138 | ||
aee1aac6 | 2139 | if (compressor == compressors.end()) |
ae635e3c | 2140 | return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str()); |
e5f3f8c1 | 2141 | return Open(FileName, Mode, *compressor, AccessMode); |
aee1aac6 | 2142 | } |
e5f3f8c1 | 2143 | bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode) |
aee1aac6 DK |
2144 | { |
2145 | Close(); | |
aee1aac6 DK |
2146 | Flags = AutoClose; |
2147 | ||
2148 | if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0) | |
ae635e3c | 2149 | return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str()); |
aee1aac6 | 2150 | if ((Mode & ReadWrite) == 0) |
ae635e3c | 2151 | return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str()); |
468720c5 | 2152 | |
cd46d4eb DK |
2153 | unsigned int OpenMode = Mode; |
2154 | if (FileName == "/dev/null") | |
2155 | OpenMode = OpenMode & ~(Atomic | Exclusive | Create | Empty); | |
2156 | ||
2157 | if ((OpenMode & Atomic) == Atomic) | |
257e8d66 DK |
2158 | { |
2159 | Flags |= Replace; | |
257e8d66 | 2160 | } |
cd46d4eb | 2161 | else if ((OpenMode & (Exclusive | Create)) == (Exclusive | Create)) |
257e8d66 DK |
2162 | { |
2163 | // for atomic, this will be done by rename in Close() | |
ce1f3a2c | 2164 | RemoveFile("FileFd::Open", FileName); |
257e8d66 | 2165 | } |
cd46d4eb | 2166 | if ((OpenMode & Empty) == Empty) |
578bfd0a | 2167 | { |
257e8d66 DK |
2168 | struct stat Buf; |
2169 | if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode)) | |
ce1f3a2c | 2170 | RemoveFile("FileFd::Open", FileName); |
257e8d66 | 2171 | } |
c4fc2fd7 | 2172 | |
561f860a | 2173 | int fileflags = 0; |
cd46d4eb | 2174 | #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE |
561f860a DK |
2175 | if_FLAGGED_SET(ReadWrite, O_RDWR); |
2176 | else if_FLAGGED_SET(ReadOnly, O_RDONLY); | |
2177 | else if_FLAGGED_SET(WriteOnly, O_WRONLY); | |
4a9db827 | 2178 | |
561f860a DK |
2179 | if_FLAGGED_SET(Create, O_CREAT); |
2180 | if_FLAGGED_SET(Empty, O_TRUNC); | |
2181 | if_FLAGGED_SET(Exclusive, O_EXCL); | |
561f860a | 2182 | #undef if_FLAGGED_SET |
52b47296 | 2183 | |
cd46d4eb | 2184 | if ((OpenMode & Atomic) == Atomic) |
7335eebe AGM |
2185 | { |
2186 | char *name = strdup((FileName + ".XXXXXX").c_str()); | |
2187 | ||
dc545c0b | 2188 | if((iFd = mkstemp(name)) == -1) |
7335eebe AGM |
2189 | { |
2190 | free(name); | |
98b69f9d | 2191 | return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str()); |
7335eebe AGM |
2192 | } |
2193 | ||
2194 | TemporaryFileName = string(name); | |
7335eebe | 2195 | free(name); |
dc545c0b | 2196 | |
230e69d7 DK |
2197 | // umask() will always set the umask and return the previous value, so |
2198 | // we first set the umask and then reset it to the old value | |
2199 | mode_t const CurrentUmask = umask(0); | |
2200 | umask(CurrentUmask); | |
2201 | // calculate the actual file permissions (just like open/creat) | |
2202 | mode_t const FilePermissions = (AccessMode & ~CurrentUmask); | |
2203 | ||
2204 | if(fchmod(iFd, FilePermissions) == -1) | |
dc545c0b | 2205 | return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str()); |
7335eebe | 2206 | } |
468720c5 | 2207 | else |
230e69d7 | 2208 | iFd = open(FileName.c_str(), fileflags, AccessMode); |
468720c5 | 2209 | |
b711c01e | 2210 | this->FileName = FileName; |
cd46d4eb | 2211 | if (iFd == -1 || OpenInternDescriptor(OpenMode, compressor) == false) |
561f860a | 2212 | { |
468720c5 | 2213 | if (iFd != -1) |
fc81e8f2 | 2214 | { |
561f860a DK |
2215 | close (iFd); |
2216 | iFd = -1; | |
fc81e8f2 | 2217 | } |
ae635e3c | 2218 | return FileFdErrno("open",_("Could not open file %s"), FileName.c_str()); |
257e8d66 | 2219 | } |
578bfd0a | 2220 | |
13d87e2e AL |
2221 | SetCloseExec(iFd,true); |
2222 | return true; | |
578bfd0a | 2223 | } |
257e8d66 DK |
2224 | /*}}}*/ |
2225 | // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/ | |
52b47296 | 2226 | bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose) |
aee1aac6 DK |
2227 | { |
2228 | std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors(); | |
2229 | std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin(); | |
2230 | std::string name; | |
bce778a3 MV |
2231 | |
2232 | // compat with the old API | |
2233 | if (Mode == ReadOnlyGzip && Compress == None) | |
2234 | Compress = Gzip; | |
2235 | ||
aee1aac6 DK |
2236 | switch (Compress) |
2237 | { | |
2238 | case None: name = "."; break; | |
2239 | case Gzip: name = "gzip"; break; | |
2240 | case Bzip2: name = "bzip2"; break; | |
2241 | case Lzma: name = "lzma"; break; | |
2242 | case Xz: name = "xz"; break; | |
e3fbd54c | 2243 | case Lz4: name = "lz4"; break; |
aee1aac6 DK |
2244 | case Auto: |
2245 | case Extension: | |
f97bb523 DK |
2246 | if (AutoClose == true && Fd != -1) |
2247 | close(Fd); | |
ae635e3c | 2248 | return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd); |
aee1aac6 DK |
2249 | } |
2250 | for (; compressor != compressors.end(); ++compressor) | |
2251 | if (compressor->Name == name) | |
2252 | break; | |
2253 | if (compressor == compressors.end()) | |
f97bb523 DK |
2254 | { |
2255 | if (AutoClose == true && Fd != -1) | |
2256 | close(Fd); | |
ae635e3c | 2257 | return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str()); |
f97bb523 | 2258 | } |
aee1aac6 DK |
2259 | return OpenDescriptor(Fd, Mode, *compressor, AutoClose); |
2260 | } | |
52b47296 | 2261 | bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose) |
144c0969 JAK |
2262 | { |
2263 | Close(); | |
2264 | Flags = (AutoClose) ? FileFd::AutoClose : 0; | |
84baaae9 | 2265 | iFd = Fd; |
b711c01e | 2266 | this->FileName = ""; |
84baaae9 | 2267 | if (OpenInternDescriptor(Mode, compressor) == false) |
468720c5 | 2268 | { |
f97bb523 | 2269 | if (iFd != -1 && ( |
84baaae9 | 2270 | (Flags & Compressed) == Compressed || |
f97bb523 DK |
2271 | AutoClose == true)) |
2272 | { | |
468720c5 | 2273 | close (iFd); |
f97bb523 DK |
2274 | iFd = -1; |
2275 | } | |
2276 | return FileFdError(_("Could not open file descriptor %d"), Fd); | |
144c0969 | 2277 | } |
144c0969 | 2278 | return true; |
468720c5 | 2279 | } |
52b47296 | 2280 | bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor) |
468720c5 | 2281 | { |
84baaae9 DK |
2282 | if (iFd == -1) |
2283 | return false; | |
ff477ee1 | 2284 | |
fa89055f DK |
2285 | if (d != nullptr) |
2286 | d->InternalClose(FileName); | |
2287 | ||
2288 | if (d == nullptr) | |
2289 | { | |
2290 | if (false) | |
2291 | /* dummy so that the rest can be 'else if's */; | |
2292 | #define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \ | |
2293 | else if (compressor.Name == NAME) \ | |
2294 | d = new CONSTRUCTOR(this) | |
69d6988a | 2295 | #ifdef HAVE_ZLIB |
fa89055f | 2296 | APT_COMPRESS_INIT("gzip", GzipFileFdPrivate); |
69d6988a DK |
2297 | #endif |
2298 | #ifdef HAVE_BZ2 | |
fa89055f | 2299 | APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate); |
69d6988a | 2300 | #endif |
7f350a37 | 2301 | #ifdef HAVE_LZMA |
fa89055f DK |
2302 | APT_COMPRESS_INIT("xz", LzmaFileFdPrivate); |
2303 | APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate); | |
7f350a37 | 2304 | #endif |
e3fbd54c JAK |
2305 | #ifdef HAVE_LZ4 |
2306 | APT_COMPRESS_INIT("lz4", Lz4FileFdPrivate); | |
2307 | #endif | |
69d6988a | 2308 | #undef APT_COMPRESS_INIT |
fa89055f DK |
2309 | else if (compressor.Name == "." || compressor.Binary.empty() == true) |
2310 | d = new DirectFileFdPrivate(this); | |
2311 | else | |
2312 | d = new PipedFileFdPrivate(this); | |
69d6988a | 2313 | |
88749b5d JAK |
2314 | if (Mode & BufferedWrite) |
2315 | d = new BufferedWriteFileFdPrivate(d); | |
2316 | ||
1d68256d JAK |
2317 | d->set_openmode(Mode); |
2318 | d->set_compressor(compressor); | |
fa89055f | 2319 | if ((Flags & AutoClose) != AutoClose && d->InternalAlwaysAutoClose()) |
84baaae9 DK |
2320 | { |
2321 | // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well | |
2322 | int const internFd = dup(iFd); | |
2323 | if (internFd == -1) | |
2324 | return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd); | |
2325 | iFd = internFd; | |
2326 | } | |
561f860a | 2327 | } |
fa89055f | 2328 | return d->InternalOpen(iFd, Mode); |
144c0969 | 2329 | } |
578bfd0a | 2330 | /*}}}*/ |
8e06abb2 | 2331 | // FileFd::~File - Closes the file /*{{{*/ |
578bfd0a AL |
2332 | // --------------------------------------------------------------------- |
2333 | /* If the proper modes are selected then we close the Fd and possibly | |
2334 | unlink the file on error. */ | |
8e06abb2 | 2335 | FileFd::~FileFd() |
578bfd0a AL |
2336 | { |
2337 | Close(); | |
500400fe | 2338 | if (d != NULL) |
fa89055f | 2339 | d->InternalClose(FileName); |
96ab3c6f MV |
2340 | delete d; |
2341 | d = NULL; | |
578bfd0a AL |
2342 | } |
2343 | /*}}}*/ | |
8e06abb2 | 2344 | // FileFd::Read - Read a bit of the file /*{{{*/ |
578bfd0a | 2345 | // --------------------------------------------------------------------- |
1e3f4083 | 2346 | /* We are careful to handle interruption by a signal while reading |
b0db36b1 | 2347 | gracefully. */ |
650faab0 | 2348 | bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual) |
578bfd0a | 2349 | { |
fa89055f DK |
2350 | if (d == nullptr) |
2351 | return false; | |
39e77e45 | 2352 | ssize_t Res = 1; |
b0db36b1 | 2353 | errno = 0; |
f604cf55 AL |
2354 | if (Actual != 0) |
2355 | *Actual = 0; | |
699b209e | 2356 | *((char *)To) = '\0'; |
39e77e45 | 2357 | while (Res > 0 && Size > 0) |
578bfd0a | 2358 | { |
fa89055f | 2359 | Res = d->InternalRead(To, Size); |
b711c01e | 2360 | |
b0db36b1 AL |
2361 | if (Res < 0) |
2362 | { | |
b711c01e | 2363 | if (errno == EINTR) |
c4b113e6 DK |
2364 | { |
2365 | // trick the while-loop into running again | |
2366 | Res = 1; | |
2367 | errno = 0; | |
b711c01e | 2368 | continue; |
c4b113e6 | 2369 | } |
fa89055f | 2370 | return d->InternalReadError(); |
b0db36b1 | 2371 | } |
578bfd0a | 2372 | |
b0db36b1 AL |
2373 | To = (char *)To + Res; |
2374 | Size -= Res; | |
ff477ee1 | 2375 | if (d != NULL) |
1d68256d | 2376 | d->set_seekpos(d->get_seekpos() + Res); |
f604cf55 AL |
2377 | if (Actual != 0) |
2378 | *Actual += Res; | |
b0db36b1 | 2379 | } |
b0db36b1 AL |
2380 | |
2381 | if (Size == 0) | |
2382 | return true; | |
2383 | ||
ddc1d8d0 | 2384 | // Eof handling |
f604cf55 | 2385 | if (Actual != 0) |
ddc1d8d0 AL |
2386 | { |
2387 | Flags |= HitEof; | |
2388 | return true; | |
2389 | } | |
ae635e3c DK |
2390 | |
2391 | return FileFdError(_("read, still have %llu to read but none left"), Size); | |
578bfd0a AL |
2392 | } |
2393 | /*}}}*/ | |
032bd56f DK |
2394 | // FileFd::ReadLine - Read a complete line from the file /*{{{*/ |
2395 | // --------------------------------------------------------------------- | |
fa89055f | 2396 | /* Beware: This method can be quite slow for big buffers on UNcompressed |
032bd56f DK |
2397 | files because of the naive implementation! */ |
2398 | char* FileFd::ReadLine(char *To, unsigned long long const Size) | |
2399 | { | |
699b209e | 2400 | *To = '\0'; |
fa89055f DK |
2401 | if (d == nullptr) |
2402 | return nullptr; | |
2403 | return d->InternalReadLine(To, Size); | |
032bd56f DK |
2404 | } |
2405 | /*}}}*/ | |
766761fd JAK |
2406 | // FileFd::Flush - Flush the file /*{{{*/ |
2407 | bool FileFd::Flush() | |
2408 | { | |
2409 | if (d == nullptr) | |
2410 | return true; | |
2411 | ||
2412 | return d->InternalFlush(); | |
2413 | } | |
2414 | /*}}}*/ | |
8e06abb2 | 2415 | // FileFd::Write - Write to the file /*{{{*/ |
650faab0 | 2416 | bool FileFd::Write(const void *From,unsigned long long Size) |
578bfd0a | 2417 | { |
fa89055f DK |
2418 | if (d == nullptr) |
2419 | return false; | |
5df91bc7 | 2420 | ssize_t Res = 1; |
b0db36b1 | 2421 | errno = 0; |
5df91bc7 | 2422 | while (Res > 0 && Size > 0) |
578bfd0a | 2423 | { |
fa89055f | 2424 | Res = d->InternalWrite(From, Size); |
b0db36b1 AL |
2425 | if (Res < 0 && errno == EINTR) |
2426 | continue; | |
2427 | if (Res < 0) | |
fa89055f DK |
2428 | return d->InternalWriteError(); |
2429 | ||
cf4ff3b7 | 2430 | From = (char const *)From + Res; |
b0db36b1 | 2431 | Size -= Res; |
ff477ee1 | 2432 | if (d != NULL) |
1d68256d | 2433 | d->set_seekpos(d->get_seekpos() + Res); |
578bfd0a | 2434 | } |
fa89055f | 2435 | |
b0db36b1 AL |
2436 | if (Size == 0) |
2437 | return true; | |
ae635e3c DK |
2438 | |
2439 | return FileFdError(_("write, still have %llu to write but couldn't"), Size); | |
d68d65ad DK |
2440 | } |
2441 | bool FileFd::Write(int Fd, const void *From, unsigned long long Size) | |
2442 | { | |
5df91bc7 | 2443 | ssize_t Res = 1; |
d68d65ad | 2444 | errno = 0; |
5df91bc7 | 2445 | while (Res > 0 && Size > 0) |
d68d65ad DK |
2446 | { |
2447 | Res = write(Fd,From,Size); | |
2448 | if (Res < 0 && errno == EINTR) | |
2449 | continue; | |
2450 | if (Res < 0) | |
2451 | return _error->Errno("write",_("Write error")); | |
2452 | ||
cf4ff3b7 | 2453 | From = (char const *)From + Res; |
d68d65ad DK |
2454 | Size -= Res; |
2455 | } | |
d68d65ad DK |
2456 | |
2457 | if (Size == 0) | |
2458 | return true; | |
2459 | ||
2460 | return _error->Error(_("write, still have %llu to write but couldn't"), Size); | |
578bfd0a AL |
2461 | } |
2462 | /*}}}*/ | |
8e06abb2 | 2463 | // FileFd::Seek - Seek in the file /*{{{*/ |
650faab0 | 2464 | bool FileFd::Seek(unsigned long long To) |
578bfd0a | 2465 | { |
fa89055f DK |
2466 | if (d == nullptr) |
2467 | return false; | |
bb93178b | 2468 | Flags &= ~HitEof; |
fa89055f | 2469 | return d->InternalSeek(To); |
727f18af AL |
2470 | } |
2471 | /*}}}*/ | |
fa89055f | 2472 | // FileFd::Skip - Skip over data in the file /*{{{*/ |
650faab0 | 2473 | bool FileFd::Skip(unsigned long long Over) |
727f18af | 2474 | { |
fa89055f DK |
2475 | if (d == nullptr) |
2476 | return false; | |
2477 | return d->InternalSkip(Over); | |
6d5dd02a AL |
2478 | } |
2479 | /*}}}*/ | |
fa89055f | 2480 | // FileFd::Truncate - Truncate the file /*{{{*/ |
650faab0 | 2481 | bool FileFd::Truncate(unsigned long long To) |
6d5dd02a | 2482 | { |
fa89055f DK |
2483 | if (d == nullptr) |
2484 | return false; | |
ad5051ef DK |
2485 | // truncating /dev/null is always successful - as we get an error otherwise |
2486 | if (To == 0 && FileName == "/dev/null") | |
2487 | return true; | |
fa89055f | 2488 | return d->InternalTruncate(To); |
578bfd0a AL |
2489 | } |
2490 | /*}}}*/ | |
7f25bdff AL |
2491 | // FileFd::Tell - Current seek position /*{{{*/ |
2492 | // --------------------------------------------------------------------- | |
2493 | /* */ | |
650faab0 | 2494 | unsigned long long FileFd::Tell() |
7f25bdff | 2495 | { |
fa89055f DK |
2496 | if (d == nullptr) |
2497 | return false; | |
2498 | off_t const Res = d->InternalTell(); | |
7f25bdff | 2499 | if (Res == (off_t)-1) |
ae635e3c | 2500 | FileFdErrno("lseek","Failed to determine the current file position"); |
1d68256d | 2501 | d->set_seekpos(Res); |
7f25bdff AL |
2502 | return Res; |
2503 | } | |
2504 | /*}}}*/ | |
8190b07a | 2505 | static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/ |
578bfd0a | 2506 | { |
1d68256d | 2507 | bool ispipe = (d != NULL && d->get_is_pipe() == true); |
6008b79a DK |
2508 | if (ispipe == false) |
2509 | { | |
2510 | if (fstat(iFd,&Buf) != 0) | |
8190b07a DK |
2511 | // higher-level code will generate more meaningful messages, |
2512 | // even translated this would be meaningless for users | |
2513 | return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd); | |
003c40d3 DK |
2514 | if (FileName.empty() == false) |
2515 | ispipe = S_ISFIFO(Buf.st_mode); | |
6008b79a | 2516 | } |
699b209e DK |
2517 | |
2518 | // for compressor pipes st_size is undefined and at 'best' zero | |
6008b79a | 2519 | if (ispipe == true) |
699b209e DK |
2520 | { |
2521 | // we set it here, too, as we get the info here for free | |
2522 | // in theory the Open-methods should take care of it already | |
ff477ee1 | 2523 | if (d != NULL) |
1d68256d | 2524 | d->set_is_pipe(true); |
699b209e | 2525 | if (stat(FileName.c_str(), &Buf) != 0) |
8190b07a DK |
2526 | return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str()); |
2527 | } | |
2528 | return true; | |
2529 | } | |
2530 | /*}}}*/ | |
2531 | // FileFd::FileSize - Return the size of the file /*{{{*/ | |
2532 | unsigned long long FileFd::FileSize() | |
2533 | { | |
2534 | struct stat Buf; | |
2535 | if (StatFileFd("file size", iFd, FileName, Buf, d) == false) | |
2536 | { | |
2537 | Flags |= Fail; | |
2538 | return 0; | |
699b209e | 2539 | } |
4260fd39 DK |
2540 | return Buf.st_size; |
2541 | } | |
2542 | /*}}}*/ | |
8190b07a DK |
2543 | // FileFd::ModificationTime - Return the time of last touch /*{{{*/ |
2544 | time_t FileFd::ModificationTime() | |
2545 | { | |
2546 | struct stat Buf; | |
2547 | if (StatFileFd("modification time", iFd, FileName, Buf, d) == false) | |
2548 | { | |
2549 | Flags |= Fail; | |
2550 | return 0; | |
2551 | } | |
2552 | return Buf.st_mtime; | |
2553 | } | |
2554 | /*}}}*/ | |
4260fd39 | 2555 | // FileFd::Size - Return the size of the content in the file /*{{{*/ |
650faab0 | 2556 | unsigned long long FileFd::Size() |
4260fd39 | 2557 | { |
fa89055f DK |
2558 | if (d == nullptr) |
2559 | return false; | |
2560 | return d->InternalSize(); | |
578bfd0a AL |
2561 | } |
2562 | /*}}}*/ | |
8e06abb2 | 2563 | // FileFd::Close - Close the file if the close flag is set /*{{{*/ |
578bfd0a AL |
2564 | // --------------------------------------------------------------------- |
2565 | /* */ | |
8e06abb2 | 2566 | bool FileFd::Close() |
578bfd0a | 2567 | { |
766761fd JAK |
2568 | if (Flush() == false) |
2569 | return false; | |
032bd56f DK |
2570 | if (iFd == -1) |
2571 | return true; | |
2572 | ||
578bfd0a AL |
2573 | bool Res = true; |
2574 | if ((Flags & AutoClose) == AutoClose) | |
d13c2d3f | 2575 | { |
500400fe DK |
2576 | if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0) |
2577 | Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str()); | |
2da8aae5 JAK |
2578 | } |
2579 | ||
2580 | if (d != NULL) | |
2581 | { | |
fa89055f | 2582 | Res &= d->InternalClose(FileName); |
2da8aae5 JAK |
2583 | delete d; |
2584 | d = NULL; | |
d13c2d3f | 2585 | } |
3010fb0e | 2586 | |
d3aac32e | 2587 | if ((Flags & Replace) == Replace) { |
3010fb0e | 2588 | if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0) |
62d073d9 DK |
2589 | Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str()); |
2590 | ||
fd3b761e | 2591 | FileName = TemporaryFileName; // for the unlink() below. |
257e8d66 | 2592 | TemporaryFileName.clear(); |
3010fb0e | 2593 | } |
62d073d9 DK |
2594 | |
2595 | iFd = -1; | |
2596 | ||
578bfd0a AL |
2597 | if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail && |
2598 | FileName.empty() == false) | |
ce1f3a2c | 2599 | Res &= RemoveFile("FileFd::Close", FileName); |
3010fb0e | 2600 | |
fbb89d94 DK |
2601 | if (Res == false) |
2602 | Flags |= Fail; | |
578bfd0a AL |
2603 | return Res; |
2604 | } | |
2605 | /*}}}*/ | |
b2e465d6 AL |
2606 | // FileFd::Sync - Sync the file /*{{{*/ |
2607 | // --------------------------------------------------------------------- | |
2608 | /* */ | |
2609 | bool FileFd::Sync() | |
2610 | { | |
b2e465d6 | 2611 | if (fsync(iFd) != 0) |
ae635e3c DK |
2612 | return FileFdErrno("sync",_("Problem syncing the file")); |
2613 | return true; | |
2614 | } | |
2615 | /*}}}*/ | |
2616 | // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/ | |
2617 | bool FileFd::FileFdErrno(const char *Function, const char *Description,...) | |
2618 | { | |
2619 | Flags |= Fail; | |
2620 | va_list args; | |
2621 | size_t msgSize = 400; | |
2622 | int const errsv = errno; | |
2623 | while (true) | |
fbb89d94 | 2624 | { |
ae635e3c DK |
2625 | va_start(args,Description); |
2626 | if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false) | |
2627 | break; | |
2628 | va_end(args); | |
fbb89d94 | 2629 | } |
ae635e3c DK |
2630 | return false; |
2631 | } | |
2632 | /*}}}*/ | |
2633 | // FileFd::FileFdError - set Fail and call _error->Error *{{{*/ | |
2634 | bool FileFd::FileFdError(const char *Description,...) { | |
2635 | Flags |= Fail; | |
2636 | va_list args; | |
2637 | size_t msgSize = 400; | |
2638 | while (true) | |
2639 | { | |
2640 | va_start(args,Description); | |
2641 | if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false) | |
2642 | break; | |
2643 | va_end(args); | |
2644 | } | |
2645 | return false; | |
b2e465d6 AL |
2646 | } |
2647 | /*}}}*/ | |
fa89055f | 2648 | gzFile FileFd::gzFd() { /*{{{*/ |
7f350a37 | 2649 | #ifdef HAVE_ZLIB |
fa89055f DK |
2650 | GzipFileFdPrivate * const gzipd = dynamic_cast<GzipFileFdPrivate*>(d); |
2651 | if (gzipd == nullptr) | |
2652 | return nullptr; | |
2653 | else | |
2654 | return gzipd->gz; | |
7f350a37 | 2655 | #else |
fa89055f | 2656 | return nullptr; |
7f350a37 DK |
2657 | #endif |
2658 | } | |
fa89055f | 2659 | /*}}}*/ |
8d01b9d6 | 2660 | |
f8aba23f | 2661 | // Glob - wrapper around "glob()" /*{{{*/ |
8d01b9d6 MV |
2662 | std::vector<std::string> Glob(std::string const &pattern, int flags) |
2663 | { | |
2664 | std::vector<std::string> result; | |
2665 | glob_t globbuf; | |
ec4835a1 ÁGM |
2666 | int glob_res; |
2667 | unsigned int i; | |
8d01b9d6 MV |
2668 | |
2669 | glob_res = glob(pattern.c_str(), flags, NULL, &globbuf); | |
2670 | ||
2671 | if (glob_res != 0) | |
2672 | { | |
2673 | if(glob_res != GLOB_NOMATCH) { | |
2674 | _error->Errno("glob", "Problem with glob"); | |
2675 | return result; | |
2676 | } | |
2677 | } | |
2678 | ||
2679 | // append results | |
2680 | for(i=0;i<globbuf.gl_pathc;i++) | |
2681 | result.push_back(string(globbuf.gl_pathv[i])); | |
2682 | ||
2683 | globfree(&globbuf); | |
2684 | return result; | |
2685 | } | |
2686 | /*}}}*/ | |
f8aba23f | 2687 | std::string GetTempDir() /*{{{*/ |
68e01721 MV |
2688 | { |
2689 | const char *tmpdir = getenv("TMPDIR"); | |
2690 | ||
2691 | #ifdef P_tmpdir | |
2692 | if (!tmpdir) | |
2693 | tmpdir = P_tmpdir; | |
2694 | #endif | |
2695 | ||
68e01721 | 2696 | struct stat st; |
0d303f17 | 2697 | if (!tmpdir || strlen(tmpdir) == 0 || // tmpdir is set |
dd6da7d2 DK |
2698 | stat(tmpdir, &st) != 0 || (st.st_mode & S_IFDIR) == 0) // exists and is directory |
2699 | tmpdir = "/tmp"; | |
2700 | else if (geteuid() != 0 && // root can do everything anyway | |
2701 | faccessat(-1, tmpdir, R_OK | W_OK | X_OK, AT_EACCESS | AT_SYMLINK_NOFOLLOW) != 0) // current user has rwx access to directory | |
68e01721 MV |
2702 | tmpdir = "/tmp"; |
2703 | ||
2704 | return string(tmpdir); | |
dd6da7d2 DK |
2705 | } |
2706 | std::string GetTempDir(std::string const &User) | |
2707 | { | |
2708 | // no need/possibility to drop privs | |
2709 | if(getuid() != 0 || User.empty() || User == "root") | |
2710 | return GetTempDir(); | |
2711 | ||
2712 | struct passwd const * const pw = getpwnam(User.c_str()); | |
2713 | if (pw == NULL) | |
2714 | return GetTempDir(); | |
2715 | ||
226c0f64 DK |
2716 | gid_t const old_euid = geteuid(); |
2717 | gid_t const old_egid = getegid(); | |
dd6da7d2 DK |
2718 | if (setegid(pw->pw_gid) != 0) |
2719 | _error->Errno("setegid", "setegid %u failed", pw->pw_gid); | |
2720 | if (seteuid(pw->pw_uid) != 0) | |
2721 | _error->Errno("seteuid", "seteuid %u failed", pw->pw_uid); | |
2722 | ||
2723 | std::string const tmp = GetTempDir(); | |
2724 | ||
226c0f64 DK |
2725 | if (seteuid(old_euid) != 0) |
2726 | _error->Errno("seteuid", "seteuid %u failed", old_euid); | |
2727 | if (setegid(old_egid) != 0) | |
2728 | _error->Errno("setegid", "setegid %u failed", old_egid); | |
dd6da7d2 DK |
2729 | |
2730 | return tmp; | |
68e01721 | 2731 | } |
f8aba23f | 2732 | /*}}}*/ |
c9443c01 | 2733 | FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink, FileFd * const TmpFd) /*{{{*/ |
0d29b9d4 MV |
2734 | { |
2735 | char fn[512]; | |
c9443c01 | 2736 | FileFd * const Fd = TmpFd == NULL ? new FileFd() : TmpFd; |
0d29b9d4 | 2737 | |
c9443c01 DK |
2738 | std::string const tempdir = GetTempDir(); |
2739 | snprintf(fn, sizeof(fn), "%s/%s.XXXXXX", | |
0d29b9d4 | 2740 | tempdir.c_str(), Prefix.c_str()); |
c9443c01 | 2741 | int const fd = mkstemp(fn); |
0d29b9d4 MV |
2742 | if(ImmediateUnlink) |
2743 | unlink(fn); | |
c9443c01 | 2744 | if (fd < 0) |
0d29b9d4 MV |
2745 | { |
2746 | _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn); | |
2747 | return NULL; | |
2748 | } | |
c9443c01 | 2749 | if (!Fd->OpenDescriptor(fd, FileFd::ReadWrite, FileFd::None, true)) |
0d29b9d4 MV |
2750 | { |
2751 | _error->Errno("GetTempFile",_("Unable to write to %s"),fn); | |
2752 | return NULL; | |
2753 | } | |
0d29b9d4 MV |
2754 | return Fd; |
2755 | } | |
f8aba23f DK |
2756 | /*}}}*/ |
2757 | bool Rename(std::string From, std::string To) /*{{{*/ | |
c1409d1b MV |
2758 | { |
2759 | if (rename(From.c_str(),To.c_str()) != 0) | |
2760 | { | |
2761 | _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno), | |
2762 | From.c_str(),To.c_str()); | |
2763 | return false; | |
f8aba23f | 2764 | } |
c1409d1b MV |
2765 | return true; |
2766 | } | |
f8aba23f DK |
2767 | /*}}}*/ |
2768 | bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/ | |
7ad2a347 MV |
2769 | { |
2770 | int fd; | |
2771 | if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly) | |
2772 | return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only"); | |
2773 | ||
2774 | int Pipe[2] = {-1, -1}; | |
2775 | if(pipe(Pipe) != 0) | |
7ad2a347 | 2776 | return _error->Errno("pipe", _("Failed to create subprocess IPC")); |
5e49cbb7 | 2777 | |
7ad2a347 MV |
2778 | std::set<int> keep_fds; |
2779 | keep_fds.insert(Pipe[0]); | |
2780 | keep_fds.insert(Pipe[1]); | |
2781 | Child = ExecFork(keep_fds); | |
2782 | if(Child < 0) | |
2783 | return _error->Errno("fork", "Failed to fork"); | |
2784 | if(Child == 0) | |
2785 | { | |
2786 | if(Mode == FileFd::ReadOnly) | |
2787 | { | |
2788 | close(Pipe[0]); | |
2789 | fd = Pipe[1]; | |
2790 | } | |
2791 | else if(Mode == FileFd::WriteOnly) | |
2792 | { | |
2793 | close(Pipe[1]); | |
2794 | fd = Pipe[0]; | |
2795 | } | |
2796 | ||
2797 | if(Mode == FileFd::ReadOnly) | |
2798 | { | |
2799 | dup2(fd, 1); | |
2800 | dup2(fd, 2); | |
2801 | } else if(Mode == FileFd::WriteOnly) | |
2802 | dup2(fd, 0); | |
2803 | ||
2804 | execv(Args[0], (char**)Args); | |
2805 | _exit(100); | |
2806 | } | |
2807 | if(Mode == FileFd::ReadOnly) | |
2808 | { | |
2809 | close(Pipe[1]); | |
2810 | fd = Pipe[0]; | |
8f5b67ae DK |
2811 | } |
2812 | else if(Mode == FileFd::WriteOnly) | |
7ad2a347 MV |
2813 | { |
2814 | close(Pipe[0]); | |
2815 | fd = Pipe[1]; | |
2816 | } | |
8f5b67ae DK |
2817 | else |
2818 | return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only"); | |
7ad2a347 MV |
2819 | Fd.OpenDescriptor(fd, Mode, FileFd::None, true); |
2820 | ||
2821 | return true; | |
2822 | } | |
f8aba23f DK |
2823 | /*}}}*/ |
2824 | bool DropPrivileges() /*{{{*/ | |
fc1a78d8 | 2825 | { |
8f45798d DK |
2826 | if(_config->FindB("Debug::NoDropPrivs", false) == true) |
2827 | return true; | |
2828 | ||
2829 | #if __gnu_linux__ | |
2830 | #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 ) | |
2831 | #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!" | |
2832 | #endif | |
2833 | // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime | |
2834 | int ret = prctl(38, 1, 0, 0, 0); | |
2835 | // ignore EINVAL - kernel is too old to understand the option | |
2836 | if(ret < 0 && errno != EINVAL) | |
2837 | _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret); | |
2838 | #endif | |
2839 | ||
990dd78a DK |
2840 | // empty setting disables privilege dropping - this also ensures |
2841 | // backward compatibility, see bug #764506 | |
2842 | const std::string toUser = _config->Find("APT::Sandbox::User"); | |
514a25cb | 2843 | if (toUser.empty() || toUser == "root") |
990dd78a DK |
2844 | return true; |
2845 | ||
ebca2f25 DK |
2846 | // a lot can go wrong trying to drop privileges completely, |
2847 | // so ideally we would like to verify that we have done it – | |
2848 | // but the verify asks for too much in case of fakeroot (and alike) | |
2849 | // [Specific checks can be overridden with dedicated options] | |
2850 | bool const VerifySandboxing = _config->FindB("APT::Sandbox::Verify", false); | |
2851 | ||
f1e3c8f0 | 2852 | // uid will be 0 in the end, but gid might be different anyway |
8f45798d DK |
2853 | uid_t const old_uid = getuid(); |
2854 | gid_t const old_gid = getgid(); | |
fc1a78d8 | 2855 | |
5f2047ec JAK |
2856 | if (old_uid != 0) |
2857 | return true; | |
3927c6da | 2858 | |
b8dae9a1 | 2859 | struct passwd *pw = getpwnam(toUser.c_str()); |
fc1a78d8 | 2860 | if (pw == NULL) |
b8dae9a1 | 2861 | return _error->Error("No user %s, can not drop rights", toUser.c_str()); |
3927c6da | 2862 | |
f1e3c8f0 | 2863 | // Do not change the order here, it might break things |
5a326439 | 2864 | // Get rid of all our supplementary groups first |
3b084f06 | 2865 | if (setgroups(1, &pw->pw_gid)) |
3927c6da MV |
2866 | return _error->Errno("setgroups", "Failed to setgroups"); |
2867 | ||
5a326439 JAK |
2868 | // Now change the group ids to the new user |
2869 | #ifdef HAVE_SETRESGID | |
2870 | if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) | |
2871 | return _error->Errno("setresgid", "Failed to set new group ids"); | |
2872 | #else | |
3927c6da | 2873 | if (setegid(pw->pw_gid) != 0) |
5f2047ec JAK |
2874 | return _error->Errno("setegid", "Failed to setegid"); |
2875 | ||
fc1a78d8 MV |
2876 | if (setgid(pw->pw_gid) != 0) |
2877 | return _error->Errno("setgid", "Failed to setgid"); | |
5a326439 | 2878 | #endif |
5f2047ec | 2879 | |
5a326439 JAK |
2880 | // Change the user ids to the new user |
2881 | #ifdef HAVE_SETRESUID | |
2882 | if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) | |
2883 | return _error->Errno("setresuid", "Failed to set new user ids"); | |
2884 | #else | |
fc1a78d8 MV |
2885 | if (setuid(pw->pw_uid) != 0) |
2886 | return _error->Errno("setuid", "Failed to setuid"); | |
5f2047ec JAK |
2887 | if (seteuid(pw->pw_uid) != 0) |
2888 | return _error->Errno("seteuid", "Failed to seteuid"); | |
5a326439 | 2889 | #endif |
5f2047ec | 2890 | |
ebca2f25 DK |
2891 | // disabled by default as fakeroot doesn't implement getgroups currently (#806521) |
2892 | if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Groups", false) == true) | |
2893 | { | |
2894 | // Verify that the user isn't still in any supplementary groups | |
2895 | long const ngroups_max = sysconf(_SC_NGROUPS_MAX); | |
2896 | std::unique_ptr<gid_t[]> gidlist(new gid_t[ngroups_max]); | |
2897 | if (unlikely(gidlist == NULL)) | |
2898 | return _error->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max); | |
2899 | ssize_t gidlist_nr; | |
2900 | if ((gidlist_nr = getgroups(ngroups_max, gidlist.get())) < 0) | |
2901 | return _error->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max); | |
2902 | for (ssize_t i = 0; i < gidlist_nr; ++i) | |
2903 | if (gidlist[i] != pw->pw_gid) | |
2904 | return _error->Error("Could not switch group, user %s is still in group %d", toUser.c_str(), gidlist[i]); | |
2905 | } | |
2906 | ||
2907 | // enabled by default as all fakeroot-lookalikes should fake that accordingly | |
2908 | if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::IDs", true) == true) | |
2909 | { | |
2910 | // Verify that gid, egid, uid, and euid changed | |
2911 | if (getgid() != pw->pw_gid) | |
2912 | return _error->Error("Could not switch group"); | |
2913 | if (getegid() != pw->pw_gid) | |
2914 | return _error->Error("Could not switch effective group"); | |
2915 | if (getuid() != pw->pw_uid) | |
2916 | return _error->Error("Could not switch user"); | |
2917 | if (geteuid() != pw->pw_uid) | |
2918 | return _error->Error("Could not switch effective user"); | |
5f2047ec | 2919 | |
550ab420 | 2920 | #ifdef HAVE_GETRESUID |
ebca2f25 DK |
2921 | // verify that the saved set-user-id was changed as well |
2922 | uid_t ruid = 0; | |
2923 | uid_t euid = 0; | |
2924 | uid_t suid = 0; | |
2925 | if (getresuid(&ruid, &euid, &suid)) | |
2926 | return _error->Errno("getresuid", "Could not get saved set-user-ID"); | |
2927 | if (suid != pw->pw_uid) | |
2928 | return _error->Error("Could not switch saved set-user-ID"); | |
550ab420 JAK |
2929 | #endif |
2930 | ||
2931 | #ifdef HAVE_GETRESGID | |
ebca2f25 DK |
2932 | // verify that the saved set-group-id was changed as well |
2933 | gid_t rgid = 0; | |
2934 | gid_t egid = 0; | |
2935 | gid_t sgid = 0; | |
2936 | if (getresgid(&rgid, &egid, &sgid)) | |
2937 | return _error->Errno("getresuid", "Could not get saved set-group-ID"); | |
2938 | if (sgid != pw->pw_gid) | |
2939 | return _error->Error("Could not switch saved set-group-ID"); | |
550ab420 | 2940 | #endif |
ebca2f25 | 2941 | } |
550ab420 | 2942 | |
ebca2f25 DK |
2943 | // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged |
2944 | if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Regain", false) == true) | |
2945 | { | |
2946 | // Check that uid and gid changes do not work anymore | |
2947 | if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1)) | |
2948 | return _error->Error("Could restore a gid to root, privilege dropping did not work"); | |
bdc00df5 | 2949 | |
ebca2f25 DK |
2950 | if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) |
2951 | return _error->Error("Could restore a uid to root, privilege dropping did not work"); | |
2952 | } | |
bdc00df5 | 2953 | |
fc1a78d8 MV |
2954 | return true; |
2955 | } | |
f8aba23f | 2956 | /*}}}*/ |