Make object creation in http fetch a bit safer.
Unlike write_sha1_file() that tries to create the object file in a temporary location and then move it to the final location, fetch_object could have been interrupted in the middle, leaving a corrupt file. Signed-off-by: Junio C Hamano <junkio@cox.net>
Junio C Hamano committed
Sep 21, 2005 at 02:46 UTC
09d920831edba17fe983269a9d0d85e592dd4bb3
1 file changed
+24
-5
http-fetch.c
+24
-5
@@ -350,13 +350,18 @@ int fetch_object(struct alt_base *repo, unsigned char *sha1)
350
char *hex = sha1_to_hex(sha1);
351
char *filename = sha1_file_name(sha1);
352
unsigned char real_sha1[20];
353
+ char tmpfile[PATH_MAX];
354
+ int ret;
355
char *url;
356
char *posn;
357
356
- local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
358
+ snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX",
359
+ get_object_directory());
360
361
+ local = mkstemp(tmpfile);
362
if (local < 0)
359
- return error("Couldn't open local object %s\n", filename);
363
+ return error("Couldn't create temporary file %s for %s: %s\n",
364
+ tmpfile, filename, strerror(errno));
365
366
memset(&stream, 0, sizeof(stream));
367
@@ -386,18 +391,32 @@ int fetch_object(struct alt_base *repo, unsigned char *sha1)
391
return -1;
392
}
393
394
+ fchmod(local, 0444);
395
close(local);
396
inflateEnd(&stream);
397
SHA1_Final(real_sha1, &c);
398
if (zret != Z_STREAM_END) {
393
- unlink(filename);
399
+ unlink(tmpfile);
400
return error("File %s (%s) corrupt\n", hex, url);
401
}
402
if (memcmp(sha1, real_sha1, 20)) {
397
- unlink(filename);
403
+ unlink(tmpfile);
404
return error("File %s has bad hash\n", hex);
405
}
400
-
406
+ ret = link(tmpfile, filename);
407
+ if (ret < 0) {
408
+ /* Same Coda hack as in write_sha1_file(sha1_file.c) */
409
+ ret = errno;
410
+ if (ret == EXDEV && !rename(tmpfile, filename))
411
+ goto out;
412
+ }
413
+ unlink(tmpfile);
414
+ if (ret) {
415
+ if (ret != EEXIST)
416
+ return error("unable to write sha1 filename %s: %s",
417
+ filename, strerror(ret));
418
+ }
419
+ out:
420
pull_say("got %s\n", hex);
421
return 0;
422
}