fileutl.cc 10 KB

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