cdromutl.cc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: cdromutl.cc,v 1.12 2001/02/20 07:03:17 jgg Exp $
  4. /* ######################################################################
  5. CDROM Utilities - Some functions to manipulate CDROM mounts.
  6. These are here for the cdrom method and apt-cdrom.
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include<config.h>
  11. #include <apt-pkg/cdromutl.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/md5.h>
  14. #include <apt-pkg/fileutl.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/strutl.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <iostream>
  20. #include <string>
  21. #include <vector>
  22. #include <sys/statvfs.h>
  23. #include <dirent.h>
  24. #include <fcntl.h>
  25. #include <sys/stat.h>
  26. #include <unistd.h>
  27. #include <stdio.h>
  28. #include <apti18n.h>
  29. /*}}}*/
  30. using std::string;
  31. // IsMounted - Returns true if the mount point is mounted /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* This is a simple algorithm that should always work, we stat the mount point
  34. and the '..' file in the mount point and see if they are on the same device.
  35. By definition if they are the same then it is not mounted. This should
  36. account for symlinked mount points as well. */
  37. bool IsMounted(string &Path)
  38. {
  39. if (Path.empty() == true)
  40. return false;
  41. // Need that trailing slash for directories
  42. if (Path[Path.length() - 1] != '/')
  43. Path += '/';
  44. // if the path has a ".disk" directory we treat it as mounted
  45. // this way even extracted copies of disks are recognized
  46. if (DirectoryExists(Path + ".disk/") == true)
  47. return true;
  48. /* First we check if the path is actually mounted, we do this by
  49. stating the path and the previous directory (careful of links!)
  50. and comparing their device fields. */
  51. struct stat Buf,Buf2;
  52. if (stat(Path.c_str(),&Buf) != 0 ||
  53. stat((Path + "../").c_str(),&Buf2) != 0)
  54. return _error->Errno("stat",_("Unable to stat the mount point %s"),Path.c_str());
  55. if (Buf.st_dev == Buf2.st_dev)
  56. return false;
  57. return true;
  58. }
  59. /*}}}*/
  60. // UnmountCdrom - Unmount a cdrom /*{{{*/
  61. // ---------------------------------------------------------------------
  62. /* Forking umount works much better than the umount syscall which can
  63. leave /etc/mtab inconsitant. We drop all messages this produces. */
  64. bool UnmountCdrom(string Path)
  65. {
  66. // do not generate errors, even if the mountpoint does not exist
  67. // the mountpoint might be auto-created by the mount command
  68. // and a non-existing mountpoint is surely not mounted
  69. _error->PushToStack();
  70. bool const mounted = IsMounted(Path);
  71. _error->RevertToStack();
  72. if (mounted == false)
  73. return true;
  74. for (int i=0;i<3;i++)
  75. {
  76. int Child = ExecFork();
  77. // The child
  78. if (Child == 0)
  79. {
  80. // Make all the fds /dev/null
  81. int const null_fd = open("/dev/null",O_RDWR);
  82. for (int I = 0; I != 3; ++I)
  83. dup2(null_fd, I);
  84. if (_config->Exists("Acquire::cdrom::"+Path+"::UMount") == true)
  85. {
  86. if (system(_config->Find("Acquire::cdrom::"+Path+"::UMount").c_str()) != 0)
  87. _exit(100);
  88. _exit(0);
  89. }
  90. else
  91. {
  92. const char *Args[10];
  93. Args[0] = "umount";
  94. Args[1] = Path.c_str();
  95. Args[2] = 0;
  96. execvp(Args[0],(char **)Args);
  97. _exit(100);
  98. }
  99. }
  100. // if it can not be umounted, give it a bit more time
  101. // this can happen when auto-mount magic or fs/cdrom prober attack
  102. if (ExecWait(Child,"umount",true) == true)
  103. return true;
  104. sleep(1);
  105. }
  106. return false;
  107. }
  108. /*}}}*/
  109. // MountCdrom - Mount a cdrom /*{{{*/
  110. // ---------------------------------------------------------------------
  111. /* We fork mount and drop all messages */
  112. bool MountCdrom(string Path, string DeviceName)
  113. {
  114. // do not generate errors, even if the mountpoint does not exist
  115. // the mountpoint might be auto-created by the mount command
  116. _error->PushToStack();
  117. bool const mounted = IsMounted(Path);
  118. _error->RevertToStack();
  119. if (mounted == true)
  120. return true;
  121. int Child = ExecFork();
  122. // The child
  123. if (Child == 0)
  124. {
  125. // Make all the fds /dev/null
  126. int const null_fd = open("/dev/null",O_RDWR);
  127. for (int I = 0; I != 3; ++I)
  128. dup2(null_fd, I);
  129. if (_config->Exists("Acquire::cdrom::"+Path+"::Mount") == true)
  130. {
  131. if (system(_config->Find("Acquire::cdrom::"+Path+"::Mount").c_str()) != 0)
  132. _exit(100);
  133. _exit(0);
  134. }
  135. else
  136. {
  137. const char *Args[10];
  138. Args[0] = "mount";
  139. if (DeviceName == "")
  140. {
  141. Args[1] = Path.c_str();
  142. Args[2] = 0;
  143. } else {
  144. Args[1] = DeviceName.c_str();
  145. Args[2] = Path.c_str();
  146. Args[3] = 0;
  147. }
  148. execvp(Args[0],(char **)Args);
  149. _exit(100);
  150. }
  151. }
  152. // Wait for mount
  153. return ExecWait(Child,"mount",true);
  154. }
  155. /*}}}*/
  156. // IdentCdrom - Generate a unique string for this CD /*{{{*/
  157. // ---------------------------------------------------------------------
  158. /* We convert everything we hash into a string, this prevents byte size/order
  159. from effecting the outcome. */
  160. bool IdentCdrom(string CD,string &Res,unsigned int Version)
  161. {
  162. MD5Summation Hash;
  163. bool writable_media = false;
  164. // if we are on a writable medium (like a usb-stick) that is just
  165. // used like a cdrom don't use "." as it will constantly change,
  166. // use .disk instead
  167. if (access(CD.c_str(), W_OK) == 0 && DirectoryExists(CD+string("/.disk")))
  168. {
  169. writable_media = true;
  170. CD = CD.append("/.disk");
  171. if (_config->FindB("Debug::aptcdrom",false) == true)
  172. std::clog << "Found writable cdrom, using alternative path: " << CD
  173. << std::endl;
  174. }
  175. string StartDir = SafeGetCWD();
  176. if (chdir(CD.c_str()) != 0)
  177. return _error->Errno("chdir",_("Unable to change to %s"),CD.c_str());
  178. DIR *D = opendir(".");
  179. if (D == 0)
  180. return _error->Errno("opendir",_("Unable to read %s"),CD.c_str());
  181. /* Run over the directory, we assume that the reader order will never
  182. change as the media is read-only. In theory if the kernel did
  183. some sort of wacked caching this might not be true.. */
  184. for (struct dirent *Dir = readdir(D); Dir != 0; Dir = readdir(D))
  185. {
  186. // Skip some files..
  187. if (strcmp(Dir->d_name,".") == 0 ||
  188. strcmp(Dir->d_name,"..") == 0)
  189. continue;
  190. std::string S;
  191. if (Version <= 1)
  192. {
  193. strprintf(S, "%lu", (unsigned long)Dir->d_ino);
  194. }
  195. else
  196. {
  197. struct stat Buf;
  198. if (stat(Dir->d_name,&Buf) != 0)
  199. continue;
  200. strprintf(S, "%lu", (unsigned long)Buf.st_mtime);
  201. }
  202. Hash.Add(S.c_str());
  203. Hash.Add(Dir->d_name);
  204. };
  205. if (chdir(StartDir.c_str()) != 0) {
  206. _error->Errno("chdir",_("Unable to change to %s"),StartDir.c_str());
  207. closedir(D);
  208. return false;
  209. }
  210. closedir(D);
  211. // Some stats from the fsys
  212. std::string S;
  213. if (_config->FindB("Debug::identcdrom",false) == false)
  214. {
  215. struct statvfs Buf;
  216. if (statvfs(CD.c_str(),&Buf) != 0)
  217. return _error->Errno("statfs",_("Failed to stat the cdrom"));
  218. // We use a kilobyte block size to advoid overflow
  219. if (writable_media)
  220. {
  221. strprintf(S, "%lu", (unsigned long)(Buf.f_blocks*(Buf.f_bsize/1024)));
  222. } else {
  223. strprintf(S, "%lu %lu", (unsigned long)(Buf.f_blocks*(Buf.f_bsize/1024)),
  224. (unsigned long)(Buf.f_bfree*(Buf.f_bsize/1024)));
  225. }
  226. Hash.Add(S.c_str());
  227. strprintf(S, "-%u", Version);
  228. }
  229. else
  230. strprintf(S, "-%u.debug", Version);
  231. Res = Hash.Result().Value() + S;
  232. return true;
  233. }
  234. /*}}}*/
  235. // FindMountPointForDevice - Find mountpoint for the given device /*{{{*/
  236. string FindMountPointForDevice(const char *devnode)
  237. {
  238. // this is the order that mount uses as well
  239. std::vector<std::string> const mounts = _config->FindVector("Dir::state::MountPoints", "/etc/mtab,/proc/mount");
  240. for (std::vector<std::string>::const_iterator m = mounts.begin(); m != mounts.end(); ++m)
  241. if (FileExists(*m) == true)
  242. {
  243. char * line = NULL;
  244. size_t line_len = 0;
  245. FILE * f = fopen(m->c_str(), "r");
  246. while(getline(&line, &line_len, f) != -1)
  247. {
  248. char * out[] = { NULL, NULL, NULL };
  249. TokSplitString(' ', line, out, 3);
  250. if (out[2] != NULL || out[1] == NULL || out[0] == NULL)
  251. continue;
  252. if (strcmp(out[0], devnode) != 0)
  253. continue;
  254. fclose(f);
  255. // unescape the \0XXX chars in the path
  256. string mount_point = out[1];
  257. free(line);
  258. return DeEscapeString(mount_point);
  259. }
  260. fclose(f);
  261. free(line);
  262. }
  263. return string();
  264. }
  265. /*}}}*/