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