]>
git.saurik.com Git - apple/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
28 ({ __typeof(a) __a = (a); __typeof(b) __b = (b); \
29 __a < __b ? __a : __b; })
33 * Context for the sparse bundle routines. The path name,
34 * size of the band files, and cached file descriptor and
35 * band numbers, to reduce the amount of pathname lookups
38 struct SparseBundleContext
{
41 int cfd
; // Cached file descriptor
42 int cBandNum
; // cached bandfile number
45 static const int kBandSize
= 8388608;
47 // Prototype bundle Info.plist file
48 static const char *bundlePrototype
=
49 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
50 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
51 "<plist version=\"1.0\">\n"
53 "\t<key>CFBundleInfoDictionaryVersion</key>\n"
54 "\t<string>6.0</string>\n"
55 "\t<key>band-size</key>\n"
56 "\t<integer>%d</integer>\n"
57 "\t<key>bundle-backingstore-version</key>\n"
58 "\t<integer>1</integer>\n"
59 "\t<key>diskimage-bundle-type</key>\n"
60 "\t<string>com.apple.diskimage.sparsebundle</string>\n"
62 "\t<integer>%llu</integer>\n"
68 * Read from a sparse bundle. If the band file doesn't exist, or is shorter than
69 * what we need to get from it, we pad out with 0's.
72 doSparseRead(struct IOWrapper
*context
, off_t offset
, void *buffer
, off_t len
)
74 struct SparseBundleContext
*ctx
= context
->context
;
75 off_t blockSize
= ctx
->bandSize
;
80 off_t bandNum
= (offset
+ nread
) / blockSize
; // Which band file to use
81 off_t bandOffset
= (offset
+ nread
) % blockSize
; // how far to go into the file
82 ssize_t amount
= MIN(len
- nread
, blockSize
- bandOffset
); // How many bytes to write in this band file
87 asprintf(&bandName
, "%s/bands/%llx", ctx
->pathname
, bandNum
);
89 warn("Cannot allocate memory for path '%s/bands/%llx'", ctx
->pathname
, bandNum
);
93 fd
= open(bandName
, O_RDONLY
);
95 if (errno
== ENOENT
) {
96 // Doesn't exist, so we just write zeroes
98 memset(buffer
+ nread
, 0, amount
);
102 warn("Cannot open band file %s for offset %llu", bandName
, offset
+ nread
);
108 n
= pread(fd
, (char*)buffer
+ nread
, amount
, bandOffset
);
110 warn("Cannot read from band file %s for offset %llu for amount %zu", bandName
, offset
+nread
, amount
);
115 if (n
< amount
) { // hit EOF, pad out with zeroes
116 memset(buffer
+ nread
+ amount
, 0, amount
- n
);
129 * Write a chunk of data to a bundle.
132 doSparseWrite(IOWrapper_t
*context
, off_t offset
, void *buffer
, off_t len
)
134 struct SparseBundleContext
*ctx
= context
->context
;
135 off_t blockSize
= ctx
->bandSize
;
139 while (written
< len
) {
140 off_t bandNum
= (offset
+ written
) / blockSize
; // Which band file to use
141 off_t bandOffset
= (offset
+ written
) % blockSize
; // how far to go into the file
142 size_t amount
= MIN(len
- written
, blockSize
- bandOffset
); // How many bytes to write in this band file
146 if (ctx
->cfd
== -1 || ctx
->cBandNum
!= bandNum
) {
147 char *bandName
= NULL
;
149 if (ctx
->cfd
!= -1) {
153 asprintf(&bandName
, "%s/bands/%llx", ctx
->pathname
, bandNum
);
155 warnx("Cannot allocate memory for band %s/bands/%llx", ctx
->pathname
, bandNum
);
160 fd
= open(bandName
, O_WRONLY
| O_CREAT
, 0666);
162 warn("Cannot open band file %s for offset %llu", bandName
, offset
+ written
);
168 * When we create a new band file, we sync the volume
169 * it's on, so that we can ensure that the band file is present
170 * on disk. (Otherwise, with a crash, we can end up with the
171 * data not where we expected.) In this case, however, we probably
172 * don't need to wait for it -- just start the sync.
174 fsync_volume_np(fd
, 0);
175 fcntl(fd
, F_NOCACHE
, 1);
179 ctx
->cBandNum
= bandNum
;
183 nwritten
= pwrite(fd
, (char*)buffer
+ written
, amount
, bandOffset
);
184 if (nwritten
== -1) {
185 warn("Cannot write to band file %s/band/%llx for offset %llu for amount %zu", ctx
->pathname
, bandNum
, offset
+written
, amount
);
191 // Sync the data out.
202 * Write a given extent (<start, length> pair) from an input device to the
203 * sparse bundle. We also use a block to update progress.
206 WriteExtentToSparse(struct IOWrapper
* context
, DeviceInfo_t
*devp
, off_t start
, off_t len
, void (^bp
)(off_t
))
208 const ssize_t bufSize
= 1024 * 1024;
209 uint8_t *buffer
= NULL
;
213 if (debug
) printf("Writing extent <%lld, %lld>\n", start
, len
);
214 buffer
= malloc(bufSize
);
215 if (buffer
== NULL
) {
216 warn("%s(%s): Could not allocate %zu bytes for buffer", __FILE__
, __FUNCTION__
, bufSize
);
221 while (total
< len
) {
224 ssize_t amt
= MIN(bufSize
, len
- total
);
225 nread
= UnalignedRead(devp
, buffer
, amt
, start
+ total
);
227 warn("Cannot read from device at offset %lld", start
+ total
);
232 warnx("Short read from source device -- got %zd, expected %zd", nread
, amt
);
234 nwritten
= doSparseWrite(context
, start
+ total
, buffer
, nread
);
235 if (nwritten
== -1) {
242 if (debug
) printf("\twrote %lld\n", total
);
249 static const CFStringRef kBandSizeKey
= CFSTR("band-size");
250 static const CFStringRef kDevSizeKey
= CFSTR("size");
253 * We need to be able to get the size of the "device" from a sparse bundle;
254 * we do this by using CF routines to parse the Info.plist file, and then
255 * get the two keys we care about: band-size (size of the band files), and
256 * size (size -- in bytes -- of the "disk").
259 GetSizesFromPlist(const char *path
, size_t *bandSize
, off_t
*devSize
)
262 CFReadStreamRef inFile
= NULL
;
263 CFURLRef inFileURL
= NULL
;
264 CFStringRef cfPath
= NULL
;
265 CFPropertyListRef cfDict
= NULL
;
266 CFNumberRef cfVal
= NULL
;
271 inFileURL
= CFURLCreateFromFileSystemRepresentation(NULL
, (const UInt8
*)path
, strlen(path
), FALSE
);
272 if (inFileURL
== NULL
) {
273 if (debug
) warn("Cannot create url from pathname %s", path
);
277 inFile
= CFReadStreamCreateWithFile(NULL
, inFileURL
);
278 if (inFile
== NULL
) {
279 if (debug
) warn("cannot create read stream from path %s", path
);
283 if (CFReadStreamOpen(inFile
) == FALSE
) {
284 if (debug
) warn("cannot open read stream");
288 cfDict
= CFPropertyListCreateWithStream(NULL
, inFile
, 0, 0, NULL
, NULL
);
289 if (cfDict
== NULL
) {
290 if (debug
) warnx("cannot create propertly list from stream for path %s", path
);
294 cfVal
= CFDictionaryGetValue(cfDict
, kBandSizeKey
);
296 if (debug
) warnx("cannot get bandsize key from plist");
300 if (CFNumberGetValue(cfVal
, kCFNumberIntType
, &tmpInt
) == false) {
301 if (debug
) warnx("cannot get value from band size number");
307 cfVal
= CFDictionaryGetValue(cfDict
, kDevSizeKey
);
309 if (debug
) warnx("cannot get dev size key from plist");
312 if (CFNumberGetValue(cfVal
, kCFNumberLongLongType
, &tmpLL
) == false) {
324 CFRelease(inFileURL
);
332 #define kProgressName "HC.progress.txt"
335 * Get the progress state from a sparse bundle. If it's not there, then
339 GetProgress(struct IOWrapper
*context
)
341 struct SparseBundleContext
*ctx
= context
->context
;
344 char progFile
[strlen(ctx
->pathname
) + sizeof(kProgressName
) + 2]; // '/' and NUL
346 sprintf(progFile
, "%s/%s", ctx
->pathname
, kProgressName
);
347 fp
= fopen(progFile
, "r");
351 if (fscanf(fp
, "%llu", &retval
) != 1) {
360 * Write the progress information out. This involves writing a file in
361 * the sparse bundle with the amount -- in bytes -- we've written so far.
364 SetProgress(struct IOWrapper
*context
, off_t prog
)
366 struct SparseBundleContext
*ctx
= context
->context
;
368 char progFile
[strlen(ctx
->pathname
) + sizeof(kProgressName
) + 2]; // '/' and NUL
370 sprintf(progFile
, "%s/%s", ctx
->pathname
, kProgressName
);
374 fp
= fopen(progFile
, "w");
376 (void)fprintf(fp
, "%llu\n", prog
);
384 * Clean up. This is used when we have to initialize the bundle, but don't
385 * have any progress information -- in that case, we don't want to have any
386 * of the old band files laying around. We use removefile() to recursively
387 * remove them, but keep the bands directory.
390 doCleanup(struct IOWrapper
*ctx
)
392 struct SparseBundleContext
*context
= ctx
->context
;
394 char bandsDir
[strlen(context
->pathname
) + sizeof("/bands") + 1]; // 1 for NUL
396 sprintf(bandsDir
, "%s/bands", context
->pathname
);
399 fprintf(stderr
, "Cleaning up, about to call removefile\n");
400 rv
= removefile(bandsDir
, NULL
, REMOVEFILE_RECURSIVE
| REMOVEFILE_KEEP_PARENT
);
402 fprintf(stderr
, "removefile returned %d\n", rv
);
404 return (rv
== 0) ? 0 : -1;
408 * Initialize the IOWrapper structure for a sparse bundle. This will
409 * create the bundle directory (but not its parents!) if needed, and
410 * will populate it out. It checks to see if there is an existing bundle
411 * of the same name, and, if so, ensures that the izes are correct. Then
412 * it sets up all the function pointers.
415 InitSparseBundle(const char *path
, DeviceInfo_t
*devp
)
417 struct SparseBundleContext ctx
= { 0 };
418 IOWrapper_t
*wrapper
= NULL
;
420 char *tmpname
= NULL
;
423 if (strstr(path
, ".sparsebundle") == NULL
) {
424 asprintf(&ctx
.pathname
, "%s.sparsebundle", path
);
426 ctx
.pathname
= strdup(path
);
429 if (ctx
.pathname
== NULL
) {
433 if (lstat(ctx
.pathname
, &sb
) == -1) {
434 if (errno
!= ENOENT
) {
435 warn("cannot check sparse bundle %s", ctx
.pathname
);
438 if (mkdir(ctx
.pathname
, 0777) == -1) {
439 warn("cannot create sparse bundle %s", ctx
.pathname
);
442 } else if ((sb
.st_mode
& S_IFMT
) != S_IFDIR
) {
443 warnx("sparse bundle object %s is not a directory", ctx
.pathname
);
446 /* NB! All names we create inside the bundle directory are shorter
447 * then "Info.plist", we re-use the buffer allocated here for
448 * multiple file names. */
449 tmplen
= asprintf(&tmpname
, "%s/Info.plist", ctx
.pathname
);
450 if (tmpname
== NULL
) {
454 if (stat(tmpname
, &sb
) != -1) {
457 if (GetSizesFromPlist(tmpname
, &bandSize
, &devSize
) == -1) {
458 warnx("Existing sparse bundle can't be parsed");
462 printf("Existing sparse bundle size = %lld, bandsize = %zu\n", devSize
, bandSize
);
464 if (devSize
!= devp
->size
) {
465 warnx("Existing sparse bundle size (%lld) != dev size (%lld)", devSize
, devp
->size
);
468 ctx
.bandSize
= bandSize
;
470 FILE *fp
= fopen(tmpname
, "w");
472 warn("cannot create sparse bundle info plist %s", tmpname
);
475 ctx
.bandSize
= kBandSize
;
476 if (fprintf(fp
, bundlePrototype
, kBandSize
, devp
->size
) < 0) {
477 warn("failed to set bundle information in %s", tmpname
);
478 fclose(fp
); /* eat error return */
481 if (fclose(fp
) != 0) {
482 warn("failed to update bundle information in %s", tmpname
);
485 snprintf(tmpname
, tmplen
+ 1, "%s/Info.bckup", ctx
.pathname
);
486 if ((int)strlen(tmpname
) == tmplen
) { /* Only update backup if we get the full path */
487 /* Failure to create a backup is not fatal */
488 fp
= fopen(tmpname
, "w");
490 if ((fprintf(fp
, bundlePrototype
, kBandSize
, devp
->size
) < 0) ||
496 warn("Cannot create backup bundle information file in %s", tmpname
);
498 if ((snprintf(tmpname
, tmplen
+ 1, "%s/bands", ctx
.pathname
) > tmplen
) ||
499 (mkdir(tmpname
, 0777) == -1)) {
500 warn("cannot create bands directory in sparse bundle %s", ctx
.pathname
);
503 if (snprintf(tmpname
, tmplen
+ 1, "%s/token", ctx
.pathname
) <= tmplen
) {
504 close(open(tmpname
, O_CREAT
| O_TRUNC
, 0666));
508 wrapper
= malloc(sizeof(*wrapper
));
510 struct SparseBundleContext
*wrapped_ctx
;
512 wrapped_ctx
= malloc(sizeof(*wrapped_ctx
));
515 wrapped_ctx
->cfd
= -1;
517 wrapper
->writer
= &WriteExtentToSparse
;
518 wrapper
->reader
= &doSparseRead
;
519 wrapper
->getprog
= &GetProgress
;
520 wrapper
->setprog
= &SetProgress
;
521 wrapper
->cleanup
= &doCleanup
;
522 wrapper
->context
= wrapped_ctx
;
529 if (wrapper
== NULL
) {