]> git.saurik.com Git - apt.git/blame - apt-pkg/contrib/fileutl.cc
Neuros fix for missing Provides
[apt.git] / apt-pkg / contrib / fileutl.cc
CommitLineData
578bfd0a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
4decd43c 3// $Id: fileutl.cc,v 1.37 2001/03/03 22:45:59 tausq 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;
f08fcf34
AL
406
407 case WriteTemp:
4decd43c
AL
408 unlink(FileName.c_str());
409 iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
f08fcf34 410 break;
578bfd0a
AL
411 }
412
413 if (iFd < 0)
b2e465d6 414 return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
13d87e2e
AL
415
416 this->FileName = FileName;
417 SetCloseExec(iFd,true);
418 return true;
578bfd0a
AL
419}
420 /*}}}*/
8e06abb2 421// FileFd::~File - Closes the file /*{{{*/
578bfd0a
AL
422// ---------------------------------------------------------------------
423/* If the proper modes are selected then we close the Fd and possibly
424 unlink the file on error. */
8e06abb2 425FileFd::~FileFd()
578bfd0a
AL
426{
427 Close();
428}
429 /*}}}*/
8e06abb2 430// FileFd::Read - Read a bit of the file /*{{{*/
578bfd0a 431// ---------------------------------------------------------------------
b0db36b1
AL
432/* We are carefull to handle interruption by a signal while reading
433 gracefully. */
ddc1d8d0 434bool FileFd::Read(void *To,unsigned long Size,bool AllowEof)
578bfd0a 435{
b0db36b1
AL
436 int Res;
437 errno = 0;
438 do
578bfd0a 439 {
b0db36b1
AL
440 Res = read(iFd,To,Size);
441 if (Res < 0 && errno == EINTR)
442 continue;
443 if (Res < 0)
444 {
445 Flags |= Fail;
b2e465d6 446 return _error->Errno("read",_("Read error"));
b0db36b1 447 }
578bfd0a 448
b0db36b1
AL
449 To = (char *)To + Res;
450 Size -= Res;
451 }
452 while (Res > 0 && Size > 0);
453
454 if (Size == 0)
455 return true;
456
ddc1d8d0
AL
457 // Eof handling
458 if (AllowEof == true)
459 {
460 Flags |= HitEof;
461 return true;
462 }
463
b0db36b1 464 Flags |= Fail;
b2e465d6 465 return _error->Error(_("read, still have %lu to read but none left"),Size);
578bfd0a
AL
466}
467 /*}}}*/
8e06abb2 468// FileFd::Write - Write to the file /*{{{*/
578bfd0a
AL
469// ---------------------------------------------------------------------
470/* */
a05599f1 471bool FileFd::Write(const void *From,unsigned long Size)
578bfd0a 472{
b0db36b1
AL
473 int Res;
474 errno = 0;
475 do
578bfd0a 476 {
b0db36b1
AL
477 Res = write(iFd,From,Size);
478 if (Res < 0 && errno == EINTR)
479 continue;
480 if (Res < 0)
481 {
482 Flags |= Fail;
b2e465d6 483 return _error->Errno("write",_("Write error"));
b0db36b1
AL
484 }
485
486 From = (char *)From + Res;
487 Size -= Res;
578bfd0a 488 }
b0db36b1 489 while (Res > 0 && Size > 0);
578bfd0a 490
b0db36b1
AL
491 if (Size == 0)
492 return true;
493
494 Flags |= Fail;
b2e465d6 495 return _error->Error(_("write, still have %lu to write but couldn't"),Size);
578bfd0a
AL
496}
497 /*}}}*/
8e06abb2 498// FileFd::Seek - Seek in the file /*{{{*/
578bfd0a
AL
499// ---------------------------------------------------------------------
500/* */
8e06abb2 501bool FileFd::Seek(unsigned long To)
578bfd0a
AL
502{
503 if (lseek(iFd,To,SEEK_SET) != (signed)To)
504 {
505 Flags |= Fail;
b2e465d6 506 return _error->Error("Unable to seek to %lu",To);
578bfd0a
AL
507 }
508
727f18af
AL
509 return true;
510}
511 /*}}}*/
512// FileFd::Skip - Seek in the file /*{{{*/
513// ---------------------------------------------------------------------
514/* */
515bool FileFd::Skip(unsigned long Over)
516{
517 if (lseek(iFd,Over,SEEK_CUR) < 0)
518 {
519 Flags |= Fail;
b2e465d6 520 return _error->Error("Unable to seek ahead %lu",Over);
727f18af
AL
521 }
522
6d5dd02a
AL
523 return true;
524}
525 /*}}}*/
526// FileFd::Truncate - Truncate the file /*{{{*/
527// ---------------------------------------------------------------------
528/* */
529bool FileFd::Truncate(unsigned long To)
530{
531 if (ftruncate(iFd,To) != 0)
532 {
533 Flags |= Fail;
b2e465d6 534 return _error->Error("Unable to truncate to %lu",To);
6d5dd02a
AL
535 }
536
578bfd0a
AL
537 return true;
538}
539 /*}}}*/
7f25bdff
AL
540// FileFd::Tell - Current seek position /*{{{*/
541// ---------------------------------------------------------------------
542/* */
543unsigned long FileFd::Tell()
544{
545 off_t Res = lseek(iFd,0,SEEK_CUR);
546 if (Res == (off_t)-1)
547 _error->Errno("lseek","Failed to determine the current file position");
548 return Res;
549}
550 /*}}}*/
8e06abb2 551// FileFd::Size - Return the size of the file /*{{{*/
578bfd0a
AL
552// ---------------------------------------------------------------------
553/* */
8e06abb2 554unsigned long FileFd::Size()
578bfd0a
AL
555{
556 struct stat Buf;
557 if (fstat(iFd,&Buf) != 0)
558 return _error->Errno("fstat","Unable to determine the file size");
559 return Buf.st_size;
560}
561 /*}}}*/
8e06abb2 562// FileFd::Close - Close the file if the close flag is set /*{{{*/
578bfd0a
AL
563// ---------------------------------------------------------------------
564/* */
8e06abb2 565bool FileFd::Close()
578bfd0a
AL
566{
567 bool Res = true;
568 if ((Flags & AutoClose) == AutoClose)
1164783d 569 if (iFd >= 0 && close(iFd) != 0)
b2e465d6 570 Res &= _error->Errno("close",_("Problem closing the file"));
1164783d
AL
571 iFd = -1;
572
578bfd0a
AL
573 if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
574 FileName.empty() == false)
575 if (unlink(FileName.c_str()) != 0)
b2e465d6 576 Res &= _error->WarningE("unlnk",_("Problem unlinking the file"));
578bfd0a
AL
577 return Res;
578}
579 /*}}}*/
b2e465d6
AL
580// FileFd::Sync - Sync the file /*{{{*/
581// ---------------------------------------------------------------------
582/* */
583bool FileFd::Sync()
584{
585#ifdef _POSIX_SYNCHRONIZED_IO
586 if (fsync(iFd) != 0)
587 return _error->Errno("sync",_("Problem syncing the file"));
588#endif
589 return true;
590}
591 /*}}}*/