fileutl.cc 11 KB

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