fileutl.cc 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: fileutl.cc,v 1.16 1998/11/27 04:20:52 jgg Exp $
  4. /* ######################################################################
  5. File Utilities
  6. CopyFile - Buffered copy of a single file
  7. GetLock - dpkg compatible lock file manipulation (fcntl)
  8. This source is placed in the Public Domain, do with it what you will
  9. It was originally written by Jason Gunthorpe.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #ifdef __GNUG__
  14. #pragma implementation "apt-pkg/fileutl.h"
  15. #endif
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/error.h>
  18. #include <unistd.h>
  19. #include <sys/stat.h>
  20. #include <sys/fcntl.h>
  21. #include <sys/types.h>
  22. /*}}}*/
  23. // CopyFile - Buffered copy of a file /*{{{*/
  24. // ---------------------------------------------------------------------
  25. /* The caller is expected to set things so that failure causes erasure */
  26. bool CopyFile(FileFd &From,FileFd &To)
  27. {
  28. if (From.IsOpen() == false || To.IsOpen() == false)
  29. return false;
  30. // Buffered copy between fds
  31. unsigned char *Buf = new unsigned char[64000];
  32. long Size;
  33. while ((Size = read(From.Fd(),Buf,64000)) > 0)
  34. {
  35. if (To.Write(Buf,Size) == false)
  36. {
  37. delete [] Buf;
  38. return false;
  39. }
  40. }
  41. delete [] Buf;
  42. return true;
  43. }
  44. /*}}}*/
  45. // GetLock - Gets a lock file /*{{{*/
  46. // ---------------------------------------------------------------------
  47. /* This will create an empty file of the given name and lock it. Once this
  48. is done all other calls to GetLock in any other process will fail with
  49. -1. The return result is the fd of the file, the call should call
  50. close at some time. */
  51. int GetLock(string File,bool Errors)
  52. {
  53. int FD = open(File.c_str(),O_RDWR | O_CREAT | O_TRUNC,0640);
  54. if (FD < 0)
  55. {
  56. if (Errors == true)
  57. _error->Errno("open","Could not open lock file %s",File.c_str());
  58. return -1;
  59. }
  60. // Aquire a write lock
  61. struct flock fl;
  62. fl.l_type= F_WRLCK;
  63. fl.l_whence= SEEK_SET;
  64. fl.l_start= 0;
  65. fl.l_len= 1;
  66. if (fcntl(FD,F_SETLK,&fl) == -1)
  67. {
  68. if (Errors == true)
  69. _error->Errno("open","Could not get lock %s",File.c_str());
  70. close(FD);
  71. return -1;
  72. }
  73. return FD;
  74. }
  75. /*}}}*/
  76. // FileExists - Check if a file exists /*{{{*/
  77. // ---------------------------------------------------------------------
  78. /* */
  79. bool FileExists(string File)
  80. {
  81. struct stat Buf;
  82. if (stat(File.c_str(),&Buf) != 0)
  83. return false;
  84. return true;
  85. }
  86. /*}}}*/
  87. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  88. // ---------------------------------------------------------------------
  89. /* We return / on failure. */
  90. string SafeGetCWD()
  91. {
  92. // Stash the current dir.
  93. char S[300];
  94. S[0] = 0;
  95. if (getcwd(S,sizeof(S)) == 0)
  96. return "/";
  97. return S;
  98. }
  99. /*}}}*/
  100. // flNotDir - Strip the directory from the filename /*{{{*/
  101. // ---------------------------------------------------------------------
  102. /* */
  103. string flNotDir(string File)
  104. {
  105. string::size_type Res = File.rfind('/');
  106. if (Res == string::npos)
  107. return File;
  108. Res++;
  109. return string(File,Res,Res - File.length());
  110. }
  111. /*}}}*/
  112. // flNotFile - Strip the file from the directory name /*{{{*/
  113. // ---------------------------------------------------------------------
  114. /* */
  115. string flNotFile(string File)
  116. {
  117. string::size_type Res = File.rfind('/');
  118. if (Res == string::npos)
  119. return File;
  120. Res++;
  121. return string(File,0,Res);
  122. }
  123. /*}}}*/
  124. // SetCloseExec - Set the close on exec flag /*{{{*/
  125. // ---------------------------------------------------------------------
  126. /* */
  127. void SetCloseExec(int Fd,bool Close)
  128. {
  129. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  130. {
  131. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  132. exit(100);
  133. }
  134. }
  135. /*}}}*/
  136. // SetNonBlock - Set the nonblocking flag /*{{{*/
  137. // ---------------------------------------------------------------------
  138. /* */
  139. void SetNonBlock(int Fd,bool Block)
  140. {
  141. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  142. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  143. {
  144. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  145. exit(100);
  146. }
  147. }
  148. /*}}}*/
  149. // WaitFd - Wait for a FD to become readable /*{{{*/
  150. // ---------------------------------------------------------------------
  151. /* This waits for a FD to become readable using select. It is usefull for
  152. applications making use of non-blocking sockets. */
  153. bool WaitFd(int Fd)
  154. {
  155. fd_set Set;
  156. FD_ZERO(&Set);
  157. FD_SET(Fd,&Set);
  158. if (select(Fd+1,&Set,0,0,0) <= 0)
  159. return false;
  160. return true;
  161. }
  162. /*}}}*/
  163. // FileFd::FileFd - Open a file /*{{{*/
  164. // ---------------------------------------------------------------------
  165. /* The most commonly used open mode combinations are given with Mode */
  166. FileFd::FileFd(string FileName,OpenMode Mode, unsigned long Perms)
  167. {
  168. Flags = AutoClose;
  169. switch (Mode)
  170. {
  171. case ReadOnly:
  172. iFd = open(FileName.c_str(),O_RDONLY);
  173. break;
  174. case WriteEmpty:
  175. {
  176. struct stat Buf;
  177. if (stat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  178. unlink(FileName.c_str());
  179. iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_TRUNC,Perms);
  180. break;
  181. }
  182. case WriteExists:
  183. iFd = open(FileName.c_str(),O_RDWR);
  184. break;
  185. case WriteAny:
  186. iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms);
  187. break;
  188. }
  189. if (iFd < 0)
  190. _error->Errno("open","Could not open file %s",FileName.c_str());
  191. else
  192. {
  193. this->FileName = FileName;
  194. SetCloseExec(iFd,true);
  195. }
  196. }
  197. /*}}}*/
  198. // FileFd::~File - Closes the file /*{{{*/
  199. // ---------------------------------------------------------------------
  200. /* If the proper modes are selected then we close the Fd and possibly
  201. unlink the file on error. */
  202. FileFd::~FileFd()
  203. {
  204. Close();
  205. }
  206. /*}}}*/
  207. // FileFd::Read - Read a bit of the file /*{{{*/
  208. // ---------------------------------------------------------------------
  209. /* */
  210. bool FileFd::Read(void *To,unsigned long Size)
  211. {
  212. if (read(iFd,To,Size) != (signed)Size)
  213. {
  214. Flags |= Fail;
  215. return _error->Errno("read","Read error");
  216. }
  217. return true;
  218. }
  219. /*}}}*/
  220. // FileFd::Write - Write to the file /*{{{*/
  221. // ---------------------------------------------------------------------
  222. /* */
  223. bool FileFd::Write(const void *From,unsigned long Size)
  224. {
  225. if (write(iFd,From,Size) != (signed)Size)
  226. {
  227. Flags |= Fail;
  228. return _error->Errno("write","Write error");
  229. }
  230. return true;
  231. }
  232. /*}}}*/
  233. // FileFd::Seek - Seek in the file /*{{{*/
  234. // ---------------------------------------------------------------------
  235. /* */
  236. bool FileFd::Seek(unsigned long To)
  237. {
  238. if (lseek(iFd,To,SEEK_SET) != (signed)To)
  239. {
  240. Flags |= Fail;
  241. return _error->Error("Unable to seek to %u",To);
  242. }
  243. return true;
  244. }
  245. /*}}}*/
  246. // FileFd::Size - Return the size of the file /*{{{*/
  247. // ---------------------------------------------------------------------
  248. /* */
  249. unsigned long FileFd::Size()
  250. {
  251. struct stat Buf;
  252. if (fstat(iFd,&Buf) != 0)
  253. return _error->Errno("fstat","Unable to determine the file size");
  254. return Buf.st_size;
  255. }
  256. /*}}}*/
  257. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  258. // ---------------------------------------------------------------------
  259. /* */
  260. bool FileFd::Close()
  261. {
  262. bool Res = true;
  263. if ((Flags & AutoClose) == AutoClose)
  264. if (iFd >= 0 && close(iFd) != 0)
  265. Res &= _error->Errno("close","Problem closing the file");
  266. iFd = -1;
  267. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  268. FileName.empty() == false)
  269. if (unlink(FileName.c_str()) != 0)
  270. Res &= _error->Warning("unlnk","Problem unlinking the file");
  271. return Res;
  272. }
  273. /*}}}*/