fileutl.cc 8.6 KB

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