]>
Commit | Line | Data |
---|---|---|
578bfd0a AL |
1 | // -*- mode: cpp; mode: fold -*- |
2 | // Description /*{{{*/ | |
7da2b375 | 3 | // $Id: fileutl.cc,v 1.42 2002/09/14 05:29:22 jgg Exp $ |
578bfd0a AL |
4 | /* ###################################################################### |
5 | ||
6 | File Utilities | |
7 | ||
8 | CopyFile - Buffered copy of a single file | |
9 | GetLock - dpkg compatible lock file manipulation (fcntl) | |
10 | ||
614adaa0 MV |
11 | Most of this source is placed in the Public Domain, do with it what |
12 | you will | |
7da2b375 | 13 | It was originally written by Jason Gunthorpe <jgg@debian.org>. |
a3a03f5d | 14 | FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com> |
578bfd0a | 15 | |
614adaa0 MV |
16 | The exception is RunScripts() it is under the GPLv2 |
17 | ||
578bfd0a AL |
18 | ##################################################################### */ |
19 | /*}}}*/ | |
20 | // Include Files /*{{{*/ | |
094a497d | 21 | #include <apt-pkg/fileutl.h> |
1cd1c398 | 22 | #include <apt-pkg/strutl.h> |
094a497d | 23 | #include <apt-pkg/error.h> |
b2e465d6 | 24 | #include <apt-pkg/sptr.h> |
75ef8f14 | 25 | #include <apt-pkg/configuration.h> |
b2e465d6 AL |
26 | |
27 | #include <apti18n.h> | |
578bfd0a | 28 | |
152ab79e | 29 | #include <cstdlib> |
4f333a8b | 30 | #include <cstring> |
3010fb0e | 31 | #include <cstdio> |
4f333a8b | 32 | |
4d055c05 | 33 | #include <iostream> |
578bfd0a | 34 | #include <unistd.h> |
2c206aa4 | 35 | #include <fcntl.h> |
578bfd0a | 36 | #include <sys/stat.h> |
578bfd0a | 37 | #include <sys/types.h> |
cc2313b7 | 38 | #include <sys/time.h> |
1ae93c94 | 39 | #include <sys/wait.h> |
46e39c8e | 40 | #include <dirent.h> |
54676e1a | 41 | #include <signal.h> |
65a1e968 | 42 | #include <errno.h> |
75ef8f14 | 43 | #include <set> |
46e39c8e | 44 | #include <algorithm> |
578bfd0a AL |
45 | /*}}}*/ |
46 | ||
4d055c05 AL |
47 | using namespace std; |
48 | ||
614adaa0 MV |
49 | // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/ |
50 | // --------------------------------------------------------------------- | |
51 | /* */ | |
52 | bool RunScripts(const char *Cnf) | |
53 | { | |
54 | Configuration::Item const *Opts = _config->Tree(Cnf); | |
55 | if (Opts == 0 || Opts->Child == 0) | |
56 | return true; | |
57 | Opts = Opts->Child; | |
58 | ||
59 | // Fork for running the system calls | |
60 | pid_t Child = ExecFork(); | |
61 | ||
62 | // This is the child | |
63 | if (Child == 0) | |
64 | { | |
65 | if (chdir("/tmp/") != 0) | |
66 | _exit(100); | |
67 | ||
68 | unsigned int Count = 1; | |
69 | for (; Opts != 0; Opts = Opts->Next, Count++) | |
70 | { | |
71 | if (Opts->Value.empty() == true) | |
72 | continue; | |
73 | ||
74 | if (system(Opts->Value.c_str()) != 0) | |
75 | _exit(100+Count); | |
76 | } | |
77 | _exit(0); | |
78 | } | |
79 | ||
80 | // Wait for the child | |
81 | int Status = 0; | |
82 | while (waitpid(Child,&Status,0) != Child) | |
83 | { | |
84 | if (errno == EINTR) | |
85 | continue; | |
86 | return _error->Errno("waitpid","Couldn't wait for subprocess"); | |
87 | } | |
88 | ||
89 | // Restore sig int/quit | |
90 | signal(SIGQUIT,SIG_DFL); | |
91 | signal(SIGINT,SIG_DFL); | |
92 | ||
93 | // Check for an error code. | |
94 | if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0) | |
95 | { | |
96 | unsigned int Count = WEXITSTATUS(Status); | |
97 | if (Count > 100) | |
98 | { | |
99 | Count -= 100; | |
100 | for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--); | |
101 | _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str()); | |
102 | } | |
103 | ||
104 | return _error->Error("Sub-process returned an error code"); | |
105 | } | |
106 | ||
107 | return true; | |
108 | } | |
109 | /*}}}*/ | |
110 | ||
578bfd0a AL |
111 | // CopyFile - Buffered copy of a file /*{{{*/ |
112 | // --------------------------------------------------------------------- | |
113 | /* The caller is expected to set things so that failure causes erasure */ | |
8b89e57f | 114 | bool CopyFile(FileFd &From,FileFd &To) |
578bfd0a AL |
115 | { |
116 | if (From.IsOpen() == false || To.IsOpen() == false) | |
117 | return false; | |
118 | ||
119 | // Buffered copy between fds | |
b2e465d6 | 120 | SPtrArray<unsigned char> Buf = new unsigned char[64000]; |
b0db36b1 AL |
121 | unsigned long Size = From.Size(); |
122 | while (Size != 0) | |
578bfd0a | 123 | { |
b0db36b1 AL |
124 | unsigned long ToRead = Size; |
125 | if (Size > 64000) | |
126 | ToRead = 64000; | |
127 | ||
4a6d5862 | 128 | if (From.Read(Buf,ToRead) == false || |
b0db36b1 | 129 | To.Write(Buf,ToRead) == false) |
578bfd0a | 130 | return false; |
b0db36b1 AL |
131 | |
132 | Size -= ToRead; | |
578bfd0a AL |
133 | } |
134 | ||
578bfd0a AL |
135 | return true; |
136 | } | |
137 | /*}}}*/ | |
138 | // GetLock - Gets a lock file /*{{{*/ | |
139 | // --------------------------------------------------------------------- | |
140 | /* This will create an empty file of the given name and lock it. Once this | |
141 | is done all other calls to GetLock in any other process will fail with | |
142 | -1. The return result is the fd of the file, the call should call | |
143 | close at some time. */ | |
144 | int GetLock(string File,bool Errors) | |
145 | { | |
f659b39a OS |
146 | // GetLock() is used in aptitude on directories with public-write access |
147 | // Use O_NOFOLLOW here to prevent symlink traversal attacks | |
148 | int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640); | |
578bfd0a AL |
149 | if (FD < 0) |
150 | { | |
b2e465d6 AL |
151 | // Read only .. cant have locking problems there. |
152 | if (errno == EROFS) | |
153 | { | |
154 | _error->Warning(_("Not using locking for read only lock file %s"),File.c_str()); | |
155 | return dup(0); // Need something for the caller to close | |
156 | } | |
157 | ||
578bfd0a | 158 | if (Errors == true) |
b2e465d6 AL |
159 | _error->Errno("open",_("Could not open lock file %s"),File.c_str()); |
160 | ||
161 | // Feh.. We do this to distinguish the lock vs open case.. | |
162 | errno = EPERM; | |
578bfd0a AL |
163 | return -1; |
164 | } | |
b2e465d6 AL |
165 | SetCloseExec(FD,true); |
166 | ||
578bfd0a AL |
167 | // Aquire a write lock |
168 | struct flock fl; | |
c71bc556 AL |
169 | fl.l_type = F_WRLCK; |
170 | fl.l_whence = SEEK_SET; | |
171 | fl.l_start = 0; | |
172 | fl.l_len = 0; | |
578bfd0a AL |
173 | if (fcntl(FD,F_SETLK,&fl) == -1) |
174 | { | |
d89df07a AL |
175 | if (errno == ENOLCK) |
176 | { | |
b2e465d6 AL |
177 | _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str()); |
178 | return dup(0); // Need something for the caller to close | |
d89df07a | 179 | } |
578bfd0a | 180 | if (Errors == true) |
b2e465d6 AL |
181 | _error->Errno("open",_("Could not get lock %s"),File.c_str()); |
182 | ||
183 | int Tmp = errno; | |
578bfd0a | 184 | close(FD); |
b2e465d6 | 185 | errno = Tmp; |
578bfd0a AL |
186 | return -1; |
187 | } | |
188 | ||
189 | return FD; | |
190 | } | |
191 | /*}}}*/ | |
192 | // FileExists - Check if a file exists /*{{{*/ | |
193 | // --------------------------------------------------------------------- | |
194 | /* */ | |
195 | bool FileExists(string File) | |
196 | { | |
197 | struct stat Buf; | |
198 | if (stat(File.c_str(),&Buf) != 0) | |
199 | return false; | |
200 | return true; | |
201 | } | |
202 | /*}}}*/ | |
1cd1c398 DK |
203 | // DirectoryExists - Check if a directory exists and is really one /*{{{*/ |
204 | // --------------------------------------------------------------------- | |
205 | /* */ | |
206 | bool DirectoryExists(string const &Path) | |
207 | { | |
208 | struct stat Buf; | |
209 | if (stat(Path.c_str(),&Buf) != 0) | |
210 | return false; | |
211 | return ((Buf.st_mode & S_IFDIR) != 0); | |
212 | } | |
213 | /*}}}*/ | |
214 | // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/ | |
215 | // --------------------------------------------------------------------- | |
216 | /* This method will create all directories needed for path in good old | |
217 | mkdir -p style but refuses to do this if Parent is not a prefix of | |
218 | this Path. Example: /var/cache/ and /var/cache/apt/archives are given, | |
219 | so it will create apt/archives if /var/cache exists - on the other | |
220 | hand if the parent is /var/lib the creation will fail as this path | |
221 | is not a parent of the path to be generated. */ | |
222 | bool CreateDirectory(string const &Parent, string const &Path) | |
223 | { | |
224 | if (Parent.empty() == true || Path.empty() == true) | |
225 | return false; | |
226 | ||
227 | if (DirectoryExists(Path) == true) | |
228 | return true; | |
229 | ||
230 | if (DirectoryExists(Parent) == false) | |
231 | return false; | |
232 | ||
233 | // we are not going to create directories "into the blue" | |
234 | if (Path.find(Parent, 0) != 0) | |
235 | return false; | |
236 | ||
237 | vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/'); | |
238 | string progress = Parent; | |
239 | for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d) | |
240 | { | |
241 | if (d->empty() == true) | |
242 | continue; | |
243 | ||
244 | progress.append("/").append(*d); | |
245 | if (DirectoryExists(progress) == true) | |
246 | continue; | |
247 | ||
248 | if (mkdir(progress.c_str(), 0755) != 0) | |
249 | return false; | |
250 | } | |
251 | return true; | |
252 | } | |
253 | /*}}}*/ | |
46e39c8e MV |
254 | // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/ |
255 | // --------------------------------------------------------------------- | |
256 | /* If an extension is given only files with this extension are included | |
257 | in the returned vector, otherwise every "normal" file is included. */ | |
b39c1859 MV |
258 | std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext, |
259 | bool const &SortList, bool const &AllowNoExt) | |
260 | { | |
261 | std::vector<string> ext; | |
262 | ext.reserve(2); | |
263 | if (Ext.empty() == false) | |
264 | ext.push_back(Ext); | |
265 | if (AllowNoExt == true && ext.empty() == false) | |
266 | ext.push_back(""); | |
267 | return GetListOfFilesInDir(Dir, ext, SortList); | |
268 | } | |
269 | std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext, | |
270 | bool const &SortList) | |
271 | { | |
272 | // Attention debuggers: need to be set with the environment config file! | |
273 | bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false); | |
274 | if (Debug == true) | |
275 | { | |
276 | std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl; | |
277 | if (Ext.empty() == true) | |
278 | std::clog << "\tNO extension" << std::endl; | |
279 | else | |
280 | for (std::vector<string>::const_iterator e = Ext.begin(); | |
281 | e != Ext.end(); ++e) | |
282 | std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl; | |
283 | } | |
284 | ||
46e39c8e | 285 | std::vector<string> List; |
1408e219 | 286 | Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently"); |
46e39c8e MV |
287 | DIR *D = opendir(Dir.c_str()); |
288 | if (D == 0) | |
289 | { | |
290 | _error->Errno("opendir",_("Unable to read %s"),Dir.c_str()); | |
291 | return List; | |
292 | } | |
293 | ||
294 | for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) | |
295 | { | |
b39c1859 | 296 | // skip "hidden" files |
46e39c8e MV |
297 | if (Ent->d_name[0] == '.') |
298 | continue; | |
299 | ||
b39c1859 MV |
300 | // check for accepted extension: |
301 | // no extension given -> periods are bad as hell! | |
302 | // extensions given -> "" extension allows no extension | |
303 | if (Ext.empty() == false) | |
304 | { | |
305 | string d_ext = flExtension(Ent->d_name); | |
306 | if (d_ext == Ent->d_name) // no extension | |
307 | { | |
308 | if (std::find(Ext.begin(), Ext.end(), "") == Ext.end()) | |
309 | { | |
310 | if (Debug == true) | |
311 | std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl; | |
1408e219 | 312 | _error->Notice("Ignoring file '%s' in directory '%s' as it has no filename extension", Ent->d_name, Dir.c_str()); |
b39c1859 MV |
313 | continue; |
314 | } | |
315 | } | |
316 | else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end()) | |
317 | { | |
318 | if (Debug == true) | |
319 | std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl; | |
1408e219 DK |
320 | if (SilentIgnore.Match(Ent->d_name) == false) |
321 | _error->Notice("Ignoring file '%s' in directory '%s' as it has an invalid filename extension", Ent->d_name, Dir.c_str()); | |
b39c1859 MV |
322 | continue; |
323 | } | |
324 | } | |
46e39c8e | 325 | |
b39c1859 | 326 | // Skip bad filenames ala run-parts |
46e39c8e MV |
327 | const char *C = Ent->d_name; |
328 | for (; *C != 0; ++C) | |
329 | if (isalpha(*C) == 0 && isdigit(*C) == 0 | |
b39c1859 MV |
330 | && *C != '_' && *C != '-') { |
331 | // no required extension -> dot is a bad character | |
332 | if (*C == '.' && Ext.empty() == false) | |
333 | continue; | |
46e39c8e | 334 | break; |
b39c1859 | 335 | } |
46e39c8e | 336 | |
b39c1859 | 337 | // we don't reach the end of the name -> bad character included |
46e39c8e | 338 | if (*C != 0) |
b39c1859 MV |
339 | { |
340 | if (Debug == true) | |
341 | std::clog << "Bad file: " << Ent->d_name << " → bad character »" | |
342 | << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl; | |
343 | continue; | |
344 | } | |
345 | ||
346 | // skip filenames which end with a period. These are never valid | |
347 | if (*(C - 1) == '.') | |
348 | { | |
349 | if (Debug == true) | |
350 | std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl; | |
46e39c8e | 351 | continue; |
b39c1859 | 352 | } |
46e39c8e MV |
353 | |
354 | // Make sure it is a file and not something else | |
355 | string const File = flCombine(Dir,Ent->d_name); | |
356 | struct stat St; | |
357 | if (stat(File.c_str(),&St) != 0 || S_ISREG(St.st_mode) == 0) | |
b39c1859 MV |
358 | { |
359 | if (Debug == true) | |
360 | std::clog << "Bad file: " << Ent->d_name << " → stat says not a good file" << std::endl; | |
46e39c8e | 361 | continue; |
b39c1859 | 362 | } |
46e39c8e | 363 | |
b39c1859 MV |
364 | if (Debug == true) |
365 | std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl; | |
46e39c8e MV |
366 | List.push_back(File); |
367 | } | |
368 | closedir(D); | |
369 | ||
370 | if (SortList == true) | |
371 | std::sort(List.begin(),List.end()); | |
372 | return List; | |
373 | } | |
374 | /*}}}*/ | |
578bfd0a AL |
375 | // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/ |
376 | // --------------------------------------------------------------------- | |
377 | /* We return / on failure. */ | |
378 | string SafeGetCWD() | |
379 | { | |
380 | // Stash the current dir. | |
381 | char S[300]; | |
382 | S[0] = 0; | |
7f25bdff | 383 | if (getcwd(S,sizeof(S)-2) == 0) |
578bfd0a | 384 | return "/"; |
7f25bdff AL |
385 | unsigned int Len = strlen(S); |
386 | S[Len] = '/'; | |
387 | S[Len+1] = 0; | |
578bfd0a AL |
388 | return S; |
389 | } | |
390 | /*}}}*/ | |
8ce4327b AL |
391 | // flNotDir - Strip the directory from the filename /*{{{*/ |
392 | // --------------------------------------------------------------------- | |
393 | /* */ | |
394 | string flNotDir(string File) | |
395 | { | |
396 | string::size_type Res = File.rfind('/'); | |
397 | if (Res == string::npos) | |
398 | return File; | |
399 | Res++; | |
400 | return string(File,Res,Res - File.length()); | |
401 | } | |
402 | /*}}}*/ | |
d38b7b3d AL |
403 | // flNotFile - Strip the file from the directory name /*{{{*/ |
404 | // --------------------------------------------------------------------- | |
171c45bc | 405 | /* Result ends in a / */ |
d38b7b3d AL |
406 | string flNotFile(string File) |
407 | { | |
408 | string::size_type Res = File.rfind('/'); | |
409 | if (Res == string::npos) | |
171c45bc | 410 | return "./"; |
d38b7b3d AL |
411 | Res++; |
412 | return string(File,0,Res); | |
413 | } | |
414 | /*}}}*/ | |
b2e465d6 AL |
415 | // flExtension - Return the extension for the file /*{{{*/ |
416 | // --------------------------------------------------------------------- | |
417 | /* */ | |
418 | string flExtension(string File) | |
419 | { | |
420 | string::size_type Res = File.rfind('.'); | |
421 | if (Res == string::npos) | |
422 | return File; | |
423 | Res++; | |
424 | return string(File,Res,Res - File.length()); | |
425 | } | |
426 | /*}}}*/ | |
421c8d10 AL |
427 | // flNoLink - If file is a symlink then deref it /*{{{*/ |
428 | // --------------------------------------------------------------------- | |
429 | /* If the name is not a link then the returned path is the input. */ | |
430 | string flNoLink(string File) | |
431 | { | |
432 | struct stat St; | |
433 | if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0) | |
434 | return File; | |
435 | if (stat(File.c_str(),&St) != 0) | |
436 | return File; | |
437 | ||
438 | /* Loop resolving the link. There is no need to limit the number of | |
439 | loops because the stat call above ensures that the symlink is not | |
440 | circular */ | |
441 | char Buffer[1024]; | |
442 | string NFile = File; | |
443 | while (1) | |
444 | { | |
445 | // Read the link | |
446 | int Res; | |
447 | if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 || | |
448 | (unsigned)Res >= sizeof(Buffer)) | |
449 | return File; | |
450 | ||
451 | // Append or replace the previous path | |
452 | Buffer[Res] = 0; | |
453 | if (Buffer[0] == '/') | |
454 | NFile = Buffer; | |
455 | else | |
456 | NFile = flNotFile(NFile) + Buffer; | |
457 | ||
458 | // See if we are done | |
459 | if (lstat(NFile.c_str(),&St) != 0) | |
460 | return File; | |
461 | if (S_ISLNK(St.st_mode) == 0) | |
462 | return NFile; | |
463 | } | |
464 | } | |
465 | /*}}}*/ | |
b2e465d6 AL |
466 | // flCombine - Combine a file and a directory /*{{{*/ |
467 | // --------------------------------------------------------------------- | |
468 | /* If the file is an absolute path then it is just returned, otherwise | |
469 | the directory is pre-pended to it. */ | |
470 | string flCombine(string Dir,string File) | |
471 | { | |
472 | if (File.empty() == true) | |
473 | return string(); | |
474 | ||
475 | if (File[0] == '/' || Dir.empty() == true) | |
476 | return File; | |
477 | if (File.length() >= 2 && File[0] == '.' && File[1] == '/') | |
478 | return File; | |
479 | if (Dir[Dir.length()-1] == '/') | |
480 | return Dir + File; | |
481 | return Dir + '/' + File; | |
482 | } | |
483 | /*}}}*/ | |
3b5421b4 AL |
484 | // SetCloseExec - Set the close on exec flag /*{{{*/ |
485 | // --------------------------------------------------------------------- | |
486 | /* */ | |
487 | void SetCloseExec(int Fd,bool Close) | |
488 | { | |
489 | if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0) | |
490 | { | |
491 | cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl; | |
492 | exit(100); | |
493 | } | |
494 | } | |
495 | /*}}}*/ | |
496 | // SetNonBlock - Set the nonblocking flag /*{{{*/ | |
497 | // --------------------------------------------------------------------- | |
498 | /* */ | |
499 | void SetNonBlock(int Fd,bool Block) | |
500 | { | |
0a8a80e5 AL |
501 | int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK); |
502 | if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0) | |
3b5421b4 AL |
503 | { |
504 | cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl; | |
505 | exit(100); | |
506 | } | |
507 | } | |
508 | /*}}}*/ | |
509 | // WaitFd - Wait for a FD to become readable /*{{{*/ | |
510 | // --------------------------------------------------------------------- | |
b2e465d6 | 511 | /* This waits for a FD to become readable using select. It is useful for |
6d5dd02a AL |
512 | applications making use of non-blocking sockets. The timeout is |
513 | in seconds. */ | |
1084d58a | 514 | bool WaitFd(int Fd,bool write,unsigned long timeout) |
3b5421b4 AL |
515 | { |
516 | fd_set Set; | |
cc2313b7 | 517 | struct timeval tv; |
3b5421b4 AL |
518 | FD_ZERO(&Set); |
519 | FD_SET(Fd,&Set); | |
6d5dd02a AL |
520 | tv.tv_sec = timeout; |
521 | tv.tv_usec = 0; | |
1084d58a | 522 | if (write == true) |
b0db36b1 AL |
523 | { |
524 | int Res; | |
525 | do | |
526 | { | |
527 | Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0)); | |
528 | } | |
529 | while (Res < 0 && errno == EINTR); | |
530 | ||
531 | if (Res <= 0) | |
532 | return false; | |
1084d58a AL |
533 | } |
534 | else | |
535 | { | |
b0db36b1 AL |
536 | int Res; |
537 | do | |
538 | { | |
539 | Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0)); | |
540 | } | |
541 | while (Res < 0 && errno == EINTR); | |
542 | ||
543 | if (Res <= 0) | |
544 | return false; | |
cc2313b7 | 545 | } |
1084d58a | 546 | |
3b5421b4 AL |
547 | return true; |
548 | } | |
549 | /*}}}*/ | |
54676e1a AL |
550 | // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/ |
551 | // --------------------------------------------------------------------- | |
552 | /* This is used if you want to cleanse the environment for the forked | |
553 | child, it fixes up the important signals and nukes all of the fds, | |
554 | otherwise acts like normal fork. */ | |
75ef8f14 | 555 | pid_t ExecFork() |
54676e1a AL |
556 | { |
557 | // Fork off the process | |
558 | pid_t Process = fork(); | |
559 | if (Process < 0) | |
560 | { | |
561 | cerr << "FATAL -> Failed to fork." << endl; | |
562 | exit(100); | |
563 | } | |
564 | ||
565 | // Spawn the subprocess | |
566 | if (Process == 0) | |
567 | { | |
568 | // Setup the signals | |
569 | signal(SIGPIPE,SIG_DFL); | |
570 | signal(SIGQUIT,SIG_DFL); | |
571 | signal(SIGINT,SIG_DFL); | |
572 | signal(SIGWINCH,SIG_DFL); | |
573 | signal(SIGCONT,SIG_DFL); | |
574 | signal(SIGTSTP,SIG_DFL); | |
75ef8f14 MV |
575 | |
576 | set<int> KeepFDs; | |
577 | Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds"); | |
578 | if (Opts != 0 && Opts->Child != 0) | |
579 | { | |
580 | Opts = Opts->Child; | |
581 | for (; Opts != 0; Opts = Opts->Next) | |
582 | { | |
583 | if (Opts->Value.empty() == true) | |
584 | continue; | |
585 | int fd = atoi(Opts->Value.c_str()); | |
586 | KeepFDs.insert(fd); | |
587 | } | |
588 | } | |
589 | ||
54676e1a AL |
590 | // Close all of our FDs - just in case |
591 | for (int K = 3; K != 40; K++) | |
75ef8f14 MV |
592 | { |
593 | if(KeepFDs.find(K) == KeepFDs.end()) | |
007dc9e0 | 594 | fcntl(K,F_SETFD,FD_CLOEXEC); |
75ef8f14 | 595 | } |
54676e1a AL |
596 | } |
597 | ||
598 | return Process; | |
599 | } | |
600 | /*}}}*/ | |
ddc1d8d0 AL |
601 | // ExecWait - Fancy waitpid /*{{{*/ |
602 | // --------------------------------------------------------------------- | |
2c9a72d1 | 603 | /* Waits for the given sub process. If Reap is set then no errors are |
ddc1d8d0 AL |
604 | generated. Otherwise a failed subprocess will generate a proper descriptive |
605 | message */ | |
3826564e | 606 | bool ExecWait(pid_t Pid,const char *Name,bool Reap) |
ddc1d8d0 AL |
607 | { |
608 | if (Pid <= 1) | |
609 | return true; | |
610 | ||
611 | // Wait and collect the error code | |
612 | int Status; | |
613 | while (waitpid(Pid,&Status,0) != Pid) | |
614 | { | |
615 | if (errno == EINTR) | |
616 | continue; | |
617 | ||
618 | if (Reap == true) | |
619 | return false; | |
620 | ||
db0db9fe | 621 | return _error->Error(_("Waited for %s but it wasn't there"),Name); |
ddc1d8d0 AL |
622 | } |
623 | ||
624 | ||
625 | // Check for an error code. | |
626 | if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0) | |
627 | { | |
628 | if (Reap == true) | |
629 | return false; | |
ab7f4d7c | 630 | if (WIFSIGNALED(Status) != 0) |
40e7fe0e | 631 | { |
ab7f4d7c MV |
632 | if( WTERMSIG(Status) == SIGSEGV) |
633 | return _error->Error(_("Sub-process %s received a segmentation fault."),Name); | |
634 | else | |
635 | return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status)); | |
40e7fe0e | 636 | } |
ddc1d8d0 AL |
637 | |
638 | if (WIFEXITED(Status) != 0) | |
b2e465d6 | 639 | return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status)); |
ddc1d8d0 | 640 | |
b2e465d6 | 641 | return _error->Error(_("Sub-process %s exited unexpectedly"),Name); |
ddc1d8d0 AL |
642 | } |
643 | ||
644 | return true; | |
645 | } | |
646 | /*}}}*/ | |
578bfd0a | 647 | |
13d87e2e | 648 | // FileFd::Open - Open a file /*{{{*/ |
578bfd0a AL |
649 | // --------------------------------------------------------------------- |
650 | /* The most commonly used open mode combinations are given with Mode */ | |
13d87e2e | 651 | bool FileFd::Open(string FileName,OpenMode Mode, unsigned long Perms) |
578bfd0a | 652 | { |
13d87e2e | 653 | Close(); |
1164783d | 654 | Flags = AutoClose; |
578bfd0a AL |
655 | switch (Mode) |
656 | { | |
657 | case ReadOnly: | |
658 | iFd = open(FileName.c_str(),O_RDONLY); | |
659 | break; | |
c4fc2fd7 | 660 | |
661 | case ReadOnlyGzip: | |
662 | iFd = open(FileName.c_str(),O_RDONLY); | |
d13c2d3f | 663 | if (iFd > 0) { |
c4fc2fd7 | 664 | gz = gzdopen (iFd, "r"); |
665 | if (gz == NULL) { | |
666 | close (iFd); | |
667 | iFd = -1; | |
668 | } | |
a3a03f5d | 669 | } |
578bfd0a AL |
670 | break; |
671 | ||
4a9db827 | 672 | case WriteAtomic: |
50b513a1 | 673 | { |
3010fb0e JAK |
674 | Flags |= Replace; |
675 | char *name = strdup((FileName + ".XXXXXX").c_str()); | |
676 | TemporaryFileName = string(mktemp(name)); | |
677 | iFd = open(TemporaryFileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms); | |
678 | free(name); | |
50b513a1 AL |
679 | break; |
680 | } | |
4a9db827 | 681 | |
fc81e8f2 JAK |
682 | case WriteEmpty: |
683 | { | |
684 | struct stat Buf; | |
685 | if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode)) | |
686 | unlink(FileName.c_str()); | |
687 | iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_TRUNC,Perms); | |
688 | break; | |
689 | } | |
578bfd0a AL |
690 | |
691 | case WriteExists: | |
692 | iFd = open(FileName.c_str(),O_RDWR); | |
693 | break; | |
0a8e3465 AL |
694 | |
695 | case WriteAny: | |
696 | iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms); | |
d38b7b3d | 697 | break; |
f08fcf34 AL |
698 | |
699 | case WriteTemp: | |
4decd43c AL |
700 | unlink(FileName.c_str()); |
701 | iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms); | |
f08fcf34 | 702 | break; |
578bfd0a AL |
703 | } |
704 | ||
705 | if (iFd < 0) | |
b2e465d6 | 706 | return _error->Errno("open",_("Could not open file %s"),FileName.c_str()); |
13d87e2e AL |
707 | |
708 | this->FileName = FileName; | |
709 | SetCloseExec(iFd,true); | |
710 | return true; | |
578bfd0a | 711 | } |
144c0969 JAK |
712 | |
713 | bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, bool AutoClose) | |
714 | { | |
715 | Close(); | |
716 | Flags = (AutoClose) ? FileFd::AutoClose : 0; | |
717 | iFd = Fd; | |
718 | if (Mode == ReadOnlyGzip) { | |
719 | gz = gzdopen (iFd, "r"); | |
720 | if (gz == NULL) { | |
721 | if (AutoClose) | |
722 | close (iFd); | |
723 | return _error->Errno("gzdopen",_("Could not open file descriptor %d"), | |
724 | Fd); | |
725 | } | |
726 | } | |
727 | this->FileName = ""; | |
728 | return true; | |
729 | } | |
578bfd0a | 730 | /*}}}*/ |
8e06abb2 | 731 | // FileFd::~File - Closes the file /*{{{*/ |
578bfd0a AL |
732 | // --------------------------------------------------------------------- |
733 | /* If the proper modes are selected then we close the Fd and possibly | |
734 | unlink the file on error. */ | |
8e06abb2 | 735 | FileFd::~FileFd() |
578bfd0a AL |
736 | { |
737 | Close(); | |
738 | } | |
739 | /*}}}*/ | |
8e06abb2 | 740 | // FileFd::Read - Read a bit of the file /*{{{*/ |
578bfd0a | 741 | // --------------------------------------------------------------------- |
b0db36b1 AL |
742 | /* We are carefull to handle interruption by a signal while reading |
743 | gracefully. */ | |
f604cf55 | 744 | bool FileFd::Read(void *To,unsigned long Size,unsigned long *Actual) |
578bfd0a | 745 | { |
b0db36b1 AL |
746 | int Res; |
747 | errno = 0; | |
f604cf55 AL |
748 | if (Actual != 0) |
749 | *Actual = 0; | |
750 | ||
b0db36b1 | 751 | do |
578bfd0a | 752 | { |
a3a03f5d | 753 | if (gz != NULL) |
754 | Res = gzread(gz,To,Size); | |
755 | else | |
756 | Res = read(iFd,To,Size); | |
b0db36b1 AL |
757 | if (Res < 0 && errno == EINTR) |
758 | continue; | |
759 | if (Res < 0) | |
760 | { | |
761 | Flags |= Fail; | |
b2e465d6 | 762 | return _error->Errno("read",_("Read error")); |
b0db36b1 | 763 | } |
578bfd0a | 764 | |
b0db36b1 AL |
765 | To = (char *)To + Res; |
766 | Size -= Res; | |
f604cf55 AL |
767 | if (Actual != 0) |
768 | *Actual += Res; | |
b0db36b1 AL |
769 | } |
770 | while (Res > 0 && Size > 0); | |
771 | ||
772 | if (Size == 0) | |
773 | return true; | |
774 | ||
ddc1d8d0 | 775 | // Eof handling |
f604cf55 | 776 | if (Actual != 0) |
ddc1d8d0 AL |
777 | { |
778 | Flags |= HitEof; | |
779 | return true; | |
780 | } | |
781 | ||
b0db36b1 | 782 | Flags |= Fail; |
b2e465d6 | 783 | return _error->Error(_("read, still have %lu to read but none left"),Size); |
578bfd0a AL |
784 | } |
785 | /*}}}*/ | |
8e06abb2 | 786 | // FileFd::Write - Write to the file /*{{{*/ |
578bfd0a AL |
787 | // --------------------------------------------------------------------- |
788 | /* */ | |
a05599f1 | 789 | bool FileFd::Write(const void *From,unsigned long Size) |
578bfd0a | 790 | { |
b0db36b1 AL |
791 | int Res; |
792 | errno = 0; | |
793 | do | |
578bfd0a | 794 | { |
a3a03f5d | 795 | if (gz != NULL) |
796 | Res = gzwrite(gz,From,Size); | |
797 | else | |
798 | Res = write(iFd,From,Size); | |
b0db36b1 AL |
799 | if (Res < 0 && errno == EINTR) |
800 | continue; | |
801 | if (Res < 0) | |
802 | { | |
803 | Flags |= Fail; | |
b2e465d6 | 804 | return _error->Errno("write",_("Write error")); |
b0db36b1 AL |
805 | } |
806 | ||
807 | From = (char *)From + Res; | |
808 | Size -= Res; | |
578bfd0a | 809 | } |
b0db36b1 | 810 | while (Res > 0 && Size > 0); |
578bfd0a | 811 | |
b0db36b1 AL |
812 | if (Size == 0) |
813 | return true; | |
814 | ||
815 | Flags |= Fail; | |
b2e465d6 | 816 | return _error->Error(_("write, still have %lu to write but couldn't"),Size); |
578bfd0a AL |
817 | } |
818 | /*}}}*/ | |
8e06abb2 | 819 | // FileFd::Seek - Seek in the file /*{{{*/ |
578bfd0a AL |
820 | // --------------------------------------------------------------------- |
821 | /* */ | |
8e06abb2 | 822 | bool FileFd::Seek(unsigned long To) |
578bfd0a | 823 | { |
a3a03f5d | 824 | int res; |
825 | if (gz) | |
826 | res = gzseek(gz,To,SEEK_SET); | |
827 | else | |
828 | res = lseek(iFd,To,SEEK_SET); | |
829 | if (res != (signed)To) | |
578bfd0a AL |
830 | { |
831 | Flags |= Fail; | |
b2e465d6 | 832 | return _error->Error("Unable to seek to %lu",To); |
578bfd0a AL |
833 | } |
834 | ||
727f18af AL |
835 | return true; |
836 | } | |
837 | /*}}}*/ | |
838 | // FileFd::Skip - Seek in the file /*{{{*/ | |
839 | // --------------------------------------------------------------------- | |
840 | /* */ | |
841 | bool FileFd::Skip(unsigned long Over) | |
842 | { | |
a3a03f5d | 843 | int res; |
844 | if (gz) | |
845 | res = gzseek(gz,Over,SEEK_CUR); | |
846 | else | |
847 | res = lseek(iFd,Over,SEEK_CUR); | |
848 | if (res < 0) | |
727f18af AL |
849 | { |
850 | Flags |= Fail; | |
b2e465d6 | 851 | return _error->Error("Unable to seek ahead %lu",Over); |
727f18af AL |
852 | } |
853 | ||
6d5dd02a AL |
854 | return true; |
855 | } | |
856 | /*}}}*/ | |
857 | // FileFd::Truncate - Truncate the file /*{{{*/ | |
858 | // --------------------------------------------------------------------- | |
859 | /* */ | |
860 | bool FileFd::Truncate(unsigned long To) | |
861 | { | |
a3a03f5d | 862 | if (gz) |
863 | { | |
864 | Flags |= Fail; | |
865 | return _error->Error("Truncating gzipped files is not implemented (%s)", FileName.c_str()); | |
866 | } | |
6d5dd02a AL |
867 | if (ftruncate(iFd,To) != 0) |
868 | { | |
869 | Flags |= Fail; | |
b2e465d6 | 870 | return _error->Error("Unable to truncate to %lu",To); |
6d5dd02a AL |
871 | } |
872 | ||
578bfd0a AL |
873 | return true; |
874 | } | |
875 | /*}}}*/ | |
7f25bdff AL |
876 | // FileFd::Tell - Current seek position /*{{{*/ |
877 | // --------------------------------------------------------------------- | |
878 | /* */ | |
879 | unsigned long FileFd::Tell() | |
880 | { | |
a3a03f5d | 881 | off_t Res; |
882 | if (gz) | |
883 | Res = gztell(gz); | |
884 | else | |
885 | Res = lseek(iFd,0,SEEK_CUR); | |
7f25bdff AL |
886 | if (Res == (off_t)-1) |
887 | _error->Errno("lseek","Failed to determine the current file position"); | |
888 | return Res; | |
889 | } | |
890 | /*}}}*/ | |
8e06abb2 | 891 | // FileFd::Size - Return the size of the file /*{{{*/ |
578bfd0a AL |
892 | // --------------------------------------------------------------------- |
893 | /* */ | |
8e06abb2 | 894 | unsigned long FileFd::Size() |
578bfd0a | 895 | { |
a3a03f5d | 896 | //TODO: For gz, do we need the actual file size here or the uncompressed length? |
578bfd0a AL |
897 | struct stat Buf; |
898 | if (fstat(iFd,&Buf) != 0) | |
899 | return _error->Errno("fstat","Unable to determine the file size"); | |
900 | return Buf.st_size; | |
901 | } | |
902 | /*}}}*/ | |
8e06abb2 | 903 | // FileFd::Close - Close the file if the close flag is set /*{{{*/ |
578bfd0a AL |
904 | // --------------------------------------------------------------------- |
905 | /* */ | |
8e06abb2 | 906 | bool FileFd::Close() |
578bfd0a AL |
907 | { |
908 | bool Res = true; | |
909 | if ((Flags & AutoClose) == AutoClose) | |
d13c2d3f | 910 | { |
911 | if (gz != NULL) { | |
3184b4cf | 912 | int const e = gzclose(gz); |
d13c2d3f | 913 | // gzdopen() on empty files always fails with "buffer error" here, ignore that |
914 | if (e != 0 && e != Z_BUF_ERROR) | |
3184b4cf | 915 | Res &= _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str()); |
d13c2d3f | 916 | } else |
917 | if (iFd > 0 && close(iFd) != 0) | |
3184b4cf | 918 | Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str()); |
d13c2d3f | 919 | } |
3010fb0e | 920 | |
62d073d9 | 921 | if ((Flags & Replace) == Replace && iFd >= 0) { |
3010fb0e | 922 | if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0) |
62d073d9 DK |
923 | Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str()); |
924 | ||
fd3b761e | 925 | FileName = TemporaryFileName; // for the unlink() below. |
3010fb0e | 926 | } |
62d073d9 DK |
927 | |
928 | iFd = -1; | |
a3a03f5d | 929 | gz = NULL; |
62d073d9 | 930 | |
578bfd0a AL |
931 | if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail && |
932 | FileName.empty() == false) | |
933 | if (unlink(FileName.c_str()) != 0) | |
62d073d9 | 934 | Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str()); |
3010fb0e JAK |
935 | |
936 | ||
578bfd0a AL |
937 | return Res; |
938 | } | |
939 | /*}}}*/ | |
b2e465d6 AL |
940 | // FileFd::Sync - Sync the file /*{{{*/ |
941 | // --------------------------------------------------------------------- | |
942 | /* */ | |
943 | bool FileFd::Sync() | |
944 | { | |
945 | #ifdef _POSIX_SYNCHRONIZED_IO | |
946 | if (fsync(iFd) != 0) | |
947 | return _error->Errno("sync",_("Problem syncing the file")); | |
948 | #endif | |
949 | return true; | |
950 | } | |
951 | /*}}}*/ |