]>
git.saurik.com Git - hfs.git/blob - CopyHFSMeta/SparseBundle.c
10 #include <sys/fcntl.h>
11 #include <removefile.h>
13 #include <CoreFoundation/CoreFoundation.h>
14 #include <System/sys/fsctl.h>
20 * Routines to maniupulate a sparse bundle.
21 * N.B.: The sparse bundle format it uses is a subset of
22 * the real sparse bundle format: no partition map, and
27 ({ __typeof(a) __a = (a); __typeof(b) __b = (b); \
28 __a < __b ? __a : __b; })
31 * Context for the sparse bundle routines. The path name,
32 * size of the band files, and cached file descriptor and
33 * band numbers, to reduce the amount of pathname lookups
36 struct SparseBundleContext
{
39 int cfd
; // Cached file descriptor
40 int cBandNum
; // cached bandfile number
43 static const int kBandSize
= 8388608;
45 // Prototype bundle Info.plist file
46 static const char *bundlePrototype
=
47 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
48 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
49 "<plist version=\"1.0\">\n"
51 "\t<key>CFBundleInfoDictionaryVersion</key>\n"
52 "\t<string>6.0</string>\n"
53 "\t<key>band-size</key>\n"
54 "\t<integer>%d</integer>\n"
55 "\t<key>bundle-backingstore-version</key>\n"
56 "\t<integer>1</integer>\n"
57 "\t<key>diskimage-bundle-type</key>\n"
58 "\t<string>com.apple.diskimage.sparsebundle</string>\n"
60 "\t<integer>%llu</integer>\n"
65 * Perform a (potentially) unaligned read from a given input device.
68 UnalignedRead(DeviceInfo_t
*devp
, void *buffer
, size_t size
, off_t offset
)
71 size_t readSize
= ((size
+ devp
->blockSize
- 1) / devp
->blockSize
) * devp
->blockSize
;
72 off_t baseOffset
= (offset
/ devp
->blockSize
) * devp
->blockSize
;
73 size_t off
= offset
- baseOffset
;
76 if ((baseOffset
== offset
) && (readSize
== size
)) {
78 * The read is already properly aligned, so call pread.
80 return pread(devp
->fd
, buffer
, size
, offset
);
83 tmpbuf
= malloc(readSize
);
88 nread
= pread(devp
->fd
, tmpbuf
, readSize
, baseOffset
);
94 if (nread
> (ssize_t
)size
) {
97 memcpy(buffer
, tmpbuf
+ off
, nread
);
105 * Read from a sparse bundle. If the band file doesn't exist, or is shorter than
106 * what we need to get from it, we pad out with 0's.
109 doSparseRead(struct IOWrapper
*context
, off_t offset
, void *buffer
, off_t len
)
111 struct SparseBundleContext
*ctx
= context
->context
;
112 off_t blockSize
= ctx
->bandSize
;
116 while (nread
< len
) {
117 off_t bandNum
= (offset
+ nread
) / blockSize
; // Which band file to use
118 off_t bandOffset
= (offset
+ nread
) % blockSize
; // how far to go into the file
119 size_t amount
= MIN(len
- nread
, blockSize
- bandOffset
); // How many bytes to write in this band file
125 asprintf(&bandName
, "%s/bands/%x", ctx
->pathname
, bandNum
);
126 fd
= open(bandName
, O_RDONLY
);
128 if (errno
== ENOENT
) {
129 // Doesn't exist, so we just write zeroes
131 memset(buffer
+ nread
, 0, amount
);
135 warn("Cannot open band file %s for offset %llu", bandName
, offset
+ nread
);
140 n
= pread(fd
, (char*)buffer
+ nread
, amount
, bandOffset
);
142 warn("Cannot write to band file %s/band/%x for offset %llu for amount %zu", ctx
->pathname
, bandNum
, offset
+nread
, amount
);
146 if (n
< amount
) { // hit EOF, pad out with zeroes
147 memset(buffer
+ nread
+ amount
, 0, amount
- n
);
158 * Write a chunk of data to a bundle.
161 doSparseWrite(IOWrapper_t
*context
, off_t offset
, void *buffer
, size_t len
)
163 struct SparseBundleContext
*ctx
= context
->context
;
164 off_t blockSize
= ctx
->bandSize
;
168 while (written
< len
) {
169 off_t bandNum
= (offset
+ written
) / blockSize
; // Which band file to use
170 off_t bandOffset
= (offset
+ written
) % blockSize
; // how far to go into the file
171 size_t amount
= MIN(len
- written
, blockSize
- bandOffset
); // How many bytes to write in this band file
176 if (ctx
->cfd
== -1 || ctx
->cBandNum
!= bandNum
) {
177 if (ctx
->cfd
!= -1) {
180 asprintf(&bandName
, "%s/bands/%x", ctx
->pathname
, bandNum
);
181 fd
= open(bandName
, O_WRONLY
| O_CREAT
, 0666);
183 warn("Cannot open band file %s for offset %llu", bandName
, offset
+ written
);
188 * When we create a new band file, we sync the volume
189 * it's on, so that we can ensure that the band file is present
190 * on disk. (Otherwise, with a crash, we can end up with the
191 * data not where we expected.) In this case, however, we probably
192 * don't need to wait for it -- just start the sync.
194 fsync_volume_np(fd
, 0);
195 fcntl(fd
, F_NOCACHE
, 1);
199 ctx
->cBandNum
= bandNum
;
203 nwritten
= pwrite(fd
, (char*)buffer
+ written
, amount
, bandOffset
);
204 if (nwritten
== -1) {
205 warn("Cannot write to band file %s/band/%x for offset %llu for amount %zu", ctx
->pathname
, bandNum
, offset
+written
, amount
);
211 // Sync the data out.
222 * Write a given extent (<start, length> pair) from an input device to the
223 * sparse bundle. We also use a block to update progress.
226 WriteExtentToSparse(struct IOWrapper
* context
, DeviceInfo_t
*devp
, off_t start
, off_t len
, void (^bp
)(off_t
))
228 const size_t bufSize
= 1024 * 1024;
229 uint8_t *buffer
= NULL
;
233 if (debug
) printf("Writing extent <%lld, %lld>\n", start
, len
);
234 buffer
= malloc(bufSize
);
235 if (buffer
== NULL
) {
236 warn("%s(%s): Could not allocate %zu bytes for buffer", __FILE__
, __FUNCTION__
, bufSize
);
241 while (total
< len
) {
244 size_t amt
= MIN(bufSize
, len
- total
);
245 nread
= UnalignedRead(devp
, buffer
, amt
, start
+ total
);
247 warn("Cannot read from device at offset %lld", start
+ total
);
252 warnx("Short read from source device -- got %zd, expected %zd", nread
, amt
);
254 nwritten
= doSparseWrite(context
, start
+ total
, buffer
, nread
);
255 if (nwritten
== -1) {
262 if (debug
) printf("\twrote %lld\n", total
);
269 static const CFStringRef kBandSizeKey
= CFSTR("band-size");
270 static const CFStringRef kDevSizeKey
= CFSTR("size");
273 * We need to be able to get the size of the "device" from a sparse bundle;
274 * we do this by using CF routines to parse the Info.plist file, and then
275 * get the two keys we care about: band-size (size of the band files), and
276 * size (size -- in bytes -- of the "disk").
279 GetSizesFromPlist(const char *path
, size_t *bandSize
, off_t
*devSize
)
282 CFReadStreamRef inFile
= NULL
;
283 CFURLRef inFileURL
= NULL
;
284 CFStringRef cfPath
= NULL
;
285 CFPropertyListRef cfDict
= NULL
;
286 CFNumberRef cfVal
= NULL
;
291 inFileURL
= CFURLCreateFromFileSystemRepresentation(NULL
, path
, strlen(path
), FALSE
);
292 if (inFileURL
== NULL
) {
293 if (debug
) warn("Cannot create url from pathname %s", path
);
297 inFile
= CFReadStreamCreateWithFile(NULL
, inFileURL
);
298 if (inFile
== NULL
) {
299 if (debug
) warn("cannot create read stream from path %s", path
);
303 if (CFReadStreamOpen(inFile
) == FALSE
) {
304 if (debug
) warn("cannot open read stream");
308 cfDict
= CFPropertyListCreateWithStream(NULL
, inFile
, 0, 0, NULL
, NULL
);
309 if (cfDict
== NULL
) {
310 if (debug
) warnx("cannot create propertly list from stream for path %s", path
);
314 cfVal
= CFDictionaryGetValue(cfDict
, kBandSizeKey
);
316 if (debug
) warnx("cannot get bandsize key from plist");
320 if (CFNumberGetValue(cfVal
, kCFNumberIntType
, &tmpInt
) == false) {
321 if (debug
) warnx("cannot get value from band size number");
327 cfVal
= CFDictionaryGetValue(cfDict
, kDevSizeKey
);
329 if (debug
) warnx("cannot get dev size key from plist");
332 if (CFNumberGetValue(cfVal
, kCFNumberLongLongType
, &tmpLL
) == false) {
344 CFRelease(inFileURL
);
352 #define kProgressName "HC.progress.txt"
355 * Get the progress state from a sparse bundle. If it's not there, then
359 GetProgress(struct IOWrapper
*context
)
361 struct SparseBundleContext
*ctx
= context
->context
;
364 char progFile
[strlen(ctx
->pathname
) + sizeof(kProgressName
) + 2]; // '/' and NUL
366 sprintf(progFile
, "%s/%s", ctx
->pathname
, kProgressName
);
367 fp
= fopen(progFile
, "r");
371 if (fscanf(fp
, "%llu", &retval
) != 1) {
380 * Write the progress information out. This involves writing a file in
381 * the sparse bundle with the amount -- in bytes -- we've written so far.
384 SetProgress(struct IOWrapper
*context
, off_t prog
)
386 struct SparseBundleContext
*ctx
= context
->context
;
388 char progFile
[strlen(ctx
->pathname
) + sizeof(kProgressName
) + 2]; // '/' and NUL
390 sprintf(progFile
, "%s/%s", ctx
->pathname
, kProgressName
);
394 fp
= fopen(progFile
, "w");
396 (void)fprintf(fp
, "%llu\n", prog
);
404 * Clean up. This is used when we have to initialize the bundle, but don't
405 * have any progress information -- in that case, we don't want to have any
406 * of the old band files laying around. We use removefile() to recursively
407 * remove them, but keep the bands directory.
410 doCleanup(struct IOWrapper
*ctx
)
412 struct SparseBundleContext
*context
= ctx
->context
;
414 char bandsDir
[strlen(context
->pathname
) + sizeof("/bands") + 1]; // 1 for NUL
416 sprintf(bandsDir
, "%s/bands", context
->pathname
);
419 fprintf(stderr
, "Cleaning up, about to call removefile\n");
420 rv
= removefile(bandsDir
, NULL
, REMOVEFILE_RECURSIVE
| REMOVEFILE_KEEP_PARENT
);
422 fprintf(stderr
, "removefile returned %d\n", rv
);
424 return (rv
== 0) ? 0 : -1;
428 * Initialize the IOWrapper structure for a sparse bundle. This will
429 * create the bundle directory (but not its parents!) if needed, and
430 * will populate it out. It checks to see if there is an existing bundle
431 * of the same name, and, if so, ensures that the izes are correct. Then
432 * it sets up all the function pointers.
435 InitSparseBundle(const char *path
, DeviceInfo_t
*devp
)
437 struct SparseBundleContext ctx
= { 0 };
438 struct SparseBundleContext
*retctx
= NULL
;
439 IOWrapper_t
*retval
= NULL
;
441 char tmpname
[strlen(path
) + sizeof("Info.plist") + 2]; // '/' + NUL
443 if (strstr(path
, ".sparsebundle") == NULL
) {
444 asprintf(&ctx
.pathname
, "%s.sparsebundle", path
);
446 ctx
.pathname
= strdup(path
);
449 if (lstat(ctx
.pathname
, &sb
) == -1) {
450 if (errno
!= ENOENT
) {
451 warn("cannot check sparse bundle %s", ctx
.pathname
);
454 if (mkdir(ctx
.pathname
, 0777) == -1) {
455 warn("cannot create sparse bundle %s", ctx
.pathname
);
458 } else if ((sb
.st_mode
& S_IFMT
) != S_IFDIR
) {
459 warnx("sparse bundle object %s is not a directory", ctx
.pathname
);
462 sprintf(tmpname
, "%s/Info.plist", ctx
.pathname
);
463 if (stat(tmpname
, &sb
) != -1) {
466 if (GetSizesFromPlist(tmpname
, &bandSize
, &devSize
) == -1) {
467 warnx("Existing sparse bundle can't be parsed");
471 printf("Existing sparse bundle size = %lld, bandsize = %zu\n", devSize
, bandSize
);
473 if (devSize
!= devp
->size
) {
474 warnx("Existing sparse bundle size (%lld) != dev size (%lld)", devSize
, devp
->size
);
477 ctx
.bandSize
= bandSize
;
479 FILE *fp
= fopen(tmpname
, "w");
481 warn("cannot create sparse bundle info plist %s", tmpname
);
484 ctx
.bandSize
= kBandSize
;
485 fprintf(fp
, bundlePrototype
, kBandSize
, devp
->size
);
487 sprintf(tmpname
, "%s/Info.bckup", ctx
.pathname
);
488 fp
= fopen(tmpname
, "w");
490 fprintf(fp
, bundlePrototype
, kBandSize
, devp
->size
);
493 sprintf(tmpname
, "%s/bands", ctx
.pathname
);
494 if (mkdir(tmpname
, 0777) == -1) {
495 warn("cannot create bands directory in sparse bundle %s", ctx
.pathname
);
498 sprintf(tmpname
, "%s/token", ctx
.pathname
);
499 close(open(tmpname
, O_CREAT
| O_TRUNC
, 0666));
502 retval
= malloc(sizeof(*retval
));
503 if (retval
== NULL
) {
508 retctx
= malloc(sizeof(*retctx
));
514 retval
->writer
= &WriteExtentToSparse
;
515 retval
->reader
= &doSparseRead
;
516 retval
->getprog
= &GetProgress
;
517 retval
->setprog
= &SetProgress
;
518 retval
->cleanup
= &doCleanup
;
520 retval
->context
= retctx
;
522 if (retval
== NULL
) {