s390 archtable entry. Closes: #88232
[ntk/apt.git] / apt-pkg / contrib / fileutl.cc
CommitLineData
578bfd0a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
b2e465d6 3// $Id: fileutl.cc,v 1.35 2001/02/20 07:03:17 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
11 This source is placed in the Public Domain, do with it what you will
12 It was originally written by Jason Gunthorpe.
13
14 ##################################################################### */
15 /*}}}*/
16// Include Files /*{{{*/
6c139d6e 17#ifdef __GNUG__
094a497d 18#pragma implementation "apt-pkg/fileutl.h"
6c139d6e 19#endif
094a497d
AL
20#include <apt-pkg/fileutl.h>
21#include <apt-pkg/error.h>
b2e465d6
AL
22#include <apt-pkg/sptr.h>
23
24#include <apti18n.h>
578bfd0a
AL
25
26#include <unistd.h>
2c206aa4 27#include <fcntl.h>
578bfd0a 28#include <sys/stat.h>
578bfd0a 29#include <sys/types.h>
cc2313b7 30#include <sys/time.h>
1ae93c94 31#include <sys/wait.h>
54676e1a 32#include <signal.h>
65a1e968 33#include <errno.h>
578bfd0a
AL
34 /*}}}*/
35
36// CopyFile - Buffered copy of a file /*{{{*/
37// ---------------------------------------------------------------------
38/* The caller is expected to set things so that failure causes erasure */
8b89e57f 39bool CopyFile(FileFd &From,FileFd &To)
578bfd0a
AL
40{
41 if (From.IsOpen() == false || To.IsOpen() == false)
42 return false;
43
44 // Buffered copy between fds
b2e465d6 45 SPtrArray<unsigned char> Buf = new unsigned char[64000];
b0db36b1
AL
46 unsigned long Size = From.Size();
47 while (Size != 0)
578bfd0a 48 {
b0db36b1
AL
49 unsigned long ToRead = Size;
50 if (Size > 64000)
51 ToRead = 64000;
52
4a6d5862 53 if (From.Read(Buf,ToRead) == false ||
b0db36b1 54 To.Write(Buf,ToRead) == false)
578bfd0a 55 return false;
b0db36b1
AL
56
57 Size -= ToRead;
578bfd0a
AL
58 }
59
578bfd0a
AL
60 return true;
61}
62 /*}}}*/
63// GetLock - Gets a lock file /*{{{*/
64// ---------------------------------------------------------------------
65/* This will create an empty file of the given name and lock it. Once this
66 is done all other calls to GetLock in any other process will fail with
67 -1. The return result is the fd of the file, the call should call
68 close at some time. */
69int GetLock(string File,bool Errors)
70{
71 int FD = open(File.c_str(),O_RDWR | O_CREAT | O_TRUNC,0640);
72 if (FD < 0)
73 {
b2e465d6
AL
74 // Read only .. cant have locking problems there.
75 if (errno == EROFS)
76 {
77 _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
78 return dup(0); // Need something for the caller to close
79 }
80
578bfd0a 81 if (Errors == true)
b2e465d6
AL
82 _error->Errno("open",_("Could not open lock file %s"),File.c_str());
83
84 // Feh.. We do this to distinguish the lock vs open case..
85 errno = EPERM;
578bfd0a
AL
86 return -1;
87 }
b2e465d6
AL
88 SetCloseExec(FD,true);
89
578bfd0a
AL
90 // Aquire a write lock
91 struct flock fl;
c71bc556
AL
92 fl.l_type = F_WRLCK;
93 fl.l_whence = SEEK_SET;
94 fl.l_start = 0;
95 fl.l_len = 0;
578bfd0a
AL
96 if (fcntl(FD,F_SETLK,&fl) == -1)
97 {
d89df07a
AL
98 if (errno == ENOLCK)
99 {
b2e465d6
AL
100 _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
101 return dup(0); // Need something for the caller to close
d89df07a 102 }
578bfd0a 103 if (Errors == true)
b2e465d6
AL
104 _error->Errno("open",_("Could not get lock %s"),File.c_str());
105
106 int Tmp = errno;
578bfd0a 107 close(FD);
b2e465d6 108 errno = Tmp;
578bfd0a
AL
109 return -1;
110 }
111
112 return FD;
113}
114 /*}}}*/
115// FileExists - Check if a file exists /*{{{*/
116// ---------------------------------------------------------------------
117/* */
118bool FileExists(string File)
119{
120 struct stat Buf;
121 if (stat(File.c_str(),&Buf) != 0)
122 return false;
123 return true;
124}
125 /*}}}*/
126// SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
127// ---------------------------------------------------------------------
128/* We return / on failure. */
129string SafeGetCWD()
130{
131 // Stash the current dir.
132 char S[300];
133 S[0] = 0;
7f25bdff 134 if (getcwd(S,sizeof(S)-2) == 0)
578bfd0a 135 return "/";
7f25bdff
AL
136 unsigned int Len = strlen(S);
137 S[Len] = '/';
138 S[Len+1] = 0;
578bfd0a
AL
139 return S;
140}
141 /*}}}*/
8ce4327b
AL
142// flNotDir - Strip the directory from the filename /*{{{*/
143// ---------------------------------------------------------------------
144/* */
145string flNotDir(string File)
146{
147 string::size_type Res = File.rfind('/');
148 if (Res == string::npos)
149 return File;
150 Res++;
151 return string(File,Res,Res - File.length());
152}
153 /*}}}*/
d38b7b3d
AL
154// flNotFile - Strip the file from the directory name /*{{{*/
155// ---------------------------------------------------------------------
156/* */
157string flNotFile(string File)
158{
159 string::size_type Res = File.rfind('/');
160 if (Res == string::npos)
161 return File;
162 Res++;
163 return string(File,0,Res);
164}
165 /*}}}*/
b2e465d6
AL
166// flExtension - Return the extension for the file /*{{{*/
167// ---------------------------------------------------------------------
168/* */
169string flExtension(string File)
170{
171 string::size_type Res = File.rfind('.');
172 if (Res == string::npos)
173 return File;
174 Res++;
175 return string(File,Res,Res - File.length());
176}
177 /*}}}*/
421c8d10
AL
178// flNoLink - If file is a symlink then deref it /*{{{*/
179// ---------------------------------------------------------------------
180/* If the name is not a link then the returned path is the input. */
181string flNoLink(string File)
182{
183 struct stat St;
184 if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
185 return File;
186 if (stat(File.c_str(),&St) != 0)
187 return File;
188
189 /* Loop resolving the link. There is no need to limit the number of
190 loops because the stat call above ensures that the symlink is not
191 circular */
192 char Buffer[1024];
193 string NFile = File;
194 while (1)
195 {
196 // Read the link
197 int Res;
198 if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
199 (unsigned)Res >= sizeof(Buffer))
200 return File;
201
202 // Append or replace the previous path
203 Buffer[Res] = 0;
204 if (Buffer[0] == '/')
205 NFile = Buffer;
206 else
207 NFile = flNotFile(NFile) + Buffer;
208
209 // See if we are done
210 if (lstat(NFile.c_str(),&St) != 0)
211 return File;
212 if (S_ISLNK(St.st_mode) == 0)
213 return NFile;
214 }
215}
216 /*}}}*/
b2e465d6
AL
217// flCombine - Combine a file and a directory /*{{{*/
218// ---------------------------------------------------------------------
219/* If the file is an absolute path then it is just returned, otherwise
220 the directory is pre-pended to it. */
221string flCombine(string Dir,string File)
222{
223 if (File.empty() == true)
224 return string();
225
226 if (File[0] == '/' || Dir.empty() == true)
227 return File;
228 if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
229 return File;
230 if (Dir[Dir.length()-1] == '/')
231 return Dir + File;
232 return Dir + '/' + File;
233}
234 /*}}}*/
3b5421b4
AL
235// SetCloseExec - Set the close on exec flag /*{{{*/
236// ---------------------------------------------------------------------
237/* */
238void SetCloseExec(int Fd,bool Close)
239{
240 if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
241 {
242 cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
243 exit(100);
244 }
245}
246 /*}}}*/
247// SetNonBlock - Set the nonblocking flag /*{{{*/
248// ---------------------------------------------------------------------
249/* */
250void SetNonBlock(int Fd,bool Block)
251{
0a8a80e5
AL
252 int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
253 if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
3b5421b4
AL
254 {
255 cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
256 exit(100);
257 }
258}
259 /*}}}*/
260// WaitFd - Wait for a FD to become readable /*{{{*/
261// ---------------------------------------------------------------------
b2e465d6 262/* This waits for a FD to become readable using select. It is useful for
6d5dd02a
AL
263 applications making use of non-blocking sockets. The timeout is
264 in seconds. */
1084d58a 265bool WaitFd(int Fd,bool write,unsigned long timeout)
3b5421b4
AL
266{
267 fd_set Set;
cc2313b7 268 struct timeval tv;
3b5421b4
AL
269 FD_ZERO(&Set);
270 FD_SET(Fd,&Set);
6d5dd02a
AL
271 tv.tv_sec = timeout;
272 tv.tv_usec = 0;
1084d58a 273 if (write == true)
b0db36b1
AL
274 {
275 int Res;
276 do
277 {
278 Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
279 }
280 while (Res < 0 && errno == EINTR);
281
282 if (Res <= 0)
283 return false;
1084d58a
AL
284 }
285 else
286 {
b0db36b1
AL
287 int Res;
288 do
289 {
290 Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
291 }
292 while (Res < 0 && errno == EINTR);
293
294 if (Res <= 0)
295 return false;
cc2313b7 296 }
1084d58a 297
3b5421b4
AL
298 return true;
299}
300 /*}}}*/
54676e1a
AL
301// ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
302// ---------------------------------------------------------------------
303/* This is used if you want to cleanse the environment for the forked
304 child, it fixes up the important signals and nukes all of the fds,
305 otherwise acts like normal fork. */
306int ExecFork()
307{
308 // Fork off the process
309 pid_t Process = fork();
310 if (Process < 0)
311 {
312 cerr << "FATAL -> Failed to fork." << endl;
313 exit(100);
314 }
315
316 // Spawn the subprocess
317 if (Process == 0)
318 {
319 // Setup the signals
320 signal(SIGPIPE,SIG_DFL);
321 signal(SIGQUIT,SIG_DFL);
322 signal(SIGINT,SIG_DFL);
323 signal(SIGWINCH,SIG_DFL);
324 signal(SIGCONT,SIG_DFL);
325 signal(SIGTSTP,SIG_DFL);
326
327 // Close all of our FDs - just in case
328 for (int K = 3; K != 40; K++)
329 fcntl(K,F_SETFD,FD_CLOEXEC);
330 }
331
332 return Process;
333}
334 /*}}}*/
ddc1d8d0
AL
335// ExecWait - Fancy waitpid /*{{{*/
336// ---------------------------------------------------------------------
337/* Waits for the given sub process. If Reap is set the no errors are
338 generated. Otherwise a failed subprocess will generate a proper descriptive
339 message */
340bool ExecWait(int Pid,const char *Name,bool Reap)
341{
342 if (Pid <= 1)
343 return true;
344
345 // Wait and collect the error code
346 int Status;
347 while (waitpid(Pid,&Status,0) != Pid)
348 {
349 if (errno == EINTR)
350 continue;
351
352 if (Reap == true)
353 return false;
354
b2e465d6 355 return _error->Error(_("Waited, for %s but it wasn't there"),Name);
ddc1d8d0
AL
356 }
357
358
359 // Check for an error code.
360 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
361 {
362 if (Reap == true)
363 return false;
364 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
b2e465d6 365 return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
ddc1d8d0
AL
366
367 if (WIFEXITED(Status) != 0)
b2e465d6 368 return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
ddc1d8d0 369
b2e465d6 370 return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
ddc1d8d0
AL
371 }
372
373 return true;
374}
375 /*}}}*/
578bfd0a 376
13d87e2e 377// FileFd::Open - Open a file /*{{{*/
578bfd0a
AL
378// ---------------------------------------------------------------------
379/* The most commonly used open mode combinations are given with Mode */
13d87e2e 380bool FileFd::Open(string FileName,OpenMode Mode, unsigned long Perms)
578bfd0a 381{
13d87e2e 382 Close();
1164783d 383 Flags = AutoClose;
578bfd0a
AL
384 switch (Mode)
385 {
386 case ReadOnly:
387 iFd = open(FileName.c_str(),O_RDONLY);
388 break;
389
390 case WriteEmpty:
50b513a1
AL
391 {
392 struct stat Buf;
459681d3 393 if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
50b513a1
AL
394 unlink(FileName.c_str());
395 iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_TRUNC,Perms);
396 break;
397 }
578bfd0a
AL
398
399 case WriteExists:
400 iFd = open(FileName.c_str(),O_RDWR);
401 break;
0a8e3465
AL
402
403 case WriteAny:
404 iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms);
d38b7b3d 405 break;
578bfd0a
AL
406 }
407
408 if (iFd < 0)
b2e465d6 409 return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
13d87e2e
AL
410
411 this->FileName = FileName;
412 SetCloseExec(iFd,true);
413 return true;
578bfd0a
AL
414}
415 /*}}}*/
8e06abb2 416// FileFd::~File - Closes the file /*{{{*/
578bfd0a
AL
417// ---------------------------------------------------------------------
418/* If the proper modes are selected then we close the Fd and possibly
419 unlink the file on error. */
8e06abb2 420FileFd::~FileFd()
578bfd0a
AL
421{
422 Close();
423}
424 /*}}}*/
8e06abb2 425// FileFd::Read - Read a bit of the file /*{{{*/
578bfd0a 426// ---------------------------------------------------------------------
b0db36b1
AL
427/* We are carefull to handle interruption by a signal while reading
428 gracefully. */
ddc1d8d0 429bool FileFd::Read(void *To,unsigned long Size,bool AllowEof)
578bfd0a 430{
b0db36b1
AL
431 int Res;
432 errno = 0;
433 do
578bfd0a 434 {
b0db36b1
AL
435 Res = read(iFd,To,Size);
436 if (Res < 0 && errno == EINTR)
437 continue;
438 if (Res < 0)
439 {
440 Flags |= Fail;
b2e465d6 441 return _error->Errno("read",_("Read error"));
b0db36b1 442 }
578bfd0a 443
b0db36b1
AL
444 To = (char *)To + Res;
445 Size -= Res;
446 }
447 while (Res > 0 && Size > 0);
448
449 if (Size == 0)
450 return true;
451
ddc1d8d0
AL
452 // Eof handling
453 if (AllowEof == true)
454 {
455 Flags |= HitEof;
456 return true;
457 }
458
b0db36b1 459 Flags |= Fail;
b2e465d6 460 return _error->Error(_("read, still have %lu to read but none left"),Size);
578bfd0a
AL
461}
462 /*}}}*/
8e06abb2 463// FileFd::Write - Write to the file /*{{{*/
578bfd0a
AL
464// ---------------------------------------------------------------------
465/* */
a05599f1 466bool FileFd::Write(const void *From,unsigned long Size)
578bfd0a 467{
b0db36b1
AL
468 int Res;
469 errno = 0;
470 do
578bfd0a 471 {
b0db36b1
AL
472 Res = write(iFd,From,Size);
473 if (Res < 0 && errno == EINTR)
474 continue;
475 if (Res < 0)
476 {
477 Flags |= Fail;
b2e465d6 478 return _error->Errno("write",_("Write error"));
b0db36b1
AL
479 }
480
481 From = (char *)From + Res;
482 Size -= Res;
578bfd0a 483 }
b0db36b1 484 while (Res > 0 && Size > 0);
578bfd0a 485
b0db36b1
AL
486 if (Size == 0)
487 return true;
488
489 Flags |= Fail;
b2e465d6 490 return _error->Error(_("write, still have %lu to write but couldn't"),Size);
578bfd0a
AL
491}
492 /*}}}*/
8e06abb2 493// FileFd::Seek - Seek in the file /*{{{*/
578bfd0a
AL
494// ---------------------------------------------------------------------
495/* */
8e06abb2 496bool FileFd::Seek(unsigned long To)
578bfd0a
AL
497{
498 if (lseek(iFd,To,SEEK_SET) != (signed)To)
499 {
500 Flags |= Fail;
b2e465d6 501 return _error->Error("Unable to seek to %lu",To);
578bfd0a
AL
502 }
503
727f18af
AL
504 return true;
505}
506 /*}}}*/
507// FileFd::Skip - Seek in the file /*{{{*/
508// ---------------------------------------------------------------------
509/* */
510bool FileFd::Skip(unsigned long Over)
511{
512 if (lseek(iFd,Over,SEEK_CUR) < 0)
513 {
514 Flags |= Fail;
b2e465d6 515 return _error->Error("Unable to seek ahead %lu",Over);
727f18af
AL
516 }
517
6d5dd02a
AL
518 return true;
519}
520 /*}}}*/
521// FileFd::Truncate - Truncate the file /*{{{*/
522// ---------------------------------------------------------------------
523/* */
524bool FileFd::Truncate(unsigned long To)
525{
526 if (ftruncate(iFd,To) != 0)
527 {
528 Flags |= Fail;
b2e465d6 529 return _error->Error("Unable to truncate to %lu",To);
6d5dd02a
AL
530 }
531
578bfd0a
AL
532 return true;
533}
534 /*}}}*/
7f25bdff
AL
535// FileFd::Tell - Current seek position /*{{{*/
536// ---------------------------------------------------------------------
537/* */
538unsigned long FileFd::Tell()
539{
540 off_t Res = lseek(iFd,0,SEEK_CUR);
541 if (Res == (off_t)-1)
542 _error->Errno("lseek","Failed to determine the current file position");
543 return Res;
544}
545 /*}}}*/
8e06abb2 546// FileFd::Size - Return the size of the file /*{{{*/
578bfd0a
AL
547// ---------------------------------------------------------------------
548/* */
8e06abb2 549unsigned long FileFd::Size()
578bfd0a
AL
550{
551 struct stat Buf;
552 if (fstat(iFd,&Buf) != 0)
553 return _error->Errno("fstat","Unable to determine the file size");
554 return Buf.st_size;
555}
556 /*}}}*/
8e06abb2 557// FileFd::Close - Close the file if the close flag is set /*{{{*/
578bfd0a
AL
558// ---------------------------------------------------------------------
559/* */
8e06abb2 560bool FileFd::Close()
578bfd0a
AL
561{
562 bool Res = true;
563 if ((Flags & AutoClose) == AutoClose)
1164783d 564 if (iFd >= 0 && close(iFd) != 0)
b2e465d6 565 Res &= _error->Errno("close",_("Problem closing the file"));
1164783d
AL
566 iFd = -1;
567
578bfd0a
AL
568 if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
569 FileName.empty() == false)
570 if (unlink(FileName.c_str()) != 0)
b2e465d6 571 Res &= _error->WarningE("unlnk",_("Problem unlinking the file"));
578bfd0a
AL
572 return Res;
573}
574 /*}}}*/
b2e465d6
AL
575// FileFd::Sync - Sync the file /*{{{*/
576// ---------------------------------------------------------------------
577/* */
578bool FileFd::Sync()
579{
580#ifdef _POSIX_SYNCHRONIZED_IO
581 if (fsync(iFd) != 0)
582 return _error->Errno("sync",_("Problem syncing the file"));
583#endif
584 return true;
585}
586 /*}}}*/