lock.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * lock.c - packages database locking
  4. *
  5. * Copyright (C) 1994,1995 Ian Jackson <iwj10@cus.cam.ac.uk>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2,
  10. * or (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public
  18. * License along with dpkg; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <unistd.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <errno.h>
  25. #include <unistd.h>
  26. #include <assert.h>
  27. #include <fcntl.h>
  28. #include <sys/file.h>
  29. #include <config.h>
  30. #include <dpkg.h>
  31. #include <dpkg-db.h>
  32. static char *dblockfile= 0;
  33. static int dblockfd= -1;
  34. static void cu_unlockdb(int argc, void **argv) {
  35. struct flock fl;
  36. assert(dblockfile);
  37. assert(dblockfd >= 0);
  38. fl.l_type= F_UNLCK;
  39. fl.l_whence= SEEK_SET;
  40. fl.l_start= 0;
  41. fl.l_len= 0;
  42. if (fcntl(dblockfd,F_SETLK,&fl) == -1)
  43. ohshite(_("unable to unlock dpkg status database"));
  44. }
  45. void unlockdatabase(const char *admindir) {
  46. pop_cleanup(ehflag_normaltidy); /* calls cu_unlockdb */
  47. }
  48. void lockdatabase(const char *admindir) {
  49. int n;
  50. struct flock fl;
  51. if (!dblockfile) {
  52. n= strlen(admindir);
  53. dblockfile= m_malloc(n+sizeof(LOCKFILE)+2);
  54. strcpy(dblockfile,admindir);
  55. strcpy(dblockfile+n, "/" LOCKFILE);
  56. }
  57. if (dblockfd == -1) {
  58. dblockfd= open(dblockfile, O_RDWR|O_CREAT|O_TRUNC, 0660);
  59. if (dblockfd == -1) {
  60. if (errno == EPERM)
  61. ohshit(_("you do not have permission to lock the dpkg status database"));
  62. ohshite(_("unable to open/create status database lockfile"));
  63. }
  64. }
  65. fl.l_type= F_WRLCK;
  66. fl.l_whence= SEEK_SET;
  67. fl.l_start= 0;
  68. fl.l_len= 0;
  69. if (fcntl(dblockfd,F_SETLK,&fl) == -1) {
  70. if (errno == EACCES || errno == EAGAIN)
  71. ohshit(_("status database area is locked by another process"));
  72. ohshite(_("unable to lock dpkg status database"));
  73. }
  74. n= fcntl(dblockfd, F_GETFD);
  75. if (n >= 0) fcntl(dblockfd, F_SETFD, n | FD_CLOEXEC);
  76. push_cleanup(cu_unlockdb,~0, 0,0, 0);
  77. }