1#include "cache.h" 2#include "lockfile.h" 3#include "refs.h" 4#include "object.h" 5#include "tag.h" 6#include "dir.h" 7#include "string-list.h" 8 9struct ref_lock { 10 char *ref_name; 11 char *orig_ref_name; 12 struct lock_file *lk; 13 unsigned char old_sha1[20]; 14}; 15 16/* 17 * How to handle various characters in refnames: 18 * 0: An acceptable character for refs 19 * 1: End-of-component 20 * 2: ., look for a preceding . to reject .. in refs 21 * 3: {, look for a preceding @ to reject @{ in refs 22 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 23 */ 24static unsigned char refname_disposition[256] = { 25 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 26 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 27 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1, 28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0, 31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4 33}; 34 35/* 36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 37 * refs (i.e., because the reference is about to be deleted anyway). 38 */ 39#define REF_DELETING 0x02 40 41/* 42 * Used as a flag in ref_update::flags when a loose ref is being 43 * pruned. 44 */ 45#define REF_ISPRUNING 0x04 46 47/* 48 * Used as a flag in ref_update::flags when the reference should be 49 * updated to new_sha1. 50 */ 51#define REF_HAVE_NEW 0x08 52 53/* 54 * Used as a flag in ref_update::flags when old_sha1 should be 55 * checked. 56 */ 57#define REF_HAVE_OLD 0x10 58 59/* 60 * Used as a flag in ref_update::flags when the lockfile needs to be 61 * committed. 62 */ 63#define REF_NEEDS_COMMIT 0x20 64 65/* 66 * Try to read one refname component from the front of refname. 67 * Return the length of the component found, or -1 if the component is 68 * not legal. It is legal if it is something reasonable to have under 69 * ".git/refs/"; We do not like it if: 70 * 71 * - any path component of it begins with ".", or 72 * - it has double dots "..", or 73 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 74 * - it ends with a "/". 75 * - it ends with ".lock" 76 * - it contains a "\" (backslash) 77 */ 78static int check_refname_component(const char *refname, int flags) 79{ 80 const char *cp; 81 char last = '\0'; 82 83 for (cp = refname; ; cp++) { 84 int ch = *cp & 255; 85 unsigned char disp = refname_disposition[ch]; 86 switch (disp) { 87 case 1: 88 goto out; 89 case 2: 90 if (last == '.') 91 return -1; /* Refname contains "..". */ 92 break; 93 case 3: 94 if (last == '@') 95 return -1; /* Refname contains "@{". */ 96 break; 97 case 4: 98 return -1; 99 } 100 last = ch; 101 } 102out: 103 if (cp == refname) 104 return 0; /* Component has zero length. */ 105 if (refname[0] == '.') 106 return -1; /* Component starts with '.'. */ 107 if (cp - refname >= LOCK_SUFFIX_LEN && 108 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 109 return -1; /* Refname ends with ".lock". */ 110 return cp - refname; 111} 112 113int check_refname_format(const char *refname, int flags) 114{ 115 int component_len, component_count = 0; 116 117 if (!strcmp(refname, "@")) 118 /* Refname is a single character '@'. */ 119 return -1; 120 121 while (1) { 122 /* We are at the start of a path component. */ 123 component_len = check_refname_component(refname, flags); 124 if (component_len <= 0) { 125 if ((flags & REFNAME_REFSPEC_PATTERN) && 126 refname[0] == '*' && 127 (refname[1] == '\0' || refname[1] == '/')) { 128 /* Accept one wildcard as a full refname component. */ 129 flags &= ~REFNAME_REFSPEC_PATTERN; 130 component_len = 1; 131 } else { 132 return -1; 133 } 134 } 135 component_count++; 136 if (refname[component_len] == '\0') 137 break; 138 /* Skip to next component. */ 139 refname += component_len + 1; 140 } 141 142 if (refname[component_len - 1] == '.') 143 return -1; /* Refname ends with '.'. */ 144 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2) 145 return -1; /* Refname has only one component. */ 146 return 0; 147} 148 149struct ref_entry; 150 151/* 152 * Information used (along with the information in ref_entry) to 153 * describe a single cached reference. This data structure only 154 * occurs embedded in a union in struct ref_entry, and only when 155 * (ref_entry->flag & REF_DIR) is zero. 156 */ 157struct ref_value { 158 /* 159 * The name of the object to which this reference resolves 160 * (which may be a tag object). If REF_ISBROKEN, this is 161 * null. If REF_ISSYMREF, then this is the name of the object 162 * referred to by the last reference in the symlink chain. 163 */ 164 unsigned char sha1[20]; 165 166 /* 167 * If REF_KNOWS_PEELED, then this field holds the peeled value 168 * of this reference, or null if the reference is known not to 169 * be peelable. See the documentation for peel_ref() for an 170 * exact definition of "peelable". 171 */ 172 unsigned char peeled[20]; 173}; 174 175struct ref_cache; 176 177/* 178 * Information used (along with the information in ref_entry) to 179 * describe a level in the hierarchy of references. This data 180 * structure only occurs embedded in a union in struct ref_entry, and 181 * only when (ref_entry.flag & REF_DIR) is set. In that case, 182 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 183 * in the directory have already been read: 184 * 185 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 186 * or packed references, already read. 187 * 188 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 189 * references that hasn't been read yet (nor has any of its 190 * subdirectories). 191 * 192 * Entries within a directory are stored within a growable array of 193 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 194 * sorted are sorted by their component name in strcmp() order and the 195 * remaining entries are unsorted. 196 * 197 * Loose references are read lazily, one directory at a time. When a 198 * directory of loose references is read, then all of the references 199 * in that directory are stored, and REF_INCOMPLETE stubs are created 200 * for any subdirectories, but the subdirectories themselves are not 201 * read. The reading is triggered by get_ref_dir(). 202 */ 203struct ref_dir { 204 int nr, alloc; 205 206 /* 207 * Entries with index 0 <= i < sorted are sorted by name. New 208 * entries are appended to the list unsorted, and are sorted 209 * only when required; thus we avoid the need to sort the list 210 * after the addition of every reference. 211 */ 212 int sorted; 213 214 /* A pointer to the ref_cache that contains this ref_dir. */ 215 struct ref_cache *ref_cache; 216 217 struct ref_entry **entries; 218}; 219 220/* 221 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 222 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 223 * public values; see refs.h. 224 */ 225 226/* 227 * The field ref_entry->u.value.peeled of this value entry contains 228 * the correct peeled value for the reference, which might be 229 * null_sha1 if the reference is not a tag or if it is broken. 230 */ 231#define REF_KNOWS_PEELED 0x10 232 233/* ref_entry represents a directory of references */ 234#define REF_DIR 0x20 235 236/* 237 * Entry has not yet been read from disk (used only for REF_DIR 238 * entries representing loose references) 239 */ 240#define REF_INCOMPLETE 0x40 241 242/* 243 * A ref_entry represents either a reference or a "subdirectory" of 244 * references. 245 * 246 * Each directory in the reference namespace is represented by a 247 * ref_entry with (flags & REF_DIR) set and containing a subdir member 248 * that holds the entries in that directory that have been read so 249 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 250 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 251 * used for loose reference directories. 252 * 253 * References are represented by a ref_entry with (flags & REF_DIR) 254 * unset and a value member that describes the reference's value. The 255 * flag member is at the ref_entry level, but it is also needed to 256 * interpret the contents of the value field (in other words, a 257 * ref_value object is not very much use without the enclosing 258 * ref_entry). 259 * 260 * Reference names cannot end with slash and directories' names are 261 * always stored with a trailing slash (except for the top-level 262 * directory, which is always denoted by ""). This has two nice 263 * consequences: (1) when the entries in each subdir are sorted 264 * lexicographically by name (as they usually are), the references in 265 * a whole tree can be generated in lexicographic order by traversing 266 * the tree in left-to-right, depth-first order; (2) the names of 267 * references and subdirectories cannot conflict, and therefore the 268 * presence of an empty subdirectory does not block the creation of a 269 * similarly-named reference. (The fact that reference names with the 270 * same leading components can conflict *with each other* is a 271 * separate issue that is regulated by verify_refname_available().) 272 * 273 * Please note that the name field contains the fully-qualified 274 * reference (or subdirectory) name. Space could be saved by only 275 * storing the relative names. But that would require the full names 276 * to be generated on the fly when iterating in do_for_each_ref(), and 277 * would break callback functions, who have always been able to assume 278 * that the name strings that they are passed will not be freed during 279 * the iteration. 280 */ 281struct ref_entry { 282 unsigned char flag; /* ISSYMREF? ISPACKED? */ 283 union { 284 struct ref_value value; /* if not (flags&REF_DIR) */ 285 struct ref_dir subdir; /* if (flags&REF_DIR) */ 286 } u; 287 /* 288 * The full name of the reference (e.g., "refs/heads/master") 289 * or the full name of the directory with a trailing slash 290 * (e.g., "refs/heads/"): 291 */ 292 char name[FLEX_ARRAY]; 293}; 294 295static void read_loose_refs(const char *dirname, struct ref_dir *dir); 296 297static struct ref_dir *get_ref_dir(struct ref_entry *entry) 298{ 299 struct ref_dir *dir; 300 assert(entry->flag & REF_DIR); 301 dir = &entry->u.subdir; 302 if (entry->flag & REF_INCOMPLETE) { 303 read_loose_refs(entry->name, dir); 304 entry->flag &= ~REF_INCOMPLETE; 305 } 306 return dir; 307} 308 309/* 310 * Check if a refname is safe. 311 * For refs that start with "refs/" we consider it safe as long they do 312 * not try to resolve to outside of refs/. 313 * 314 * For all other refs we only consider them safe iff they only contain 315 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 316 * "config"). 317 */ 318static int refname_is_safe(const char *refname) 319{ 320 if (starts_with(refname, "refs/")) { 321 char *buf; 322 int result; 323 324 buf = xmalloc(strlen(refname) + 1); 325 /* 326 * Does the refname try to escape refs/? 327 * For example: refs/foo/../bar is safe but refs/foo/../../bar 328 * is not. 329 */ 330 result = !normalize_path_copy(buf, refname + strlen("refs/")); 331 free(buf); 332 return result; 333 } 334 while (*refname) { 335 if (!isupper(*refname) && *refname != '_') 336 return 0; 337 refname++; 338 } 339 return 1; 340} 341 342static struct ref_entry *create_ref_entry(const char *refname, 343 const unsigned char *sha1, int flag, 344 int check_name) 345{ 346 int len; 347 struct ref_entry *ref; 348 349 if (check_name && 350 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 351 die("Reference has invalid format: '%s'", refname); 352 len = strlen(refname) + 1; 353 ref = xmalloc(sizeof(struct ref_entry) + len); 354 hashcpy(ref->u.value.sha1, sha1); 355 hashclr(ref->u.value.peeled); 356 memcpy(ref->name, refname, len); 357 ref->flag = flag; 358 return ref; 359} 360 361static void clear_ref_dir(struct ref_dir *dir); 362 363static void free_ref_entry(struct ref_entry *entry) 364{ 365 if (entry->flag & REF_DIR) { 366 /* 367 * Do not use get_ref_dir() here, as that might 368 * trigger the reading of loose refs. 369 */ 370 clear_ref_dir(&entry->u.subdir); 371 } 372 free(entry); 373} 374 375/* 376 * Add a ref_entry to the end of dir (unsorted). Entry is always 377 * stored directly in dir; no recursion into subdirectories is 378 * done. 379 */ 380static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry) 381{ 382 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc); 383 dir->entries[dir->nr++] = entry; 384 /* optimize for the case that entries are added in order */ 385 if (dir->nr == 1 || 386 (dir->nr == dir->sorted + 1 && 387 strcmp(dir->entries[dir->nr - 2]->name, 388 dir->entries[dir->nr - 1]->name) < 0)) 389 dir->sorted = dir->nr; 390} 391 392/* 393 * Clear and free all entries in dir, recursively. 394 */ 395static void clear_ref_dir(struct ref_dir *dir) 396{ 397 int i; 398 for (i = 0; i < dir->nr; i++) 399 free_ref_entry(dir->entries[i]); 400 free(dir->entries); 401 dir->sorted = dir->nr = dir->alloc = 0; 402 dir->entries = NULL; 403} 404 405/* 406 * Create a struct ref_entry object for the specified dirname. 407 * dirname is the name of the directory with a trailing slash (e.g., 408 * "refs/heads/") or "" for the top-level directory. 409 */ 410static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 411 const char *dirname, size_t len, 412 int incomplete) 413{ 414 struct ref_entry *direntry; 415 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1); 416 memcpy(direntry->name, dirname, len); 417 direntry->name[len] = '\0'; 418 direntry->u.subdir.ref_cache = ref_cache; 419 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0); 420 return direntry; 421} 422 423static int ref_entry_cmp(const void *a, const void *b) 424{ 425 struct ref_entry *one = *(struct ref_entry **)a; 426 struct ref_entry *two = *(struct ref_entry **)b; 427 return strcmp(one->name, two->name); 428} 429 430static void sort_ref_dir(struct ref_dir *dir); 431 432struct string_slice { 433 size_t len; 434 const char *str; 435}; 436 437static int ref_entry_cmp_sslice(const void *key_, const void *ent_) 438{ 439 const struct string_slice *key = key_; 440 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_; 441 int cmp = strncmp(key->str, ent->name, key->len); 442 if (cmp) 443 return cmp; 444 return '\0' - (unsigned char)ent->name[key->len]; 445} 446 447/* 448 * Return the index of the entry with the given refname from the 449 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 450 * no such entry is found. dir must already be complete. 451 */ 452static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len) 453{ 454 struct ref_entry **r; 455 struct string_slice key; 456 457 if (refname == NULL || !dir->nr) 458 return -1; 459 460 sort_ref_dir(dir); 461 key.len = len; 462 key.str = refname; 463 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries), 464 ref_entry_cmp_sslice); 465 466 if (r == NULL) 467 return -1; 468 469 return r - dir->entries; 470} 471 472/* 473 * Search for a directory entry directly within dir (without 474 * recursing). Sort dir if necessary. subdirname must be a directory 475 * name (i.e., end in '/'). If mkdir is set, then create the 476 * directory if it is missing; otherwise, return NULL if the desired 477 * directory cannot be found. dir must already be complete. 478 */ 479static struct ref_dir *search_for_subdir(struct ref_dir *dir, 480 const char *subdirname, size_t len, 481 int mkdir) 482{ 483 int entry_index = search_ref_dir(dir, subdirname, len); 484 struct ref_entry *entry; 485 if (entry_index == -1) { 486 if (!mkdir) 487 return NULL; 488 /* 489 * Since dir is complete, the absence of a subdir 490 * means that the subdir really doesn't exist; 491 * therefore, create an empty record for it but mark 492 * the record complete. 493 */ 494 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0); 495 add_entry_to_dir(dir, entry); 496 } else { 497 entry = dir->entries[entry_index]; 498 } 499 return get_ref_dir(entry); 500} 501 502/* 503 * If refname is a reference name, find the ref_dir within the dir 504 * tree that should hold refname. If refname is a directory name 505 * (i.e., ends in '/'), then return that ref_dir itself. dir must 506 * represent the top-level directory and must already be complete. 507 * Sort ref_dirs and recurse into subdirectories as necessary. If 508 * mkdir is set, then create any missing directories; otherwise, 509 * return NULL if the desired directory cannot be found. 510 */ 511static struct ref_dir *find_containing_dir(struct ref_dir *dir, 512 const char *refname, int mkdir) 513{ 514 const char *slash; 515 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 516 size_t dirnamelen = slash - refname + 1; 517 struct ref_dir *subdir; 518 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir); 519 if (!subdir) { 520 dir = NULL; 521 break; 522 } 523 dir = subdir; 524 } 525 526 return dir; 527} 528 529/* 530 * Find the value entry with the given name in dir, sorting ref_dirs 531 * and recursing into subdirectories as necessary. If the name is not 532 * found or it corresponds to a directory entry, return NULL. 533 */ 534static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname) 535{ 536 int entry_index; 537 struct ref_entry *entry; 538 dir = find_containing_dir(dir, refname, 0); 539 if (!dir) 540 return NULL; 541 entry_index = search_ref_dir(dir, refname, strlen(refname)); 542 if (entry_index == -1) 543 return NULL; 544 entry = dir->entries[entry_index]; 545 return (entry->flag & REF_DIR) ? NULL : entry; 546} 547 548/* 549 * Remove the entry with the given name from dir, recursing into 550 * subdirectories as necessary. If refname is the name of a directory 551 * (i.e., ends with '/'), then remove the directory and its contents. 552 * If the removal was successful, return the number of entries 553 * remaining in the directory entry that contained the deleted entry. 554 * If the name was not found, return -1. Please note that this 555 * function only deletes the entry from the cache; it does not delete 556 * it from the filesystem or ensure that other cache entries (which 557 * might be symbolic references to the removed entry) are updated. 558 * Nor does it remove any containing dir entries that might be made 559 * empty by the removal. dir must represent the top-level directory 560 * and must already be complete. 561 */ 562static int remove_entry(struct ref_dir *dir, const char *refname) 563{ 564 int refname_len = strlen(refname); 565 int entry_index; 566 struct ref_entry *entry; 567 int is_dir = refname[refname_len - 1] == '/'; 568 if (is_dir) { 569 /* 570 * refname represents a reference directory. Remove 571 * the trailing slash; otherwise we will get the 572 * directory *representing* refname rather than the 573 * one *containing* it. 574 */ 575 char *dirname = xmemdupz(refname, refname_len - 1); 576 dir = find_containing_dir(dir, dirname, 0); 577 free(dirname); 578 } else { 579 dir = find_containing_dir(dir, refname, 0); 580 } 581 if (!dir) 582 return -1; 583 entry_index = search_ref_dir(dir, refname, refname_len); 584 if (entry_index == -1) 585 return -1; 586 entry = dir->entries[entry_index]; 587 588 memmove(&dir->entries[entry_index], 589 &dir->entries[entry_index + 1], 590 (dir->nr - entry_index - 1) * sizeof(*dir->entries) 591 ); 592 dir->nr--; 593 if (dir->sorted > entry_index) 594 dir->sorted--; 595 free_ref_entry(entry); 596 return dir->nr; 597} 598 599/* 600 * Add a ref_entry to the ref_dir (unsorted), recursing into 601 * subdirectories as necessary. dir must represent the top-level 602 * directory. Return 0 on success. 603 */ 604static int add_ref(struct ref_dir *dir, struct ref_entry *ref) 605{ 606 dir = find_containing_dir(dir, ref->name, 1); 607 if (!dir) 608 return -1; 609 add_entry_to_dir(dir, ref); 610 return 0; 611} 612 613/* 614 * Emit a warning and return true iff ref1 and ref2 have the same name 615 * and the same sha1. Die if they have the same name but different 616 * sha1s. 617 */ 618static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2) 619{ 620 if (strcmp(ref1->name, ref2->name)) 621 return 0; 622 623 /* Duplicate name; make sure that they don't conflict: */ 624 625 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 626 /* This is impossible by construction */ 627 die("Reference directory conflict: %s", ref1->name); 628 629 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 630 die("Duplicated ref, and SHA1s don't match: %s", ref1->name); 631 632 warning("Duplicated ref: %s", ref1->name); 633 return 1; 634} 635 636/* 637 * Sort the entries in dir non-recursively (if they are not already 638 * sorted) and remove any duplicate entries. 639 */ 640static void sort_ref_dir(struct ref_dir *dir) 641{ 642 int i, j; 643 struct ref_entry *last = NULL; 644 645 /* 646 * This check also prevents passing a zero-length array to qsort(), 647 * which is a problem on some platforms. 648 */ 649 if (dir->sorted == dir->nr) 650 return; 651 652 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp); 653 654 /* Remove any duplicates: */ 655 for (i = 0, j = 0; j < dir->nr; j++) { 656 struct ref_entry *entry = dir->entries[j]; 657 if (last && is_dup_ref(last, entry)) 658 free_ref_entry(entry); 659 else 660 last = dir->entries[i++] = entry; 661 } 662 dir->sorted = dir->nr = i; 663} 664 665/* Include broken references in a do_for_each_ref*() iteration: */ 666#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 667 668/* 669 * Return true iff the reference described by entry can be resolved to 670 * an object in the database. Emit a warning if the referred-to 671 * object does not exist. 672 */ 673static int ref_resolves_to_object(struct ref_entry *entry) 674{ 675 if (entry->flag & REF_ISBROKEN) 676 return 0; 677 if (!has_sha1_file(entry->u.value.sha1)) { 678 error("%s does not point to a valid object!", entry->name); 679 return 0; 680 } 681 return 1; 682} 683 684/* 685 * current_ref is a performance hack: when iterating over references 686 * using the for_each_ref*() functions, current_ref is set to the 687 * current reference's entry before calling the callback function. If 688 * the callback function calls peel_ref(), then peel_ref() first 689 * checks whether the reference to be peeled is the current reference 690 * (it usually is) and if so, returns that reference's peeled version 691 * if it is available. This avoids a refname lookup in a common case. 692 */ 693static struct ref_entry *current_ref; 694 695typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data); 696 697struct ref_entry_cb { 698 const char *base; 699 int trim; 700 int flags; 701 each_ref_fn *fn; 702 void *cb_data; 703}; 704 705/* 706 * Handle one reference in a do_for_each_ref*()-style iteration, 707 * calling an each_ref_fn for each entry. 708 */ 709static int do_one_ref(struct ref_entry *entry, void *cb_data) 710{ 711 struct ref_entry_cb *data = cb_data; 712 struct ref_entry *old_current_ref; 713 int retval; 714 715 if (!starts_with(entry->name, data->base)) 716 return 0; 717 718 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 719 !ref_resolves_to_object(entry)) 720 return 0; 721 722 /* Store the old value, in case this is a recursive call: */ 723 old_current_ref = current_ref; 724 current_ref = entry; 725 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 726 entry->flag, data->cb_data); 727 current_ref = old_current_ref; 728 return retval; 729} 730 731/* 732 * Call fn for each reference in dir that has index in the range 733 * offset <= index < dir->nr. Recurse into subdirectories that are in 734 * that index range, sorting them before iterating. This function 735 * does not sort dir itself; it should be sorted beforehand. fn is 736 * called for all references, including broken ones. 737 */ 738static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset, 739 each_ref_entry_fn fn, void *cb_data) 740{ 741 int i; 742 assert(dir->sorted == dir->nr); 743 for (i = offset; i < dir->nr; i++) { 744 struct ref_entry *entry = dir->entries[i]; 745 int retval; 746 if (entry->flag & REF_DIR) { 747 struct ref_dir *subdir = get_ref_dir(entry); 748 sort_ref_dir(subdir); 749 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data); 750 } else { 751 retval = fn(entry, cb_data); 752 } 753 if (retval) 754 return retval; 755 } 756 return 0; 757} 758 759/* 760 * Call fn for each reference in the union of dir1 and dir2, in order 761 * by refname. Recurse into subdirectories. If a value entry appears 762 * in both dir1 and dir2, then only process the version that is in 763 * dir2. The input dirs must already be sorted, but subdirs will be 764 * sorted as needed. fn is called for all references, including 765 * broken ones. 766 */ 767static int do_for_each_entry_in_dirs(struct ref_dir *dir1, 768 struct ref_dir *dir2, 769 each_ref_entry_fn fn, void *cb_data) 770{ 771 int retval; 772 int i1 = 0, i2 = 0; 773 774 assert(dir1->sorted == dir1->nr); 775 assert(dir2->sorted == dir2->nr); 776 while (1) { 777 struct ref_entry *e1, *e2; 778 int cmp; 779 if (i1 == dir1->nr) { 780 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data); 781 } 782 if (i2 == dir2->nr) { 783 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data); 784 } 785 e1 = dir1->entries[i1]; 786 e2 = dir2->entries[i2]; 787 cmp = strcmp(e1->name, e2->name); 788 if (cmp == 0) { 789 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 790 /* Both are directories; descend them in parallel. */ 791 struct ref_dir *subdir1 = get_ref_dir(e1); 792 struct ref_dir *subdir2 = get_ref_dir(e2); 793 sort_ref_dir(subdir1); 794 sort_ref_dir(subdir2); 795 retval = do_for_each_entry_in_dirs( 796 subdir1, subdir2, fn, cb_data); 797 i1++; 798 i2++; 799 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 800 /* Both are references; ignore the one from dir1. */ 801 retval = fn(e2, cb_data); 802 i1++; 803 i2++; 804 } else { 805 die("conflict between reference and directory: %s", 806 e1->name); 807 } 808 } else { 809 struct ref_entry *e; 810 if (cmp < 0) { 811 e = e1; 812 i1++; 813 } else { 814 e = e2; 815 i2++; 816 } 817 if (e->flag & REF_DIR) { 818 struct ref_dir *subdir = get_ref_dir(e); 819 sort_ref_dir(subdir); 820 retval = do_for_each_entry_in_dir( 821 subdir, 0, fn, cb_data); 822 } else { 823 retval = fn(e, cb_data); 824 } 825 } 826 if (retval) 827 return retval; 828 } 829} 830 831/* 832 * Load all of the refs from the dir into our in-memory cache. The hard work 833 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 834 * through all of the sub-directories. We do not even need to care about 835 * sorting, as traversal order does not matter to us. 836 */ 837static void prime_ref_dir(struct ref_dir *dir) 838{ 839 int i; 840 for (i = 0; i < dir->nr; i++) { 841 struct ref_entry *entry = dir->entries[i]; 842 if (entry->flag & REF_DIR) 843 prime_ref_dir(get_ref_dir(entry)); 844 } 845} 846 847struct nonmatching_ref_data { 848 const struct string_list *skip; 849 const char *conflicting_refname; 850}; 851 852static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata) 853{ 854 struct nonmatching_ref_data *data = vdata; 855 856 if (data->skip && string_list_has_string(data->skip, entry->name)) 857 return 0; 858 859 data->conflicting_refname = entry->name; 860 return 1; 861} 862 863/* 864 * Return 0 if a reference named refname could be created without 865 * conflicting with the name of an existing reference in dir. 866 * Otherwise, return a negative value and write an explanation to err. 867 * If extras is non-NULL, it is a list of additional refnames with 868 * which refname is not allowed to conflict. If skip is non-NULL, 869 * ignore potential conflicts with refs in skip (e.g., because they 870 * are scheduled for deletion in the same operation). Behavior is 871 * undefined if the same name is listed in both extras and skip. 872 * 873 * Two reference names conflict if one of them exactly matches the 874 * leading components of the other; e.g., "refs/foo/bar" conflicts 875 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 876 * "refs/foo/bar" or "refs/foo/barbados". 877 * 878 * extras and skip must be sorted. 879 */ 880static int verify_refname_available(const char *refname, 881 const struct string_list *extras, 882 const struct string_list *skip, 883 struct ref_dir *dir, 884 struct strbuf *err) 885{ 886 const char *slash; 887 int pos; 888 struct strbuf dirname = STRBUF_INIT; 889 int ret = -1; 890 891 /* 892 * For the sake of comments in this function, suppose that 893 * refname is "refs/foo/bar". 894 */ 895 896 assert(err); 897 898 strbuf_grow(&dirname, strlen(refname) + 1); 899 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 900 /* Expand dirname to the new prefix, not including the trailing slash: */ 901 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 902 903 /* 904 * We are still at a leading dir of the refname (e.g., 905 * "refs/foo"; if there is a reference with that name, 906 * it is a conflict, *unless* it is in skip. 907 */ 908 if (dir) { 909 pos = search_ref_dir(dir, dirname.buf, dirname.len); 910 if (pos >= 0 && 911 (!skip || !string_list_has_string(skip, dirname.buf))) { 912 /* 913 * We found a reference whose name is 914 * a proper prefix of refname; e.g., 915 * "refs/foo", and is not in skip. 916 */ 917 strbuf_addf(err, "'%s' exists; cannot create '%s'", 918 dirname.buf, refname); 919 goto cleanup; 920 } 921 } 922 923 if (extras && string_list_has_string(extras, dirname.buf) && 924 (!skip || !string_list_has_string(skip, dirname.buf))) { 925 strbuf_addf(err, "cannot process '%s' and '%s' at the same time", 926 refname, dirname.buf); 927 goto cleanup; 928 } 929 930 /* 931 * Otherwise, we can try to continue our search with 932 * the next component. So try to look up the 933 * directory, e.g., "refs/foo/". If we come up empty, 934 * we know there is nothing under this whole prefix, 935 * but even in that case we still have to continue the 936 * search for conflicts with extras. 937 */ 938 strbuf_addch(&dirname, '/'); 939 if (dir) { 940 pos = search_ref_dir(dir, dirname.buf, dirname.len); 941 if (pos < 0) { 942 /* 943 * There was no directory "refs/foo/", 944 * so there is nothing under this 945 * whole prefix. So there is no need 946 * to continue looking for conflicting 947 * references. But we need to continue 948 * looking for conflicting extras. 949 */ 950 dir = NULL; 951 } else { 952 dir = get_ref_dir(dir->entries[pos]); 953 } 954 } 955 } 956 957 /* 958 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 959 * There is no point in searching for a reference with that 960 * name, because a refname isn't considered to conflict with 961 * itself. But we still need to check for references whose 962 * names are in the "refs/foo/bar/" namespace, because they 963 * *do* conflict. 964 */ 965 strbuf_addstr(&dirname, refname + dirname.len); 966 strbuf_addch(&dirname, '/'); 967 968 if (dir) { 969 pos = search_ref_dir(dir, dirname.buf, dirname.len); 970 971 if (pos >= 0) { 972 /* 973 * We found a directory named "$refname/" 974 * (e.g., "refs/foo/bar/"). It is a problem 975 * iff it contains any ref that is not in 976 * "skip". 977 */ 978 struct nonmatching_ref_data data; 979 980 data.skip = skip; 981 data.conflicting_refname = NULL; 982 dir = get_ref_dir(dir->entries[pos]); 983 sort_ref_dir(dir); 984 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) { 985 strbuf_addf(err, "'%s' exists; cannot create '%s'", 986 data.conflicting_refname, refname); 987 goto cleanup; 988 } 989 } 990 } 991 992 if (extras) { 993 /* 994 * Check for entries in extras that start with 995 * "$refname/". We do that by looking for the place 996 * where "$refname/" would be inserted in extras. If 997 * there is an entry at that position that starts with 998 * "$refname/" and is not in skip, then we have a 999 * conflict.1000 */1001 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);1002 pos < extras->nr; pos++) {1003 const char *extra_refname = extras->items[pos].string;10041005 if (!starts_with(extra_refname, dirname.buf))1006 break;10071008 if (!skip || !string_list_has_string(skip, extra_refname)) {1009 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",1010 refname, extra_refname);1011 goto cleanup;1012 }1013 }1014 }10151016 /* No conflicts were found */1017 ret = 0;10181019cleanup:1020 strbuf_release(&dirname);1021 return ret;1022}10231024struct packed_ref_cache {1025 struct ref_entry *root;10261027 /*1028 * Count of references to the data structure in this instance,1029 * including the pointer from ref_cache::packed if any. The1030 * data will not be freed as long as the reference count is1031 * nonzero.1032 */1033 unsigned int referrers;10341035 /*1036 * Iff the packed-refs file associated with this instance is1037 * currently locked for writing, this points at the associated1038 * lock (which is owned by somebody else). The referrer count1039 * is also incremented when the file is locked and decremented1040 * when it is unlocked.1041 */1042 struct lock_file *lock;10431044 /* The metadata from when this packed-refs cache was read */1045 struct stat_validity validity;1046};10471048/*1049 * Future: need to be in "struct repository"1050 * when doing a full libification.1051 */1052static struct ref_cache {1053 struct ref_cache *next;1054 struct ref_entry *loose;1055 struct packed_ref_cache *packed;1056 /*1057 * The submodule name, or "" for the main repo. We allocate1058 * length 1 rather than FLEX_ARRAY so that the main ref_cache1059 * is initialized correctly.1060 */1061 char name[1];1062} ref_cache, *submodule_ref_caches;10631064/* Lock used for the main packed-refs file: */1065static struct lock_file packlock;10661067/*1068 * Increment the reference count of *packed_refs.1069 */1070static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1071{1072 packed_refs->referrers++;1073}10741075/*1076 * Decrease the reference count of *packed_refs. If it goes to zero,1077 * free *packed_refs and return true; otherwise return false.1078 */1079static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)1080{1081 if (!--packed_refs->referrers) {1082 free_ref_entry(packed_refs->root);1083 stat_validity_clear(&packed_refs->validity);1084 free(packed_refs);1085 return 1;1086 } else {1087 return 0;1088 }1089}10901091static void clear_packed_ref_cache(struct ref_cache *refs)1092{1093 if (refs->packed) {1094 struct packed_ref_cache *packed_refs = refs->packed;10951096 if (packed_refs->lock)1097 die("internal error: packed-ref cache cleared while locked");1098 refs->packed = NULL;1099 release_packed_ref_cache(packed_refs);1100 }1101}11021103static void clear_loose_ref_cache(struct ref_cache *refs)1104{1105 if (refs->loose) {1106 free_ref_entry(refs->loose);1107 refs->loose = NULL;1108 }1109}11101111static struct ref_cache *create_ref_cache(const char *submodule)1112{1113 int len;1114 struct ref_cache *refs;1115 if (!submodule)1116 submodule = "";1117 len = strlen(submodule) + 1;1118 refs = xcalloc(1, sizeof(struct ref_cache) + len);1119 memcpy(refs->name, submodule, len);1120 return refs;1121}11221123/*1124 * Return a pointer to a ref_cache for the specified submodule. For1125 * the main repository, use submodule==NULL. The returned structure1126 * will be allocated and initialized but not necessarily populated; it1127 * should not be freed.1128 */1129static struct ref_cache *get_ref_cache(const char *submodule)1130{1131 struct ref_cache *refs;11321133 if (!submodule || !*submodule)1134 return &ref_cache;11351136 for (refs = submodule_ref_caches; refs; refs = refs->next)1137 if (!strcmp(submodule, refs->name))1138 return refs;11391140 refs = create_ref_cache(submodule);1141 refs->next = submodule_ref_caches;1142 submodule_ref_caches = refs;1143 return refs;1144}11451146/* The length of a peeled reference line in packed-refs, including EOL: */1147#define PEELED_LINE_LENGTH 4211481149/*1150 * The packed-refs header line that we write out. Perhaps other1151 * traits will be added later. The trailing space is required.1152 */1153static const char PACKED_REFS_HEADER[] =1154 "# pack-refs with: peeled fully-peeled \n";11551156/*1157 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1158 * Return a pointer to the refname within the line (null-terminated),1159 * or NULL if there was a problem.1160 */1161static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)1162{1163 const char *ref;11641165 /*1166 * 42: the answer to everything.1167 *1168 * In this case, it happens to be the answer to1169 * 40 (length of sha1 hex representation)1170 * +1 (space in between hex and name)1171 * +1 (newline at the end of the line)1172 */1173 if (line->len <= 42)1174 return NULL;11751176 if (get_sha1_hex(line->buf, sha1) < 0)1177 return NULL;1178 if (!isspace(line->buf[40]))1179 return NULL;11801181 ref = line->buf + 41;1182 if (isspace(*ref))1183 return NULL;11841185 if (line->buf[line->len - 1] != '\n')1186 return NULL;1187 line->buf[--line->len] = 0;11881189 return ref;1190}11911192/*1193 * Read f, which is a packed-refs file, into dir.1194 *1195 * A comment line of the form "# pack-refs with: " may contain zero or1196 * more traits. We interpret the traits as follows:1197 *1198 * No traits:1199 *1200 * Probably no references are peeled. But if the file contains a1201 * peeled value for a reference, we will use it.1202 *1203 * peeled:1204 *1205 * References under "refs/tags/", if they *can* be peeled, *are*1206 * peeled in this file. References outside of "refs/tags/" are1207 * probably not peeled even if they could have been, but if we find1208 * a peeled value for such a reference we will use it.1209 *1210 * fully-peeled:1211 *1212 * All references in the file that can be peeled are peeled.1213 * Inversely (and this is more important), any references in the1214 * file for which no peeled value is recorded is not peelable. This1215 * trait should typically be written alongside "peeled" for1216 * compatibility with older clients, but we do not require it1217 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1218 */1219static void read_packed_refs(FILE *f, struct ref_dir *dir)1220{1221 struct ref_entry *last = NULL;1222 struct strbuf line = STRBUF_INIT;1223 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12241225 while (strbuf_getwholeline(&line, f, '\n') != EOF) {1226 unsigned char sha1[20];1227 const char *refname;1228 const char *traits;12291230 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {1231 if (strstr(traits, " fully-peeled "))1232 peeled = PEELED_FULLY;1233 else if (strstr(traits, " peeled "))1234 peeled = PEELED_TAGS;1235 /* perhaps other traits later as well */1236 continue;1237 }12381239 refname = parse_ref_line(&line, sha1);1240 if (refname) {1241 int flag = REF_ISPACKED;12421243 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1244 if (!refname_is_safe(refname))1245 die("packed refname is dangerous: %s", refname);1246 hashclr(sha1);1247 flag |= REF_BAD_NAME | REF_ISBROKEN;1248 }1249 last = create_ref_entry(refname, sha1, flag, 0);1250 if (peeled == PEELED_FULLY ||1251 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))1252 last->flag |= REF_KNOWS_PEELED;1253 add_ref(dir, last);1254 continue;1255 }1256 if (last &&1257 line.buf[0] == '^' &&1258 line.len == PEELED_LINE_LENGTH &&1259 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&1260 !get_sha1_hex(line.buf + 1, sha1)) {1261 hashcpy(last->u.value.peeled, sha1);1262 /*1263 * Regardless of what the file header said,1264 * we definitely know the value of *this*1265 * reference:1266 */1267 last->flag |= REF_KNOWS_PEELED;1268 }1269 }12701271 strbuf_release(&line);1272}12731274/*1275 * Get the packed_ref_cache for the specified ref_cache, creating it1276 * if necessary.1277 */1278static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1279{1280 const char *packed_refs_file;12811282 if (*refs->name)1283 packed_refs_file = git_path_submodule(refs->name, "packed-refs");1284 else1285 packed_refs_file = git_path("packed-refs");12861287 if (refs->packed &&1288 !stat_validity_check(&refs->packed->validity, packed_refs_file))1289 clear_packed_ref_cache(refs);12901291 if (!refs->packed) {1292 FILE *f;12931294 refs->packed = xcalloc(1, sizeof(*refs->packed));1295 acquire_packed_ref_cache(refs->packed);1296 refs->packed->root = create_dir_entry(refs, "", 0, 0);1297 f = fopen(packed_refs_file, "r");1298 if (f) {1299 stat_validity_update(&refs->packed->validity, fileno(f));1300 read_packed_refs(f, get_ref_dir(refs->packed->root));1301 fclose(f);1302 }1303 }1304 return refs->packed;1305}13061307static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1308{1309 return get_ref_dir(packed_ref_cache->root);1310}13111312static struct ref_dir *get_packed_refs(struct ref_cache *refs)1313{1314 return get_packed_ref_dir(get_packed_ref_cache(refs));1315}13161317void add_packed_ref(const char *refname, const unsigned char *sha1)1318{1319 struct packed_ref_cache *packed_ref_cache =1320 get_packed_ref_cache(&ref_cache);13211322 if (!packed_ref_cache->lock)1323 die("internal error: packed refs not locked");1324 add_ref(get_packed_ref_dir(packed_ref_cache),1325 create_ref_entry(refname, sha1, REF_ISPACKED, 1));1326}13271328/*1329 * Read the loose references from the namespace dirname into dir1330 * (without recursing). dirname must end with '/'. dir must be the1331 * directory entry corresponding to dirname.1332 */1333static void read_loose_refs(const char *dirname, struct ref_dir *dir)1334{1335 struct ref_cache *refs = dir->ref_cache;1336 DIR *d;1337 const char *path;1338 struct dirent *de;1339 int dirnamelen = strlen(dirname);1340 struct strbuf refname;13411342 if (*refs->name)1343 path = git_path_submodule(refs->name, "%s", dirname);1344 else1345 path = git_path("%s", dirname);13461347 d = opendir(path);1348 if (!d)1349 return;13501351 strbuf_init(&refname, dirnamelen + 257);1352 strbuf_add(&refname, dirname, dirnamelen);13531354 while ((de = readdir(d)) != NULL) {1355 unsigned char sha1[20];1356 struct stat st;1357 int flag;1358 const char *refdir;13591360 if (de->d_name[0] == '.')1361 continue;1362 if (ends_with(de->d_name, ".lock"))1363 continue;1364 strbuf_addstr(&refname, de->d_name);1365 refdir = *refs->name1366 ? git_path_submodule(refs->name, "%s", refname.buf)1367 : git_path("%s", refname.buf);1368 if (stat(refdir, &st) < 0) {1369 ; /* silently ignore */1370 } else if (S_ISDIR(st.st_mode)) {1371 strbuf_addch(&refname, '/');1372 add_entry_to_dir(dir,1373 create_dir_entry(refs, refname.buf,1374 refname.len, 1));1375 } else {1376 if (*refs->name) {1377 hashclr(sha1);1378 flag = 0;1379 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {1380 hashclr(sha1);1381 flag |= REF_ISBROKEN;1382 }1383 } else if (read_ref_full(refname.buf,1384 RESOLVE_REF_READING,1385 sha1, &flag)) {1386 hashclr(sha1);1387 flag |= REF_ISBROKEN;1388 }1389 if (check_refname_format(refname.buf,1390 REFNAME_ALLOW_ONELEVEL)) {1391 if (!refname_is_safe(refname.buf))1392 die("loose refname is dangerous: %s", refname.buf);1393 hashclr(sha1);1394 flag |= REF_BAD_NAME | REF_ISBROKEN;1395 }1396 add_entry_to_dir(dir,1397 create_ref_entry(refname.buf, sha1, flag, 0));1398 }1399 strbuf_setlen(&refname, dirnamelen);1400 }1401 strbuf_release(&refname);1402 closedir(d);1403}14041405static struct ref_dir *get_loose_refs(struct ref_cache *refs)1406{1407 if (!refs->loose) {1408 /*1409 * Mark the top-level directory complete because we1410 * are about to read the only subdirectory that can1411 * hold references:1412 */1413 refs->loose = create_dir_entry(refs, "", 0, 0);1414 /*1415 * Create an incomplete entry for "refs/":1416 */1417 add_entry_to_dir(get_ref_dir(refs->loose),1418 create_dir_entry(refs, "refs/", 5, 1));1419 }1420 return get_ref_dir(refs->loose);1421}14221423/* We allow "recursive" symbolic refs. Only within reason, though */1424#define MAXDEPTH 51425#define MAXREFLEN (1024)14261427/*1428 * Called by resolve_gitlink_ref_recursive() after it failed to read1429 * from the loose refs in ref_cache refs. Find <refname> in the1430 * packed-refs file for the submodule.1431 */1432static int resolve_gitlink_packed_ref(struct ref_cache *refs,1433 const char *refname, unsigned char *sha1)1434{1435 struct ref_entry *ref;1436 struct ref_dir *dir = get_packed_refs(refs);14371438 ref = find_ref(dir, refname);1439 if (ref == NULL)1440 return -1;14411442 hashcpy(sha1, ref->u.value.sha1);1443 return 0;1444}14451446static int resolve_gitlink_ref_recursive(struct ref_cache *refs,1447 const char *refname, unsigned char *sha1,1448 int recursion)1449{1450 int fd, len;1451 char buffer[128], *p;1452 const char *path;14531454 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)1455 return -1;1456 path = *refs->name1457 ? git_path_submodule(refs->name, "%s", refname)1458 : git_path("%s", refname);1459 fd = open(path, O_RDONLY);1460 if (fd < 0)1461 return resolve_gitlink_packed_ref(refs, refname, sha1);14621463 len = read(fd, buffer, sizeof(buffer)-1);1464 close(fd);1465 if (len < 0)1466 return -1;1467 while (len && isspace(buffer[len-1]))1468 len--;1469 buffer[len] = 0;14701471 /* Was it a detached head or an old-fashioned symlink? */1472 if (!get_sha1_hex(buffer, sha1))1473 return 0;14741475 /* Symref? */1476 if (strncmp(buffer, "ref:", 4))1477 return -1;1478 p = buffer + 4;1479 while (isspace(*p))1480 p++;14811482 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1483}14841485int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)1486{1487 int len = strlen(path), retval;1488 char *submodule;1489 struct ref_cache *refs;14901491 while (len && path[len-1] == '/')1492 len--;1493 if (!len)1494 return -1;1495 submodule = xstrndup(path, len);1496 refs = get_ref_cache(submodule);1497 free(submodule);14981499 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);1500 return retval;1501}15021503/*1504 * Return the ref_entry for the given refname from the packed1505 * references. If it does not exist, return NULL.1506 */1507static struct ref_entry *get_packed_ref(const char *refname)1508{1509 return find_ref(get_packed_refs(&ref_cache), refname);1510}15111512/*1513 * A loose ref file doesn't exist; check for a packed ref. The1514 * options are forwarded from resolve_safe_unsafe().1515 */1516static int resolve_missing_loose_ref(const char *refname,1517 int resolve_flags,1518 unsigned char *sha1,1519 int *flags)1520{1521 struct ref_entry *entry;15221523 /*1524 * The loose reference file does not exist; check for a packed1525 * reference.1526 */1527 entry = get_packed_ref(refname);1528 if (entry) {1529 hashcpy(sha1, entry->u.value.sha1);1530 if (flags)1531 *flags |= REF_ISPACKED;1532 return 0;1533 }1534 /* The reference is not a packed reference, either. */1535 if (resolve_flags & RESOLVE_REF_READING) {1536 errno = ENOENT;1537 return -1;1538 } else {1539 hashclr(sha1);1540 return 0;1541 }1542}15431544/* This function needs to return a meaningful errno on failure */1545static const char *resolve_ref_unsafe_1(const char *refname,1546 int resolve_flags,1547 unsigned char *sha1,1548 int *flags,1549 struct strbuf *sb_path)1550{1551 int depth = MAXDEPTH;1552 ssize_t len;1553 char buffer[256];1554 static char refname_buffer[256];1555 int bad_name = 0;15561557 if (flags)1558 *flags = 0;15591560 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1561 if (flags)1562 *flags |= REF_BAD_NAME;15631564 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1565 !refname_is_safe(refname)) {1566 errno = EINVAL;1567 return NULL;1568 }1569 /*1570 * dwim_ref() uses REF_ISBROKEN to distinguish between1571 * missing refs and refs that were present but invalid,1572 * to complain about the latter to stderr.1573 *1574 * We don't know whether the ref exists, so don't set1575 * REF_ISBROKEN yet.1576 */1577 bad_name = 1;1578 }1579 for (;;) {1580 const char *path;1581 struct stat st;1582 char *buf;1583 int fd;15841585 if (--depth < 0) {1586 errno = ELOOP;1587 return NULL;1588 }15891590 strbuf_reset(sb_path);1591 strbuf_git_path(sb_path, "%s", refname);1592 path = sb_path->buf;15931594 /*1595 * We might have to loop back here to avoid a race1596 * condition: first we lstat() the file, then we try1597 * to read it as a link or as a file. But if somebody1598 * changes the type of the file (file <-> directory1599 * <-> symlink) between the lstat() and reading, then1600 * we don't want to report that as an error but rather1601 * try again starting with the lstat().1602 */1603 stat_ref:1604 if (lstat(path, &st) < 0) {1605 if (errno != ENOENT)1606 return NULL;1607 if (resolve_missing_loose_ref(refname, resolve_flags,1608 sha1, flags))1609 return NULL;1610 if (bad_name) {1611 hashclr(sha1);1612 if (flags)1613 *flags |= REF_ISBROKEN;1614 }1615 return refname;1616 }16171618 /* Follow "normalized" - ie "refs/.." symlinks by hand */1619 if (S_ISLNK(st.st_mode)) {1620 len = readlink(path, buffer, sizeof(buffer)-1);1621 if (len < 0) {1622 if (errno == ENOENT || errno == EINVAL)1623 /* inconsistent with lstat; retry */1624 goto stat_ref;1625 else1626 return NULL;1627 }1628 buffer[len] = 0;1629 if (starts_with(buffer, "refs/") &&1630 !check_refname_format(buffer, 0)) {1631 strcpy(refname_buffer, buffer);1632 refname = refname_buffer;1633 if (flags)1634 *flags |= REF_ISSYMREF;1635 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1636 hashclr(sha1);1637 return refname;1638 }1639 continue;1640 }1641 }16421643 /* Is it a directory? */1644 if (S_ISDIR(st.st_mode)) {1645 errno = EISDIR;1646 return NULL;1647 }16481649 /*1650 * Anything else, just open it and try to use it as1651 * a ref1652 */1653 fd = open(path, O_RDONLY);1654 if (fd < 0) {1655 if (errno == ENOENT)1656 /* inconsistent with lstat; retry */1657 goto stat_ref;1658 else1659 return NULL;1660 }1661 len = read_in_full(fd, buffer, sizeof(buffer)-1);1662 if (len < 0) {1663 int save_errno = errno;1664 close(fd);1665 errno = save_errno;1666 return NULL;1667 }1668 close(fd);1669 while (len && isspace(buffer[len-1]))1670 len--;1671 buffer[len] = '\0';16721673 /*1674 * Is it a symbolic ref?1675 */1676 if (!starts_with(buffer, "ref:")) {1677 /*1678 * Please note that FETCH_HEAD has a second1679 * line containing other data.1680 */1681 if (get_sha1_hex(buffer, sha1) ||1682 (buffer[40] != '\0' && !isspace(buffer[40]))) {1683 if (flags)1684 *flags |= REF_ISBROKEN;1685 errno = EINVAL;1686 return NULL;1687 }1688 if (bad_name) {1689 hashclr(sha1);1690 if (flags)1691 *flags |= REF_ISBROKEN;1692 }1693 return refname;1694 }1695 if (flags)1696 *flags |= REF_ISSYMREF;1697 buf = buffer + 4;1698 while (isspace(*buf))1699 buf++;1700 refname = strcpy(refname_buffer, buf);1701 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1702 hashclr(sha1);1703 return refname;1704 }1705 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1706 if (flags)1707 *flags |= REF_ISBROKEN;17081709 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1710 !refname_is_safe(buf)) {1711 errno = EINVAL;1712 return NULL;1713 }1714 bad_name = 1;1715 }1716 }1717}17181719const char *resolve_ref_unsafe(const char *refname, int resolve_flags,1720 unsigned char *sha1, int *flags)1721{1722 struct strbuf sb_path = STRBUF_INIT;1723 const char *ret = resolve_ref_unsafe_1(refname, resolve_flags,1724 sha1, flags, &sb_path);1725 strbuf_release(&sb_path);1726 return ret;1727}17281729char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)1730{1731 return xstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1732}17331734/* The argument to filter_refs */1735struct ref_filter {1736 const char *pattern;1737 each_ref_fn *fn;1738 void *cb_data;1739};17401741int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)1742{1743 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1744 return 0;1745 return -1;1746}17471748int read_ref(const char *refname, unsigned char *sha1)1749{1750 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1751}17521753int ref_exists(const char *refname)1754{1755 unsigned char sha1[20];1756 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1757}17581759static int filter_refs(const char *refname, const unsigned char *sha1, int flags,1760 void *data)1761{1762 struct ref_filter *filter = (struct ref_filter *)data;1763 if (wildmatch(filter->pattern, refname, 0, NULL))1764 return 0;1765 return filter->fn(refname, sha1, flags, filter->cb_data);1766}17671768enum peel_status {1769 /* object was peeled successfully: */1770 PEEL_PEELED = 0,17711772 /*1773 * object cannot be peeled because the named object (or an1774 * object referred to by a tag in the peel chain), does not1775 * exist.1776 */1777 PEEL_INVALID = -1,17781779 /* object cannot be peeled because it is not a tag: */1780 PEEL_NON_TAG = -2,17811782 /* ref_entry contains no peeled value because it is a symref: */1783 PEEL_IS_SYMREF = -3,17841785 /*1786 * ref_entry cannot be peeled because it is broken (i.e., the1787 * symbolic reference cannot even be resolved to an object1788 * name):1789 */1790 PEEL_BROKEN = -41791};17921793/*1794 * Peel the named object; i.e., if the object is a tag, resolve the1795 * tag recursively until a non-tag is found. If successful, store the1796 * result to sha1 and return PEEL_PEELED. If the object is not a tag1797 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1798 * and leave sha1 unchanged.1799 */1800static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)1801{1802 struct object *o = lookup_unknown_object(name);18031804 if (o->type == OBJ_NONE) {1805 int type = sha1_object_info(name, NULL);1806 if (type < 0 || !object_as_type(o, type, 0))1807 return PEEL_INVALID;1808 }18091810 if (o->type != OBJ_TAG)1811 return PEEL_NON_TAG;18121813 o = deref_tag_noverify(o);1814 if (!o)1815 return PEEL_INVALID;18161817 hashcpy(sha1, o->sha1);1818 return PEEL_PEELED;1819}18201821/*1822 * Peel the entry (if possible) and return its new peel_status. If1823 * repeel is true, re-peel the entry even if there is an old peeled1824 * value that is already stored in it.1825 *1826 * It is OK to call this function with a packed reference entry that1827 * might be stale and might even refer to an object that has since1828 * been garbage-collected. In such a case, if the entry has1829 * REF_KNOWS_PEELED then leave the status unchanged and return1830 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1831 */1832static enum peel_status peel_entry(struct ref_entry *entry, int repeel)1833{1834 enum peel_status status;18351836 if (entry->flag & REF_KNOWS_PEELED) {1837 if (repeel) {1838 entry->flag &= ~REF_KNOWS_PEELED;1839 hashclr(entry->u.value.peeled);1840 } else {1841 return is_null_sha1(entry->u.value.peeled) ?1842 PEEL_NON_TAG : PEEL_PEELED;1843 }1844 }1845 if (entry->flag & REF_ISBROKEN)1846 return PEEL_BROKEN;1847 if (entry->flag & REF_ISSYMREF)1848 return PEEL_IS_SYMREF;18491850 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);1851 if (status == PEEL_PEELED || status == PEEL_NON_TAG)1852 entry->flag |= REF_KNOWS_PEELED;1853 return status;1854}18551856int peel_ref(const char *refname, unsigned char *sha1)1857{1858 int flag;1859 unsigned char base[20];18601861 if (current_ref && (current_ref->name == refname1862 || !strcmp(current_ref->name, refname))) {1863 if (peel_entry(current_ref, 0))1864 return -1;1865 hashcpy(sha1, current_ref->u.value.peeled);1866 return 0;1867 }18681869 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1870 return -1;18711872 /*1873 * If the reference is packed, read its ref_entry from the1874 * cache in the hope that we already know its peeled value.1875 * We only try this optimization on packed references because1876 * (a) forcing the filling of the loose reference cache could1877 * be expensive and (b) loose references anyway usually do not1878 * have REF_KNOWS_PEELED.1879 */1880 if (flag & REF_ISPACKED) {1881 struct ref_entry *r = get_packed_ref(refname);1882 if (r) {1883 if (peel_entry(r, 0))1884 return -1;1885 hashcpy(sha1, r->u.value.peeled);1886 return 0;1887 }1888 }18891890 return peel_object(base, sha1);1891}18921893struct warn_if_dangling_data {1894 FILE *fp;1895 const char *refname;1896 const struct string_list *refnames;1897 const char *msg_fmt;1898};18991900static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,1901 int flags, void *cb_data)1902{1903 struct warn_if_dangling_data *d = cb_data;1904 const char *resolves_to;1905 unsigned char junk[20];19061907 if (!(flags & REF_ISSYMREF))1908 return 0;19091910 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);1911 if (!resolves_to1912 || (d->refname1913 ? strcmp(resolves_to, d->refname)1914 : !string_list_has_string(d->refnames, resolves_to))) {1915 return 0;1916 }19171918 fprintf(d->fp, d->msg_fmt, refname);1919 fputc('\n', d->fp);1920 return 0;1921}19221923void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)1924{1925 struct warn_if_dangling_data data;19261927 data.fp = fp;1928 data.refname = refname;1929 data.refnames = NULL;1930 data.msg_fmt = msg_fmt;1931 for_each_rawref(warn_if_dangling_symref, &data);1932}19331934void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)1935{1936 struct warn_if_dangling_data data;19371938 data.fp = fp;1939 data.refname = NULL;1940 data.refnames = refnames;1941 data.msg_fmt = msg_fmt;1942 for_each_rawref(warn_if_dangling_symref, &data);1943}19441945/*1946 * Call fn for each reference in the specified ref_cache, omitting1947 * references not in the containing_dir of base. fn is called for all1948 * references, including broken ones. If fn ever returns a non-zero1949 * value, stop the iteration and return that value; otherwise, return1950 * 0.1951 */1952static int do_for_each_entry(struct ref_cache *refs, const char *base,1953 each_ref_entry_fn fn, void *cb_data)1954{1955 struct packed_ref_cache *packed_ref_cache;1956 struct ref_dir *loose_dir;1957 struct ref_dir *packed_dir;1958 int retval = 0;19591960 /*1961 * We must make sure that all loose refs are read before accessing the1962 * packed-refs file; this avoids a race condition in which loose refs1963 * are migrated to the packed-refs file by a simultaneous process, but1964 * our in-memory view is from before the migration. get_packed_ref_cache()1965 * takes care of making sure our view is up to date with what is on1966 * disk.1967 */1968 loose_dir = get_loose_refs(refs);1969 if (base && *base) {1970 loose_dir = find_containing_dir(loose_dir, base, 0);1971 }1972 if (loose_dir)1973 prime_ref_dir(loose_dir);19741975 packed_ref_cache = get_packed_ref_cache(refs);1976 acquire_packed_ref_cache(packed_ref_cache);1977 packed_dir = get_packed_ref_dir(packed_ref_cache);1978 if (base && *base) {1979 packed_dir = find_containing_dir(packed_dir, base, 0);1980 }19811982 if (packed_dir && loose_dir) {1983 sort_ref_dir(packed_dir);1984 sort_ref_dir(loose_dir);1985 retval = do_for_each_entry_in_dirs(1986 packed_dir, loose_dir, fn, cb_data);1987 } else if (packed_dir) {1988 sort_ref_dir(packed_dir);1989 retval = do_for_each_entry_in_dir(1990 packed_dir, 0, fn, cb_data);1991 } else if (loose_dir) {1992 sort_ref_dir(loose_dir);1993 retval = do_for_each_entry_in_dir(1994 loose_dir, 0, fn, cb_data);1995 }19961997 release_packed_ref_cache(packed_ref_cache);1998 return retval;1999}20002001/*2002 * Call fn for each reference in the specified ref_cache for which the2003 * refname begins with base. If trim is non-zero, then trim that many2004 * characters off the beginning of each refname before passing the2005 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2006 * broken references in the iteration. If fn ever returns a non-zero2007 * value, stop the iteration and return that value; otherwise, return2008 * 0.2009 */2010static int do_for_each_ref(struct ref_cache *refs, const char *base,2011 each_ref_fn fn, int trim, int flags, void *cb_data)2012{2013 struct ref_entry_cb data;2014 data.base = base;2015 data.trim = trim;2016 data.flags = flags;2017 data.fn = fn;2018 data.cb_data = cb_data;20192020 if (ref_paranoia < 0)2021 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);2022 if (ref_paranoia)2023 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20242025 return do_for_each_entry(refs, base, do_one_ref, &data);2026}20272028static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)2029{2030 unsigned char sha1[20];2031 int flag;20322033 if (submodule) {2034 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)2035 return fn("HEAD", sha1, 0, cb_data);20362037 return 0;2038 }20392040 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))2041 return fn("HEAD", sha1, flag, cb_data);20422043 return 0;2044}20452046int head_ref(each_ref_fn fn, void *cb_data)2047{2048 return do_head_ref(NULL, fn, cb_data);2049}20502051int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2052{2053 return do_head_ref(submodule, fn, cb_data);2054}20552056int for_each_ref(each_ref_fn fn, void *cb_data)2057{2058 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);2059}20602061int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2062{2063 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);2064}20652066int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)2067{2068 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);2069}20702071int for_each_ref_in_submodule(const char *submodule, const char *prefix,2072 each_ref_fn fn, void *cb_data)2073{2074 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);2075}20762077int for_each_tag_ref(each_ref_fn fn, void *cb_data)2078{2079 return for_each_ref_in("refs/tags/", fn, cb_data);2080}20812082int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2083{2084 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);2085}20862087int for_each_branch_ref(each_ref_fn fn, void *cb_data)2088{2089 return for_each_ref_in("refs/heads/", fn, cb_data);2090}20912092int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2093{2094 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);2095}20962097int for_each_remote_ref(each_ref_fn fn, void *cb_data)2098{2099 return for_each_ref_in("refs/remotes/", fn, cb_data);2100}21012102int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2103{2104 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);2105}21062107int for_each_replace_ref(each_ref_fn fn, void *cb_data)2108{2109 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);2110}21112112int head_ref_namespaced(each_ref_fn fn, void *cb_data)2113{2114 struct strbuf buf = STRBUF_INIT;2115 int ret = 0;2116 unsigned char sha1[20];2117 int flag;21182119 strbuf_addf(&buf, "%sHEAD", get_git_namespace());2120 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2121 ret = fn(buf.buf, sha1, flag, cb_data);2122 strbuf_release(&buf);21232124 return ret;2125}21262127int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)2128{2129 struct strbuf buf = STRBUF_INIT;2130 int ret;2131 strbuf_addf(&buf, "%srefs/", get_git_namespace());2132 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);2133 strbuf_release(&buf);2134 return ret;2135}21362137int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,2138 const char *prefix, void *cb_data)2139{2140 struct strbuf real_pattern = STRBUF_INIT;2141 struct ref_filter filter;2142 int ret;21432144 if (!prefix && !starts_with(pattern, "refs/"))2145 strbuf_addstr(&real_pattern, "refs/");2146 else if (prefix)2147 strbuf_addstr(&real_pattern, prefix);2148 strbuf_addstr(&real_pattern, pattern);21492150 if (!has_glob_specials(pattern)) {2151 /* Append implied '/' '*' if not present. */2152 if (real_pattern.buf[real_pattern.len - 1] != '/')2153 strbuf_addch(&real_pattern, '/');2154 /* No need to check for '*', there is none. */2155 strbuf_addch(&real_pattern, '*');2156 }21572158 filter.pattern = real_pattern.buf;2159 filter.fn = fn;2160 filter.cb_data = cb_data;2161 ret = for_each_ref(filter_refs, &filter);21622163 strbuf_release(&real_pattern);2164 return ret;2165}21662167int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)2168{2169 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);2170}21712172int for_each_rawref(each_ref_fn fn, void *cb_data)2173{2174 return do_for_each_ref(&ref_cache, "", fn, 0,2175 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2176}21772178const char *prettify_refname(const char *name)2179{2180 return name + (2181 starts_with(name, "refs/heads/") ? 11 :2182 starts_with(name, "refs/tags/") ? 10 :2183 starts_with(name, "refs/remotes/") ? 13 :2184 0);2185}21862187static const char *ref_rev_parse_rules[] = {2188 "%.*s",2189 "refs/%.*s",2190 "refs/tags/%.*s",2191 "refs/heads/%.*s",2192 "refs/remotes/%.*s",2193 "refs/remotes/%.*s/HEAD",2194 NULL2195};21962197int refname_match(const char *abbrev_name, const char *full_name)2198{2199 const char **p;2200 const int abbrev_name_len = strlen(abbrev_name);22012202 for (p = ref_rev_parse_rules; *p; p++) {2203 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {2204 return 1;2205 }2206 }22072208 return 0;2209}22102211static void unlock_ref(struct ref_lock *lock)2212{2213 /* Do not free lock->lk -- atexit() still looks at them */2214 if (lock->lk)2215 rollback_lock_file(lock->lk);2216 free(lock->ref_name);2217 free(lock->orig_ref_name);2218 free(lock);2219}22202221/*2222 * Verify that the reference locked by lock has the value old_sha1.2223 * Fail if the reference doesn't exist and mustexist is set. Return 02224 * on success or a negative value on error. This function should make2225 * sure errno is meaningful on error.2226 */2227static int verify_lock(struct ref_lock *lock,2228 const unsigned char *old_sha1, int mustexist)2229{2230 if (read_ref_full(lock->ref_name,2231 mustexist ? RESOLVE_REF_READING : 0,2232 lock->old_sha1, NULL)) {2233 int save_errno = errno;2234 error("Can't verify ref %s", lock->ref_name);2235 unlock_ref(lock);2236 errno = save_errno;2237 return -1;2238 }2239 if (hashcmp(lock->old_sha1, old_sha1)) {2240 error("Ref %s is at %s but expected %s", lock->ref_name,2241 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));2242 unlock_ref(lock);2243 errno = EBUSY;2244 return -1;2245 }2246 return 0;2247}22482249static int remove_empty_directories(const char *file)2250{2251 /* we want to create a file but there is a directory there;2252 * if that is an empty directory (or a directory that contains2253 * only empty directories), remove them.2254 */2255 struct strbuf path;2256 int result, save_errno;22572258 strbuf_init(&path, 20);2259 strbuf_addstr(&path, file);22602261 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2262 save_errno = errno;22632264 strbuf_release(&path);2265 errno = save_errno;22662267 return result;2268}22692270/*2271 * *string and *len will only be substituted, and *string returned (for2272 * later free()ing) if the string passed in is a magic short-hand form2273 * to name a branch.2274 */2275static char *substitute_branch_name(const char **string, int *len)2276{2277 struct strbuf buf = STRBUF_INIT;2278 int ret = interpret_branch_name(*string, *len, &buf);22792280 if (ret == *len) {2281 size_t size;2282 *string = strbuf_detach(&buf, &size);2283 *len = size;2284 return (char *)*string;2285 }22862287 return NULL;2288}22892290int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)2291{2292 char *last_branch = substitute_branch_name(&str, &len);2293 const char **p, *r;2294 int refs_found = 0;22952296 *ref = NULL;2297 for (p = ref_rev_parse_rules; *p; p++) {2298 char fullref[PATH_MAX];2299 unsigned char sha1_from_ref[20];2300 unsigned char *this_result;2301 int flag;23022303 this_result = refs_found ? sha1_from_ref : sha1;2304 mksnpath(fullref, sizeof(fullref), *p, len, str);2305 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2306 this_result, &flag);2307 if (r) {2308 if (!refs_found++)2309 *ref = xstrdup(r);2310 if (!warn_ambiguous_refs)2311 break;2312 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {2313 warning("ignoring dangling symref %s.", fullref);2314 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {2315 warning("ignoring broken ref %s.", fullref);2316 }2317 }2318 free(last_branch);2319 return refs_found;2320}23212322int dwim_log(const char *str, int len, unsigned char *sha1, char **log)2323{2324 char *last_branch = substitute_branch_name(&str, &len);2325 const char **p;2326 int logs_found = 0;23272328 *log = NULL;2329 for (p = ref_rev_parse_rules; *p; p++) {2330 unsigned char hash[20];2331 char path[PATH_MAX];2332 const char *ref, *it;23332334 mksnpath(path, sizeof(path), *p, len, str);2335 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,2336 hash, NULL);2337 if (!ref)2338 continue;2339 if (reflog_exists(path))2340 it = path;2341 else if (strcmp(ref, path) && reflog_exists(ref))2342 it = ref;2343 else2344 continue;2345 if (!logs_found++) {2346 *log = xstrdup(it);2347 hashcpy(sha1, hash);2348 }2349 if (!warn_ambiguous_refs)2350 break;2351 }2352 free(last_branch);2353 return logs_found;2354}23552356/*2357 * Locks a ref returning the lock on success and NULL on failure.2358 * On failure errno is set to something meaningful.2359 */2360static struct ref_lock *lock_ref_sha1_basic(const char *refname,2361 const unsigned char *old_sha1,2362 const struct string_list *extras,2363 const struct string_list *skip,2364 unsigned int flags, int *type_p,2365 struct strbuf *err)2366{2367 const char *ref_file;2368 const char *orig_refname = refname;2369 struct ref_lock *lock;2370 int last_errno = 0;2371 int type, lflags;2372 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2373 int resolve_flags = 0;2374 int attempts_remaining = 3;23752376 assert(err);23772378 lock = xcalloc(1, sizeof(struct ref_lock));23792380 if (mustexist)2381 resolve_flags |= RESOLVE_REF_READING;2382 if (flags & REF_DELETING) {2383 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2384 if (flags & REF_NODEREF)2385 resolve_flags |= RESOLVE_REF_NO_RECURSE;2386 }23872388 refname = resolve_ref_unsafe(refname, resolve_flags,2389 lock->old_sha1, &type);2390 if (!refname && errno == EISDIR) {2391 /* we are trying to lock foo but we used to2392 * have foo/bar which now does not exist;2393 * it is normal for the empty directory 'foo'2394 * to remain.2395 */2396 ref_file = git_path("%s", orig_refname);2397 if (remove_empty_directories(ref_file)) {2398 last_errno = errno;23992400 if (!verify_refname_available(orig_refname, extras, skip,2401 get_loose_refs(&ref_cache), err))2402 strbuf_addf(err, "there are still refs under '%s'",2403 orig_refname);24042405 goto error_return;2406 }2407 refname = resolve_ref_unsafe(orig_refname, resolve_flags,2408 lock->old_sha1, &type);2409 }2410 if (type_p)2411 *type_p = type;2412 if (!refname) {2413 last_errno = errno;2414 if (last_errno != ENOTDIR ||2415 !verify_refname_available(orig_refname, extras, skip,2416 get_loose_refs(&ref_cache), err))2417 strbuf_addf(err, "unable to resolve reference %s: %s",2418 orig_refname, strerror(last_errno));24192420 goto error_return;2421 }2422 /*2423 * If the ref did not exist and we are creating it, make sure2424 * there is no existing packed ref whose name begins with our2425 * refname, nor a packed ref whose name is a proper prefix of2426 * our refname.2427 */2428 if (is_null_sha1(lock->old_sha1) &&2429 verify_refname_available(refname, extras, skip,2430 get_packed_refs(&ref_cache), err)) {2431 last_errno = ENOTDIR;2432 goto error_return;2433 }24342435 lock->lk = xcalloc(1, sizeof(struct lock_file));24362437 lflags = 0;2438 if (flags & REF_NODEREF) {2439 refname = orig_refname;2440 lflags |= LOCK_NO_DEREF;2441 }2442 lock->ref_name = xstrdup(refname);2443 lock->orig_ref_name = xstrdup(orig_refname);2444 ref_file = git_path("%s", refname);24452446 retry:2447 switch (safe_create_leading_directories_const(ref_file)) {2448 case SCLD_OK:2449 break; /* success */2450 case SCLD_VANISHED:2451 if (--attempts_remaining > 0)2452 goto retry;2453 /* fall through */2454 default:2455 last_errno = errno;2456 strbuf_addf(err, "unable to create directory for %s", ref_file);2457 goto error_return;2458 }24592460 if (hold_lock_file_for_update(lock->lk, ref_file, lflags) < 0) {2461 last_errno = errno;2462 if (errno == ENOENT && --attempts_remaining > 0)2463 /*2464 * Maybe somebody just deleted one of the2465 * directories leading to ref_file. Try2466 * again:2467 */2468 goto retry;2469 else {2470 unable_to_lock_message(ref_file, errno, err);2471 goto error_return;2472 }2473 }2474 if (old_sha1 && verify_lock(lock, old_sha1, mustexist))2475 return NULL;2476 return lock;24772478 error_return:2479 unlock_ref(lock);2480 errno = last_errno;2481 return NULL;2482}24832484/*2485 * Write an entry to the packed-refs file for the specified refname.2486 * If peeled is non-NULL, write it as the entry's peeled value.2487 */2488static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,2489 unsigned char *peeled)2490{2491 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);2492 if (peeled)2493 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));2494}24952496/*2497 * An each_ref_entry_fn that writes the entry to a packed-refs file.2498 */2499static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)2500{2501 enum peel_status peel_status = peel_entry(entry, 0);25022503 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2504 error("internal error: %s is not a valid packed reference!",2505 entry->name);2506 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2507 peel_status == PEEL_PEELED ?2508 entry->u.value.peeled : NULL);2509 return 0;2510}25112512/* This should return a meaningful errno on failure */2513int lock_packed_refs(int flags)2514{2515 static int timeout_configured = 0;2516 static int timeout_value = 1000;25172518 struct packed_ref_cache *packed_ref_cache;25192520 if (!timeout_configured) {2521 git_config_get_int("core.packedrefstimeout", &timeout_value);2522 timeout_configured = 1;2523 }25242525 if (hold_lock_file_for_update_timeout(2526 &packlock, git_path("packed-refs"),2527 flags, timeout_value) < 0)2528 return -1;2529 /*2530 * Get the current packed-refs while holding the lock. If the2531 * packed-refs file has been modified since we last read it,2532 * this will automatically invalidate the cache and re-read2533 * the packed-refs file.2534 */2535 packed_ref_cache = get_packed_ref_cache(&ref_cache);2536 packed_ref_cache->lock = &packlock;2537 /* Increment the reference count to prevent it from being freed: */2538 acquire_packed_ref_cache(packed_ref_cache);2539 return 0;2540}25412542/*2543 * Commit the packed refs changes.2544 * On error we must make sure that errno contains a meaningful value.2545 */2546int commit_packed_refs(void)2547{2548 struct packed_ref_cache *packed_ref_cache =2549 get_packed_ref_cache(&ref_cache);2550 int error = 0;2551 int save_errno = 0;2552 FILE *out;25532554 if (!packed_ref_cache->lock)2555 die("internal error: packed-refs not locked");25562557 out = fdopen_lock_file(packed_ref_cache->lock, "w");2558 if (!out)2559 die_errno("unable to fdopen packed-refs descriptor");25602561 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);2562 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),2563 0, write_packed_entry_fn, out);25642565 if (commit_lock_file(packed_ref_cache->lock)) {2566 save_errno = errno;2567 error = -1;2568 }2569 packed_ref_cache->lock = NULL;2570 release_packed_ref_cache(packed_ref_cache);2571 errno = save_errno;2572 return error;2573}25742575void rollback_packed_refs(void)2576{2577 struct packed_ref_cache *packed_ref_cache =2578 get_packed_ref_cache(&ref_cache);25792580 if (!packed_ref_cache->lock)2581 die("internal error: packed-refs not locked");2582 rollback_lock_file(packed_ref_cache->lock);2583 packed_ref_cache->lock = NULL;2584 release_packed_ref_cache(packed_ref_cache);2585 clear_packed_ref_cache(&ref_cache);2586}25872588struct ref_to_prune {2589 struct ref_to_prune *next;2590 unsigned char sha1[20];2591 char name[FLEX_ARRAY];2592};25932594struct pack_refs_cb_data {2595 unsigned int flags;2596 struct ref_dir *packed_refs;2597 struct ref_to_prune *ref_to_prune;2598};25992600/*2601 * An each_ref_entry_fn that is run over loose references only. If2602 * the loose reference can be packed, add an entry in the packed ref2603 * cache. If the reference should be pruned, also add it to2604 * ref_to_prune in the pack_refs_cb_data.2605 */2606static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)2607{2608 struct pack_refs_cb_data *cb = cb_data;2609 enum peel_status peel_status;2610 struct ref_entry *packed_entry;2611 int is_tag_ref = starts_with(entry->name, "refs/tags/");26122613 /* ALWAYS pack tags */2614 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2615 return 0;26162617 /* Do not pack symbolic or broken refs: */2618 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2619 return 0;26202621 /* Add a packed ref cache entry equivalent to the loose entry. */2622 peel_status = peel_entry(entry, 1);2623 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2624 die("internal error peeling reference %s (%s)",2625 entry->name, sha1_to_hex(entry->u.value.sha1));2626 packed_entry = find_ref(cb->packed_refs, entry->name);2627 if (packed_entry) {2628 /* Overwrite existing packed entry with info from loose entry */2629 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2630 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2631 } else {2632 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,2633 REF_ISPACKED | REF_KNOWS_PEELED, 0);2634 add_ref(cb->packed_refs, packed_entry);2635 }2636 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);26372638 /* Schedule the loose reference for pruning if requested. */2639 if ((cb->flags & PACK_REFS_PRUNE)) {2640 int namelen = strlen(entry->name) + 1;2641 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);2642 hashcpy(n->sha1, entry->u.value.sha1);2643 strcpy(n->name, entry->name);2644 n->next = cb->ref_to_prune;2645 cb->ref_to_prune = n;2646 }2647 return 0;2648}26492650/*2651 * Remove empty parents, but spare refs/ and immediate subdirs.2652 * Note: munges *name.2653 */2654static void try_remove_empty_parents(char *name)2655{2656 char *p, *q;2657 int i;2658 p = name;2659 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */2660 while (*p && *p != '/')2661 p++;2662 /* tolerate duplicate slashes; see check_refname_format() */2663 while (*p == '/')2664 p++;2665 }2666 for (q = p; *q; q++)2667 ;2668 while (1) {2669 while (q > p && *q != '/')2670 q--;2671 while (q > p && *(q-1) == '/')2672 q--;2673 if (q == p)2674 break;2675 *q = '\0';2676 if (rmdir(git_path("%s", name)))2677 break;2678 }2679}26802681/* make sure nobody touched the ref, and unlink */2682static void prune_ref(struct ref_to_prune *r)2683{2684 struct ref_transaction *transaction;2685 struct strbuf err = STRBUF_INIT;26862687 if (check_refname_format(r->name, 0))2688 return;26892690 transaction = ref_transaction_begin(&err);2691 if (!transaction ||2692 ref_transaction_delete(transaction, r->name, r->sha1,2693 REF_ISPRUNING, NULL, &err) ||2694 ref_transaction_commit(transaction, &err)) {2695 ref_transaction_free(transaction);2696 error("%s", err.buf);2697 strbuf_release(&err);2698 return;2699 }2700 ref_transaction_free(transaction);2701 strbuf_release(&err);2702 try_remove_empty_parents(r->name);2703}27042705static void prune_refs(struct ref_to_prune *r)2706{2707 while (r) {2708 prune_ref(r);2709 r = r->next;2710 }2711}27122713int pack_refs(unsigned int flags)2714{2715 struct pack_refs_cb_data cbdata;27162717 memset(&cbdata, 0, sizeof(cbdata));2718 cbdata.flags = flags;27192720 lock_packed_refs(LOCK_DIE_ON_ERROR);2721 cbdata.packed_refs = get_packed_refs(&ref_cache);27222723 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,2724 pack_if_possible_fn, &cbdata);27252726 if (commit_packed_refs())2727 die_errno("unable to overwrite old ref-pack file");27282729 prune_refs(cbdata.ref_to_prune);2730 return 0;2731}27322733int repack_without_refs(struct string_list *refnames, struct strbuf *err)2734{2735 struct ref_dir *packed;2736 struct string_list_item *refname;2737 int ret, needs_repacking = 0, removed = 0;27382739 assert(err);27402741 /* Look for a packed ref */2742 for_each_string_list_item(refname, refnames) {2743 if (get_packed_ref(refname->string)) {2744 needs_repacking = 1;2745 break;2746 }2747 }27482749 /* Avoid locking if we have nothing to do */2750 if (!needs_repacking)2751 return 0; /* no refname exists in packed refs */27522753 if (lock_packed_refs(0)) {2754 unable_to_lock_message(git_path("packed-refs"), errno, err);2755 return -1;2756 }2757 packed = get_packed_refs(&ref_cache);27582759 /* Remove refnames from the cache */2760 for_each_string_list_item(refname, refnames)2761 if (remove_entry(packed, refname->string) != -1)2762 removed = 1;2763 if (!removed) {2764 /*2765 * All packed entries disappeared while we were2766 * acquiring the lock.2767 */2768 rollback_packed_refs();2769 return 0;2770 }27712772 /* Write what remains */2773 ret = commit_packed_refs();2774 if (ret)2775 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",2776 strerror(errno));2777 return ret;2778}27792780static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)2781{2782 assert(err);27832784 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2785 /*2786 * loose. The loose file name is the same as the2787 * lockfile name, minus ".lock":2788 */2789 char *loose_filename = get_locked_file_path(lock->lk);2790 int res = unlink_or_msg(loose_filename, err);2791 free(loose_filename);2792 if (res)2793 return 1;2794 }2795 return 0;2796}27972798int delete_ref(const char *refname, const unsigned char *sha1, unsigned int flags)2799{2800 struct ref_transaction *transaction;2801 struct strbuf err = STRBUF_INIT;28022803 transaction = ref_transaction_begin(&err);2804 if (!transaction ||2805 ref_transaction_delete(transaction, refname,2806 (sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2807 flags, NULL, &err) ||2808 ref_transaction_commit(transaction, &err)) {2809 error("%s", err.buf);2810 ref_transaction_free(transaction);2811 strbuf_release(&err);2812 return 1;2813 }2814 ref_transaction_free(transaction);2815 strbuf_release(&err);2816 return 0;2817}28182819/*2820 * People using contrib's git-new-workdir have .git/logs/refs ->2821 * /some/other/path/.git/logs/refs, and that may live on another device.2822 *2823 * IOW, to avoid cross device rename errors, the temporary renamed log must2824 * live into logs/refs.2825 */2826#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"28272828static int rename_tmp_log(const char *newrefname)2829{2830 int attempts_remaining = 4;28312832 retry:2833 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2834 case SCLD_OK:2835 break; /* success */2836 case SCLD_VANISHED:2837 if (--attempts_remaining > 0)2838 goto retry;2839 /* fall through */2840 default:2841 error("unable to create directory for %s", newrefname);2842 return -1;2843 }28442845 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {2846 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {2847 /*2848 * rename(a, b) when b is an existing2849 * directory ought to result in ISDIR, but2850 * Solaris 5.8 gives ENOTDIR. Sheesh.2851 */2852 if (remove_empty_directories(git_path("logs/%s", newrefname))) {2853 error("Directory not empty: logs/%s", newrefname);2854 return -1;2855 }2856 goto retry;2857 } else if (errno == ENOENT && --attempts_remaining > 0) {2858 /*2859 * Maybe another process just deleted one of2860 * the directories in the path to newrefname.2861 * Try again from the beginning.2862 */2863 goto retry;2864 } else {2865 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",2866 newrefname, strerror(errno));2867 return -1;2868 }2869 }2870 return 0;2871}28722873static int rename_ref_available(const char *oldname, const char *newname)2874{2875 struct string_list skip = STRING_LIST_INIT_NODUP;2876 struct strbuf err = STRBUF_INIT;2877 int ret;28782879 string_list_insert(&skip, oldname);2880 ret = !verify_refname_available(newname, NULL, &skip,2881 get_packed_refs(&ref_cache), &err)2882 && !verify_refname_available(newname, NULL, &skip,2883 get_loose_refs(&ref_cache), &err);2884 if (!ret)2885 error("%s", err.buf);28862887 string_list_clear(&skip, 0);2888 strbuf_release(&err);2889 return ret;2890}28912892static int write_ref_to_lockfile(struct ref_lock *lock, const unsigned char *sha1);2893static int commit_ref_update(struct ref_lock *lock,2894 const unsigned char *sha1, const char *logmsg);28952896int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)2897{2898 unsigned char sha1[20], orig_sha1[20];2899 int flag = 0, logmoved = 0;2900 struct ref_lock *lock;2901 struct stat loginfo;2902 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2903 const char *symref = NULL;2904 struct strbuf err = STRBUF_INIT;29052906 if (log && S_ISLNK(loginfo.st_mode))2907 return error("reflog for %s is a symlink", oldrefname);29082909 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2910 orig_sha1, &flag);2911 if (flag & REF_ISSYMREF)2912 return error("refname %s is a symbolic ref, renaming it is not supported",2913 oldrefname);2914 if (!symref)2915 return error("refname %s not found", oldrefname);29162917 if (!rename_ref_available(oldrefname, newrefname))2918 return 1;29192920 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))2921 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",2922 oldrefname, strerror(errno));29232924 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2925 error("unable to delete old %s", oldrefname);2926 goto rollback;2927 }29282929 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2930 delete_ref(newrefname, sha1, REF_NODEREF)) {2931 if (errno==EISDIR) {2932 if (remove_empty_directories(git_path("%s", newrefname))) {2933 error("Directory not empty: %s", newrefname);2934 goto rollback;2935 }2936 } else {2937 error("unable to delete existing %s", newrefname);2938 goto rollback;2939 }2940 }29412942 if (log && rename_tmp_log(newrefname))2943 goto rollback;29442945 logmoved = log;29462947 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);2948 if (!lock) {2949 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);2950 strbuf_release(&err);2951 goto rollback;2952 }2953 hashcpy(lock->old_sha1, orig_sha1);29542955 if (write_ref_to_lockfile(lock, orig_sha1) ||2956 commit_ref_update(lock, orig_sha1, logmsg)) {2957 error("unable to write current sha1 into %s", newrefname);2958 goto rollback;2959 }29602961 return 0;29622963 rollback:2964 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);2965 if (!lock) {2966 error("unable to lock %s for rollback: %s", oldrefname, err.buf);2967 strbuf_release(&err);2968 goto rollbacklog;2969 }29702971 flag = log_all_ref_updates;2972 log_all_ref_updates = 0;2973 if (write_ref_to_lockfile(lock, orig_sha1) ||2974 commit_ref_update(lock, orig_sha1, NULL))2975 error("unable to write current sha1 into %s", oldrefname);2976 log_all_ref_updates = flag;29772978 rollbacklog:2979 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))2980 error("unable to restore logfile %s from %s: %s",2981 oldrefname, newrefname, strerror(errno));2982 if (!logmoved && log &&2983 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))2984 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",2985 oldrefname, strerror(errno));29862987 return 1;2988}29892990static int close_ref(struct ref_lock *lock)2991{2992 if (close_lock_file(lock->lk))2993 return -1;2994 return 0;2995}29962997static int commit_ref(struct ref_lock *lock)2998{2999 if (commit_lock_file(lock->lk))3000 return -1;3001 return 0;3002}30033004/*3005 * copy the reflog message msg to buf, which has been allocated sufficiently3006 * large, while cleaning up the whitespaces. Especially, convert LF to space,3007 * because reflog file is one line per entry.3008 */3009static int copy_msg(char *buf, const char *msg)3010{3011 char *cp = buf;3012 char c;3013 int wasspace = 1;30143015 *cp++ = '\t';3016 while ((c = *msg++)) {3017 if (wasspace && isspace(c))3018 continue;3019 wasspace = isspace(c);3020 if (wasspace)3021 c = ' ';3022 *cp++ = c;3023 }3024 while (buf < cp && isspace(cp[-1]))3025 cp--;3026 *cp++ = '\n';3027 return cp - buf;3028}30293030/* This function must set a meaningful errno on failure */3031int log_ref_setup(const char *refname, struct strbuf *sb_logfile)3032{3033 int logfd, oflags = O_APPEND | O_WRONLY;3034 char *logfile;30353036 strbuf_git_path(sb_logfile, "logs/%s", refname);3037 logfile = sb_logfile->buf;3038 /* make sure the rest of the function can't change "logfile" */3039 sb_logfile = NULL;3040 if (log_all_ref_updates &&3041 (starts_with(refname, "refs/heads/") ||3042 starts_with(refname, "refs/remotes/") ||3043 starts_with(refname, "refs/notes/") ||3044 !strcmp(refname, "HEAD"))) {3045 if (safe_create_leading_directories(logfile) < 0) {3046 int save_errno = errno;3047 error("unable to create directory for %s", logfile);3048 errno = save_errno;3049 return -1;3050 }3051 oflags |= O_CREAT;3052 }30533054 logfd = open(logfile, oflags, 0666);3055 if (logfd < 0) {3056 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3057 return 0;30583059 if (errno == EISDIR) {3060 if (remove_empty_directories(logfile)) {3061 int save_errno = errno;3062 error("There are still logs under '%s'",3063 logfile);3064 errno = save_errno;3065 return -1;3066 }3067 logfd = open(logfile, oflags, 0666);3068 }30693070 if (logfd < 0) {3071 int save_errno = errno;3072 error("Unable to append to %s: %s", logfile,3073 strerror(errno));3074 errno = save_errno;3075 return -1;3076 }3077 }30783079 adjust_shared_perm(logfile);3080 close(logfd);3081 return 0;3082}30833084static int log_ref_write_fd(int fd, const unsigned char *old_sha1,3085 const unsigned char *new_sha1,3086 const char *committer, const char *msg)3087{3088 int msglen, written;3089 unsigned maxlen, len;3090 char *logrec;30913092 msglen = msg ? strlen(msg) : 0;3093 maxlen = strlen(committer) + msglen + 100;3094 logrec = xmalloc(maxlen);3095 len = sprintf(logrec, "%s %s %s\n",3096 sha1_to_hex(old_sha1),3097 sha1_to_hex(new_sha1),3098 committer);3099 if (msglen)3100 len += copy_msg(logrec + len - 1, msg) - 1;31013102 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;3103 free(logrec);3104 if (written != len)3105 return -1;31063107 return 0;3108}31093110static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,3111 const unsigned char *new_sha1, const char *msg,3112 struct strbuf *sb_log_file)3113{3114 int logfd, result, oflags = O_APPEND | O_WRONLY;3115 char *log_file;31163117 if (log_all_ref_updates < 0)3118 log_all_ref_updates = !is_bare_repository();31193120 result = log_ref_setup(refname, sb_log_file);3121 if (result)3122 return result;3123 log_file = sb_log_file->buf;3124 /* make sure the rest of the function can't change "log_file" */3125 sb_log_file = NULL;31263127 logfd = open(log_file, oflags);3128 if (logfd < 0)3129 return 0;3130 result = log_ref_write_fd(logfd, old_sha1, new_sha1,3131 git_committer_info(0), msg);3132 if (result) {3133 int save_errno = errno;3134 close(logfd);3135 error("Unable to append to %s", log_file);3136 errno = save_errno;3137 return -1;3138 }3139 if (close(logfd)) {3140 int save_errno = errno;3141 error("Unable to append to %s", log_file);3142 errno = save_errno;3143 return -1;3144 }3145 return 0;3146}31473148static int log_ref_write(const char *refname, const unsigned char *old_sha1,3149 const unsigned char *new_sha1, const char *msg)3150{3151 struct strbuf sb = STRBUF_INIT;3152 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);3153 strbuf_release(&sb);3154 return ret;3155}31563157int is_branch(const char *refname)3158{3159 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");3160}31613162/*3163 * Write sha1 into the open lockfile, then close the lockfile. On3164 * errors, rollback the lockfile and set errno to reflect the problem.3165 */3166static int write_ref_to_lockfile(struct ref_lock *lock,3167 const unsigned char *sha1)3168{3169 static char term = '\n';3170 struct object *o;31713172 o = parse_object(sha1);3173 if (!o) {3174 error("Trying to write ref %s with nonexistent object %s",3175 lock->ref_name, sha1_to_hex(sha1));3176 unlock_ref(lock);3177 errno = EINVAL;3178 return -1;3179 }3180 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {3181 error("Trying to write non-commit object %s to branch %s",3182 sha1_to_hex(sha1), lock->ref_name);3183 unlock_ref(lock);3184 errno = EINVAL;3185 return -1;3186 }3187 if (write_in_full(lock->lk->fd, sha1_to_hex(sha1), 40) != 40 ||3188 write_in_full(lock->lk->fd, &term, 1) != 1 ||3189 close_ref(lock) < 0) {3190 int save_errno = errno;3191 error("Couldn't write %s", lock->lk->filename.buf);3192 unlock_ref(lock);3193 errno = save_errno;3194 return -1;3195 }3196 return 0;3197}31983199/*3200 * Commit a change to a loose reference that has already been written3201 * to the loose reference lockfile. Also update the reflogs if3202 * necessary, using the specified lockmsg (which can be NULL).3203 */3204static int commit_ref_update(struct ref_lock *lock,3205 const unsigned char *sha1, const char *logmsg)3206{3207 clear_loose_ref_cache(&ref_cache);3208 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||3209 (strcmp(lock->ref_name, lock->orig_ref_name) &&3210 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {3211 unlock_ref(lock);3212 return -1;3213 }3214 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {3215 /*3216 * Special hack: If a branch is updated directly and HEAD3217 * points to it (may happen on the remote side of a push3218 * for example) then logically the HEAD reflog should be3219 * updated too.3220 * A generic solution implies reverse symref information,3221 * but finding all symrefs pointing to the given branch3222 * would be rather costly for this rare event (the direct3223 * update of a branch) to be worth it. So let's cheat and3224 * check with HEAD only which should cover 99% of all usage3225 * scenarios (even 100% of the default ones).3226 */3227 unsigned char head_sha1[20];3228 int head_flag;3229 const char *head_ref;3230 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3231 head_sha1, &head_flag);3232 if (head_ref && (head_flag & REF_ISSYMREF) &&3233 !strcmp(head_ref, lock->ref_name))3234 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3235 }3236 if (commit_ref(lock)) {3237 error("Couldn't set %s", lock->ref_name);3238 unlock_ref(lock);3239 return -1;3240 }3241 unlock_ref(lock);3242 return 0;3243}32443245int create_symref(const char *ref_target, const char *refs_heads_master,3246 const char *logmsg)3247{3248 const char *lockpath;3249 char ref[1000];3250 int fd, len, written;3251 char *git_HEAD = git_pathdup("%s", ref_target);3252 unsigned char old_sha1[20], new_sha1[20];32533254 if (logmsg && read_ref(ref_target, old_sha1))3255 hashclr(old_sha1);32563257 if (safe_create_leading_directories(git_HEAD) < 0)3258 return error("unable to create directory for %s", git_HEAD);32593260#ifndef NO_SYMLINK_HEAD3261 if (prefer_symlink_refs) {3262 unlink(git_HEAD);3263 if (!symlink(refs_heads_master, git_HEAD))3264 goto done;3265 fprintf(stderr, "no symlink - falling back to symbolic ref\n");3266 }3267#endif32683269 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);3270 if (sizeof(ref) <= len) {3271 error("refname too long: %s", refs_heads_master);3272 goto error_free_return;3273 }3274 lockpath = mkpath("%s.lock", git_HEAD);3275 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);3276 if (fd < 0) {3277 error("Unable to open %s for writing", lockpath);3278 goto error_free_return;3279 }3280 written = write_in_full(fd, ref, len);3281 if (close(fd) != 0 || written != len) {3282 error("Unable to write to %s", lockpath);3283 goto error_unlink_return;3284 }3285 if (rename(lockpath, git_HEAD) < 0) {3286 error("Unable to create %s", git_HEAD);3287 goto error_unlink_return;3288 }3289 if (adjust_shared_perm(git_HEAD)) {3290 error("Unable to fix permissions on %s", lockpath);3291 error_unlink_return:3292 unlink_or_warn(lockpath);3293 error_free_return:3294 free(git_HEAD);3295 return -1;3296 }32973298#ifndef NO_SYMLINK_HEAD3299 done:3300#endif3301 if (logmsg && !read_ref(refs_heads_master, new_sha1))3302 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);33033304 free(git_HEAD);3305 return 0;3306}33073308struct read_ref_at_cb {3309 const char *refname;3310 unsigned long at_time;3311 int cnt;3312 int reccnt;3313 unsigned char *sha1;3314 int found_it;33153316 unsigned char osha1[20];3317 unsigned char nsha1[20];3318 int tz;3319 unsigned long date;3320 char **msg;3321 unsigned long *cutoff_time;3322 int *cutoff_tz;3323 int *cutoff_cnt;3324};33253326static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,3327 const char *email, unsigned long timestamp, int tz,3328 const char *message, void *cb_data)3329{3330 struct read_ref_at_cb *cb = cb_data;33313332 cb->reccnt++;3333 cb->tz = tz;3334 cb->date = timestamp;33353336 if (timestamp <= cb->at_time || cb->cnt == 0) {3337 if (cb->msg)3338 *cb->msg = xstrdup(message);3339 if (cb->cutoff_time)3340 *cb->cutoff_time = timestamp;3341 if (cb->cutoff_tz)3342 *cb->cutoff_tz = tz;3343 if (cb->cutoff_cnt)3344 *cb->cutoff_cnt = cb->reccnt - 1;3345 /*3346 * we have not yet updated cb->[n|o]sha1 so they still3347 * hold the values for the previous record.3348 */3349 if (!is_null_sha1(cb->osha1)) {3350 hashcpy(cb->sha1, nsha1);3351 if (hashcmp(cb->osha1, nsha1))3352 warning("Log for ref %s has gap after %s.",3353 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));3354 }3355 else if (cb->date == cb->at_time)3356 hashcpy(cb->sha1, nsha1);3357 else if (hashcmp(nsha1, cb->sha1))3358 warning("Log for ref %s unexpectedly ended on %s.",3359 cb->refname, show_date(cb->date, cb->tz,3360 DATE_RFC2822));3361 hashcpy(cb->osha1, osha1);3362 hashcpy(cb->nsha1, nsha1);3363 cb->found_it = 1;3364 return 1;3365 }3366 hashcpy(cb->osha1, osha1);3367 hashcpy(cb->nsha1, nsha1);3368 if (cb->cnt > 0)3369 cb->cnt--;3370 return 0;3371}33723373static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,3374 const char *email, unsigned long timestamp,3375 int tz, const char *message, void *cb_data)3376{3377 struct read_ref_at_cb *cb = cb_data;33783379 if (cb->msg)3380 *cb->msg = xstrdup(message);3381 if (cb->cutoff_time)3382 *cb->cutoff_time = timestamp;3383 if (cb->cutoff_tz)3384 *cb->cutoff_tz = tz;3385 if (cb->cutoff_cnt)3386 *cb->cutoff_cnt = cb->reccnt;3387 hashcpy(cb->sha1, osha1);3388 if (is_null_sha1(cb->sha1))3389 hashcpy(cb->sha1, nsha1);3390 /* We just want the first entry */3391 return 1;3392}33933394int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,3395 unsigned char *sha1, char **msg,3396 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)3397{3398 struct read_ref_at_cb cb;33993400 memset(&cb, 0, sizeof(cb));3401 cb.refname = refname;3402 cb.at_time = at_time;3403 cb.cnt = cnt;3404 cb.msg = msg;3405 cb.cutoff_time = cutoff_time;3406 cb.cutoff_tz = cutoff_tz;3407 cb.cutoff_cnt = cutoff_cnt;3408 cb.sha1 = sha1;34093410 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);34113412 if (!cb.reccnt) {3413 if (flags & GET_SHA1_QUIETLY)3414 exit(128);3415 else3416 die("Log for %s is empty.", refname);3417 }3418 if (cb.found_it)3419 return 0;34203421 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);34223423 return 1;3424}34253426int reflog_exists(const char *refname)3427{3428 struct stat st;34293430 return !lstat(git_path("logs/%s", refname), &st) &&3431 S_ISREG(st.st_mode);3432}34333434int delete_reflog(const char *refname)3435{3436 return remove_path(git_path("logs/%s", refname));3437}34383439static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)3440{3441 unsigned char osha1[20], nsha1[20];3442 char *email_end, *message;3443 unsigned long timestamp;3444 int tz;34453446 /* old SP new SP name <email> SP time TAB msg LF */3447 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||3448 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||3449 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||3450 !(email_end = strchr(sb->buf + 82, '>')) ||3451 email_end[1] != ' ' ||3452 !(timestamp = strtoul(email_end + 2, &message, 10)) ||3453 !message || message[0] != ' ' ||3454 (message[1] != '+' && message[1] != '-') ||3455 !isdigit(message[2]) || !isdigit(message[3]) ||3456 !isdigit(message[4]) || !isdigit(message[5]))3457 return 0; /* corrupt? */3458 email_end[1] = '\0';3459 tz = strtol(message + 1, NULL, 10);3460 if (message[6] != '\t')3461 message += 6;3462 else3463 message += 7;3464 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);3465}34663467static char *find_beginning_of_line(char *bob, char *scan)3468{3469 while (bob < scan && *(--scan) != '\n')3470 ; /* keep scanning backwards */3471 /*3472 * Return either beginning of the buffer, or LF at the end of3473 * the previous line.3474 */3475 return scan;3476}34773478int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)3479{3480 struct strbuf sb = STRBUF_INIT;3481 FILE *logfp;3482 long pos;3483 int ret = 0, at_tail = 1;34843485 logfp = fopen(git_path("logs/%s", refname), "r");3486 if (!logfp)3487 return -1;34883489 /* Jump to the end */3490 if (fseek(logfp, 0, SEEK_END) < 0)3491 return error("cannot seek back reflog for %s: %s",3492 refname, strerror(errno));3493 pos = ftell(logfp);3494 while (!ret && 0 < pos) {3495 int cnt;3496 size_t nread;3497 char buf[BUFSIZ];3498 char *endp, *scanp;34993500 /* Fill next block from the end */3501 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;3502 if (fseek(logfp, pos - cnt, SEEK_SET))3503 return error("cannot seek back reflog for %s: %s",3504 refname, strerror(errno));3505 nread = fread(buf, cnt, 1, logfp);3506 if (nread != 1)3507 return error("cannot read %d bytes from reflog for %s: %s",3508 cnt, refname, strerror(errno));3509 pos -= cnt;35103511 scanp = endp = buf + cnt;3512 if (at_tail && scanp[-1] == '\n')3513 /* Looking at the final LF at the end of the file */3514 scanp--;3515 at_tail = 0;35163517 while (buf < scanp) {3518 /*3519 * terminating LF of the previous line, or the beginning3520 * of the buffer.3521 */3522 char *bp;35233524 bp = find_beginning_of_line(buf, scanp);35253526 if (*bp == '\n') {3527 /*3528 * The newline is the end of the previous line,3529 * so we know we have complete line starting3530 * at (bp + 1). Prefix it onto any prior data3531 * we collected for the line and process it.3532 */3533 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));3534 scanp = bp;3535 endp = bp + 1;3536 ret = show_one_reflog_ent(&sb, fn, cb_data);3537 strbuf_reset(&sb);3538 if (ret)3539 break;3540 } else if (!pos) {3541 /*3542 * We are at the start of the buffer, and the3543 * start of the file; there is no previous3544 * line, and we have everything for this one.3545 * Process it, and we can end the loop.3546 */3547 strbuf_splice(&sb, 0, 0, buf, endp - buf);3548 ret = show_one_reflog_ent(&sb, fn, cb_data);3549 strbuf_reset(&sb);3550 break;3551 }35523553 if (bp == buf) {3554 /*3555 * We are at the start of the buffer, and there3556 * is more file to read backwards. Which means3557 * we are in the middle of a line. Note that we3558 * may get here even if *bp was a newline; that3559 * just means we are at the exact end of the3560 * previous line, rather than some spot in the3561 * middle.3562 *3563 * Save away what we have to be combined with3564 * the data from the next read.3565 */3566 strbuf_splice(&sb, 0, 0, buf, endp - buf);3567 break;3568 }3569 }35703571 }3572 if (!ret && sb.len)3573 die("BUG: reverse reflog parser had leftover data");35743575 fclose(logfp);3576 strbuf_release(&sb);3577 return ret;3578}35793580int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)3581{3582 FILE *logfp;3583 struct strbuf sb = STRBUF_INIT;3584 int ret = 0;35853586 logfp = fopen(git_path("logs/%s", refname), "r");3587 if (!logfp)3588 return -1;35893590 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))3591 ret = show_one_reflog_ent(&sb, fn, cb_data);3592 fclose(logfp);3593 strbuf_release(&sb);3594 return ret;3595}3596/*3597 * Call fn for each reflog in the namespace indicated by name. name3598 * must be empty or end with '/'. Name will be used as a scratch3599 * space, but its contents will be restored before return.3600 */3601static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)3602{3603 DIR *d = opendir(git_path("logs/%s", name->buf));3604 int retval = 0;3605 struct dirent *de;3606 int oldlen = name->len;36073608 if (!d)3609 return name->len ? errno : 0;36103611 while ((de = readdir(d)) != NULL) {3612 struct stat st;36133614 if (de->d_name[0] == '.')3615 continue;3616 if (ends_with(de->d_name, ".lock"))3617 continue;3618 strbuf_addstr(name, de->d_name);3619 if (stat(git_path("logs/%s", name->buf), &st) < 0) {3620 ; /* silently ignore */3621 } else {3622 if (S_ISDIR(st.st_mode)) {3623 strbuf_addch(name, '/');3624 retval = do_for_each_reflog(name, fn, cb_data);3625 } else {3626 unsigned char sha1[20];3627 if (read_ref_full(name->buf, 0, sha1, NULL))3628 retval = error("bad ref for %s", name->buf);3629 else3630 retval = fn(name->buf, sha1, 0, cb_data);3631 }3632 if (retval)3633 break;3634 }3635 strbuf_setlen(name, oldlen);3636 }3637 closedir(d);3638 return retval;3639}36403641int for_each_reflog(each_ref_fn fn, void *cb_data)3642{3643 int retval;3644 struct strbuf name;3645 strbuf_init(&name, PATH_MAX);3646 retval = do_for_each_reflog(&name, fn, cb_data);3647 strbuf_release(&name);3648 return retval;3649}36503651/**3652 * Information needed for a single ref update. Set new_sha1 to the new3653 * value or to null_sha1 to delete the ref. To check the old value3654 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3655 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3656 * not exist before update.3657 */3658struct ref_update {3659 /*3660 * If (flags & REF_HAVE_NEW), set the reference to this value:3661 */3662 unsigned char new_sha1[20];3663 /*3664 * If (flags & REF_HAVE_OLD), check that the reference3665 * previously had this value:3666 */3667 unsigned char old_sha1[20];3668 /*3669 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3670 * REF_DELETING, and REF_ISPRUNING:3671 */3672 unsigned int flags;3673 struct ref_lock *lock;3674 int type;3675 char *msg;3676 const char refname[FLEX_ARRAY];3677};36783679/*3680 * Transaction states.3681 * OPEN: The transaction is in a valid state and can accept new updates.3682 * An OPEN transaction can be committed.3683 * CLOSED: A closed transaction is no longer active and no other operations3684 * than free can be used on it in this state.3685 * A transaction can either become closed by successfully committing3686 * an active transaction or if there is a failure while building3687 * the transaction thus rendering it failed/inactive.3688 */3689enum ref_transaction_state {3690 REF_TRANSACTION_OPEN = 0,3691 REF_TRANSACTION_CLOSED = 13692};36933694/*3695 * Data structure for holding a reference transaction, which can3696 * consist of checks and updates to multiple references, carried out3697 * as atomically as possible. This structure is opaque to callers.3698 */3699struct ref_transaction {3700 struct ref_update **updates;3701 size_t alloc;3702 size_t nr;3703 enum ref_transaction_state state;3704};37053706struct ref_transaction *ref_transaction_begin(struct strbuf *err)3707{3708 assert(err);37093710 return xcalloc(1, sizeof(struct ref_transaction));3711}37123713void ref_transaction_free(struct ref_transaction *transaction)3714{3715 int i;37163717 if (!transaction)3718 return;37193720 for (i = 0; i < transaction->nr; i++) {3721 free(transaction->updates[i]->msg);3722 free(transaction->updates[i]);3723 }3724 free(transaction->updates);3725 free(transaction);3726}37273728static struct ref_update *add_update(struct ref_transaction *transaction,3729 const char *refname)3730{3731 size_t len = strlen(refname);3732 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);37333734 strcpy((char *)update->refname, refname);3735 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);3736 transaction->updates[transaction->nr++] = update;3737 return update;3738}37393740int ref_transaction_update(struct ref_transaction *transaction,3741 const char *refname,3742 const unsigned char *new_sha1,3743 const unsigned char *old_sha1,3744 unsigned int flags, const char *msg,3745 struct strbuf *err)3746{3747 struct ref_update *update;37483749 assert(err);37503751 if (transaction->state != REF_TRANSACTION_OPEN)3752 die("BUG: update called for transaction that is not open");37533754 if (new_sha1 && !is_null_sha1(new_sha1) &&3755 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3756 strbuf_addf(err, "refusing to update ref with bad name %s",3757 refname);3758 return -1;3759 }37603761 update = add_update(transaction, refname);3762 if (new_sha1) {3763 hashcpy(update->new_sha1, new_sha1);3764 flags |= REF_HAVE_NEW;3765 }3766 if (old_sha1) {3767 hashcpy(update->old_sha1, old_sha1);3768 flags |= REF_HAVE_OLD;3769 }3770 update->flags = flags;3771 if (msg)3772 update->msg = xstrdup(msg);3773 return 0;3774}37753776int ref_transaction_create(struct ref_transaction *transaction,3777 const char *refname,3778 const unsigned char *new_sha1,3779 unsigned int flags, const char *msg,3780 struct strbuf *err)3781{3782 if (!new_sha1 || is_null_sha1(new_sha1))3783 die("BUG: create called without valid new_sha1");3784 return ref_transaction_update(transaction, refname, new_sha1,3785 null_sha1, flags, msg, err);3786}37873788int ref_transaction_delete(struct ref_transaction *transaction,3789 const char *refname,3790 const unsigned char *old_sha1,3791 unsigned int flags, const char *msg,3792 struct strbuf *err)3793{3794 if (old_sha1 && is_null_sha1(old_sha1))3795 die("BUG: delete called with old_sha1 set to zeros");3796 return ref_transaction_update(transaction, refname,3797 null_sha1, old_sha1,3798 flags, msg, err);3799}38003801int ref_transaction_verify(struct ref_transaction *transaction,3802 const char *refname,3803 const unsigned char *old_sha1,3804 unsigned int flags,3805 struct strbuf *err)3806{3807 if (!old_sha1)3808 die("BUG: verify called with old_sha1 set to NULL");3809 return ref_transaction_update(transaction, refname,3810 NULL, old_sha1,3811 flags, NULL, err);3812}38133814int update_ref(const char *msg, const char *refname,3815 const unsigned char *new_sha1, const unsigned char *old_sha1,3816 unsigned int flags, enum action_on_err onerr)3817{3818 struct ref_transaction *t;3819 struct strbuf err = STRBUF_INIT;38203821 t = ref_transaction_begin(&err);3822 if (!t ||3823 ref_transaction_update(t, refname, new_sha1, old_sha1,3824 flags, msg, &err) ||3825 ref_transaction_commit(t, &err)) {3826 const char *str = "update_ref failed for ref '%s': %s";38273828 ref_transaction_free(t);3829 switch (onerr) {3830 case UPDATE_REFS_MSG_ON_ERR:3831 error(str, refname, err.buf);3832 break;3833 case UPDATE_REFS_DIE_ON_ERR:3834 die(str, refname, err.buf);3835 break;3836 case UPDATE_REFS_QUIET_ON_ERR:3837 break;3838 }3839 strbuf_release(&err);3840 return 1;3841 }3842 strbuf_release(&err);3843 ref_transaction_free(t);3844 return 0;3845}38463847static int ref_update_reject_duplicates(struct string_list *refnames,3848 struct strbuf *err)3849{3850 int i, n = refnames->nr;38513852 assert(err);38533854 for (i = 1; i < n; i++)3855 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {3856 strbuf_addf(err,3857 "Multiple updates for ref '%s' not allowed.",3858 refnames->items[i].string);3859 return 1;3860 }3861 return 0;3862}38633864int ref_transaction_commit(struct ref_transaction *transaction,3865 struct strbuf *err)3866{3867 int ret = 0, i;3868 int n = transaction->nr;3869 struct ref_update **updates = transaction->updates;3870 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3871 struct string_list_item *ref_to_delete;3872 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38733874 assert(err);38753876 if (transaction->state != REF_TRANSACTION_OPEN)3877 die("BUG: commit called for transaction that is not open");38783879 if (!n) {3880 transaction->state = REF_TRANSACTION_CLOSED;3881 return 0;3882 }38833884 /* Fail if a refname appears more than once in the transaction: */3885 for (i = 0; i < n; i++)3886 string_list_append(&affected_refnames, updates[i]->refname);3887 string_list_sort(&affected_refnames);3888 if (ref_update_reject_duplicates(&affected_refnames, err)) {3889 ret = TRANSACTION_GENERIC_ERROR;3890 goto cleanup;3891 }38923893 /*3894 * Acquire all locks, verify old values if provided, check3895 * that new values are valid, and write new values to the3896 * lockfiles, ready to be activated. Only keep one lockfile3897 * open at a time to avoid running out of file descriptors.3898 */3899 for (i = 0; i < n; i++) {3900 struct ref_update *update = updates[i];39013902 if ((update->flags & REF_HAVE_NEW) &&3903 is_null_sha1(update->new_sha1))3904 update->flags |= REF_DELETING;3905 update->lock = lock_ref_sha1_basic(3906 update->refname,3907 ((update->flags & REF_HAVE_OLD) ?3908 update->old_sha1 : NULL),3909 &affected_refnames, NULL,3910 update->flags,3911 &update->type,3912 err);3913 if (!update->lock) {3914 char *reason;39153916 ret = (errno == ENOTDIR)3917 ? TRANSACTION_NAME_CONFLICT3918 : TRANSACTION_GENERIC_ERROR;3919 reason = strbuf_detach(err, NULL);3920 strbuf_addf(err, "Cannot lock ref '%s': %s",3921 update->refname, reason);3922 free(reason);3923 goto cleanup;3924 }3925 if ((update->flags & REF_HAVE_NEW) &&3926 !(update->flags & REF_DELETING)) {3927 int overwriting_symref = ((update->type & REF_ISSYMREF) &&3928 (update->flags & REF_NODEREF));39293930 if (!overwriting_symref &&3931 !hashcmp(update->lock->old_sha1, update->new_sha1)) {3932 /*3933 * The reference already has the desired3934 * value, so we don't need to write it.3935 */3936 } else if (write_ref_to_lockfile(update->lock,3937 update->new_sha1)) {3938 /*3939 * The lock was freed upon failure of3940 * write_ref_to_lockfile():3941 */3942 update->lock = NULL;3943 strbuf_addf(err, "Cannot update the ref '%s'.",3944 update->refname);3945 ret = TRANSACTION_GENERIC_ERROR;3946 goto cleanup;3947 } else {3948 update->flags |= REF_NEEDS_COMMIT;3949 }3950 }3951 if (!(update->flags & REF_NEEDS_COMMIT)) {3952 /*3953 * We didn't have to write anything to the lockfile.3954 * Close it to free up the file descriptor:3955 */3956 if (close_ref(update->lock)) {3957 strbuf_addf(err, "Couldn't close %s.lock",3958 update->refname);3959 goto cleanup;3960 }3961 }3962 }39633964 /* Perform updates first so live commits remain referenced */3965 for (i = 0; i < n; i++) {3966 struct ref_update *update = updates[i];39673968 if (update->flags & REF_NEEDS_COMMIT) {3969 if (commit_ref_update(update->lock,3970 update->new_sha1, update->msg)) {3971 /* freed by commit_ref_update(): */3972 update->lock = NULL;3973 strbuf_addf(err, "Cannot update the ref '%s'.",3974 update->refname);3975 ret = TRANSACTION_GENERIC_ERROR;3976 goto cleanup;3977 } else {3978 /* freed by commit_ref_update(): */3979 update->lock = NULL;3980 }3981 }3982 }39833984 /* Perform deletes now that updates are safely completed */3985 for (i = 0; i < n; i++) {3986 struct ref_update *update = updates[i];39873988 if (update->flags & REF_DELETING) {3989 if (delete_ref_loose(update->lock, update->type, err)) {3990 ret = TRANSACTION_GENERIC_ERROR;3991 goto cleanup;3992 }39933994 if (!(update->flags & REF_ISPRUNING))3995 string_list_append(&refs_to_delete,3996 update->lock->ref_name);3997 }3998 }39994000 if (repack_without_refs(&refs_to_delete, err)) {4001 ret = TRANSACTION_GENERIC_ERROR;4002 goto cleanup;4003 }4004 for_each_string_list_item(ref_to_delete, &refs_to_delete)4005 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4006 clear_loose_ref_cache(&ref_cache);40074008cleanup:4009 transaction->state = REF_TRANSACTION_CLOSED;40104011 for (i = 0; i < n; i++)4012 if (updates[i]->lock)4013 unlock_ref(updates[i]->lock);4014 string_list_clear(&refs_to_delete, 0);4015 string_list_clear(&affected_refnames, 0);4016 return ret;4017}40184019char *shorten_unambiguous_ref(const char *refname, int strict)4020{4021 int i;4022 static char **scanf_fmts;4023 static int nr_rules;4024 char *short_name;40254026 if (!nr_rules) {4027 /*4028 * Pre-generate scanf formats from ref_rev_parse_rules[].4029 * Generate a format suitable for scanf from a4030 * ref_rev_parse_rules rule by interpolating "%s" at the4031 * location of the "%.*s".4032 */4033 size_t total_len = 0;4034 size_t offset = 0;40354036 /* the rule list is NULL terminated, count them first */4037 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)4038 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4039 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;40404041 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);40424043 offset = 0;4044 for (i = 0; i < nr_rules; i++) {4045 assert(offset < total_len);4046 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;4047 offset += snprintf(scanf_fmts[i], total_len - offset,4048 ref_rev_parse_rules[i], 2, "%s") + 1;4049 }4050 }40514052 /* bail out if there are no rules */4053 if (!nr_rules)4054 return xstrdup(refname);40554056 /* buffer for scanf result, at most refname must fit */4057 short_name = xstrdup(refname);40584059 /* skip first rule, it will always match */4060 for (i = nr_rules - 1; i > 0 ; --i) {4061 int j;4062 int rules_to_fail = i;4063 int short_name_len;40644065 if (1 != sscanf(refname, scanf_fmts[i], short_name))4066 continue;40674068 short_name_len = strlen(short_name);40694070 /*4071 * in strict mode, all (except the matched one) rules4072 * must fail to resolve to a valid non-ambiguous ref4073 */4074 if (strict)4075 rules_to_fail = nr_rules;40764077 /*4078 * check if the short name resolves to a valid ref,4079 * but use only rules prior to the matched one4080 */4081 for (j = 0; j < rules_to_fail; j++) {4082 const char *rule = ref_rev_parse_rules[j];4083 char refname[PATH_MAX];40844085 /* skip matched rule */4086 if (i == j)4087 continue;40884089 /*4090 * the short name is ambiguous, if it resolves4091 * (with this previous rule) to a valid ref4092 * read_ref() returns 0 on success4093 */4094 mksnpath(refname, sizeof(refname),4095 rule, short_name_len, short_name);4096 if (ref_exists(refname))4097 break;4098 }40994100 /*4101 * short name is non-ambiguous if all previous rules4102 * haven't resolved to a valid ref4103 */4104 if (j == rules_to_fail)4105 return short_name;4106 }41074108 free(short_name);4109 return xstrdup(refname);4110}41114112static struct string_list *hide_refs;41134114int parse_hide_refs_config(const char *var, const char *value, const char *section)4115{4116 if (!strcmp("transfer.hiderefs", var) ||4117 /* NEEDSWORK: use parse_config_key() once both are merged */4118 (starts_with(var, section) && var[strlen(section)] == '.' &&4119 !strcmp(var + strlen(section), ".hiderefs"))) {4120 char *ref;4121 int len;41224123 if (!value)4124 return config_error_nonbool(var);4125 ref = xstrdup(value);4126 len = strlen(ref);4127 while (len && ref[len - 1] == '/')4128 ref[--len] = '\0';4129 if (!hide_refs) {4130 hide_refs = xcalloc(1, sizeof(*hide_refs));4131 hide_refs->strdup_strings = 1;4132 }4133 string_list_append(hide_refs, ref);4134 }4135 return 0;4136}41374138int ref_is_hidden(const char *refname)4139{4140 struct string_list_item *item;41414142 if (!hide_refs)4143 return 0;4144 for_each_string_list_item(item, hide_refs) {4145 int len;4146 if (!starts_with(refname, item->string))4147 continue;4148 len = strlen(item->string);4149 if (!refname[len] || refname[len] == '/')4150 return 1;4151 }4152 return 0;4153}41544155struct expire_reflog_cb {4156 unsigned int flags;4157 reflog_expiry_should_prune_fn *should_prune_fn;4158 void *policy_cb;4159 FILE *newlog;4160 unsigned char last_kept_sha1[20];4161};41624163static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,4164 const char *email, unsigned long timestamp, int tz,4165 const char *message, void *cb_data)4166{4167 struct expire_reflog_cb *cb = cb_data;4168 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41694170 if (cb->flags & EXPIRE_REFLOGS_REWRITE)4171 osha1 = cb->last_kept_sha1;41724173 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4174 message, policy_cb)) {4175 if (!cb->newlog)4176 printf("would prune %s", message);4177 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)4178 printf("prune %s", message);4179 } else {4180 if (cb->newlog) {4181 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",4182 sha1_to_hex(osha1), sha1_to_hex(nsha1),4183 email, timestamp, tz, message);4184 hashcpy(cb->last_kept_sha1, nsha1);4185 }4186 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)4187 printf("keep %s", message);4188 }4189 return 0;4190}41914192int reflog_expire(const char *refname, const unsigned char *sha1,4193 unsigned int flags,4194 reflog_expiry_prepare_fn prepare_fn,4195 reflog_expiry_should_prune_fn should_prune_fn,4196 reflog_expiry_cleanup_fn cleanup_fn,4197 void *policy_cb_data)4198{4199 static struct lock_file reflog_lock;4200 struct expire_reflog_cb cb;4201 struct ref_lock *lock;4202 char *log_file;4203 int status = 0;4204 int type;4205 struct strbuf err = STRBUF_INIT;42064207 memset(&cb, 0, sizeof(cb));4208 cb.flags = flags;4209 cb.policy_cb = policy_cb_data;4210 cb.should_prune_fn = should_prune_fn;42114212 /*4213 * The reflog file is locked by holding the lock on the4214 * reference itself, plus we might need to update the4215 * reference if --updateref was specified:4216 */4217 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);4218 if (!lock) {4219 error("cannot lock ref '%s': %s", refname, err.buf);4220 strbuf_release(&err);4221 return -1;4222 }4223 if (!reflog_exists(refname)) {4224 unlock_ref(lock);4225 return 0;4226 }42274228 log_file = git_pathdup("logs/%s", refname);4229 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4230 /*4231 * Even though holding $GIT_DIR/logs/$reflog.lock has4232 * no locking implications, we use the lock_file4233 * machinery here anyway because it does a lot of the4234 * work we need, including cleaning up if the program4235 * exits unexpectedly.4236 */4237 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {4238 struct strbuf err = STRBUF_INIT;4239 unable_to_lock_message(log_file, errno, &err);4240 error("%s", err.buf);4241 strbuf_release(&err);4242 goto failure;4243 }4244 cb.newlog = fdopen_lock_file(&reflog_lock, "w");4245 if (!cb.newlog) {4246 error("cannot fdopen %s (%s)",4247 reflog_lock.filename.buf, strerror(errno));4248 goto failure;4249 }4250 }42514252 (*prepare_fn)(refname, sha1, cb.policy_cb);4253 for_each_reflog_ent(refname, expire_reflog_ent, &cb);4254 (*cleanup_fn)(cb.policy_cb);42554256 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4257 /*4258 * It doesn't make sense to adjust a reference pointed4259 * to by a symbolic ref based on expiring entries in4260 * the symbolic reference's reflog. Nor can we update4261 * a reference if there are no remaining reflog4262 * entries.4263 */4264 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4265 !(type & REF_ISSYMREF) &&4266 !is_null_sha1(cb.last_kept_sha1);42674268 if (close_lock_file(&reflog_lock)) {4269 status |= error("couldn't write %s: %s", log_file,4270 strerror(errno));4271 } else if (update &&4272 (write_in_full(lock->lk->fd,4273 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||4274 write_str_in_full(lock->lk->fd, "\n") != 1 ||4275 close_ref(lock) < 0)) {4276 status |= error("couldn't write %s",4277 lock->lk->filename.buf);4278 rollback_lock_file(&reflog_lock);4279 } else if (commit_lock_file(&reflog_lock)) {4280 status |= error("unable to commit reflog '%s' (%s)",4281 log_file, strerror(errno));4282 } else if (update && commit_ref(lock)) {4283 status |= error("couldn't set %s", lock->ref_name);4284 }4285 }4286 free(log_file);4287 unlock_ref(lock);4288 return status;42894290 failure:4291 rollback_lock_file(&reflog_lock);4292 free(log_file);4293 unlock_ref(lock);4294 return -1;4295}