refs.con commit DESTDIR support for git/contrib/emacs (1e31fbe)
   1#include "cache.h"
   2#include "refs.h"
   3#include "object.h"
   4#include "tag.h"
   5
   6/* ISSYMREF=01 and ISPACKED=02 are public interfaces */
   7#define REF_KNOWS_PEELED 04
   8
   9struct ref_list {
  10        struct ref_list *next;
  11        unsigned char flag; /* ISSYMREF? ISPACKED? */
  12        unsigned char sha1[20];
  13        unsigned char peeled[20];
  14        char name[FLEX_ARRAY];
  15};
  16
  17static const char *parse_ref_line(char *line, unsigned char *sha1)
  18{
  19        /*
  20         * 42: the answer to everything.
  21         *
  22         * In this case, it happens to be the answer to
  23         *  40 (length of sha1 hex representation)
  24         *  +1 (space in between hex and name)
  25         *  +1 (newline at the end of the line)
  26         */
  27        int len = strlen(line) - 42;
  28
  29        if (len <= 0)
  30                return NULL;
  31        if (get_sha1_hex(line, sha1) < 0)
  32                return NULL;
  33        if (!isspace(line[40]))
  34                return NULL;
  35        line += 41;
  36        if (isspace(*line))
  37                return NULL;
  38        if (line[len] != '\n')
  39                return NULL;
  40        line[len] = 0;
  41
  42        return line;
  43}
  44
  45static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
  46                                int flag, struct ref_list *list,
  47                                struct ref_list **new_entry)
  48{
  49        int len;
  50        struct ref_list **p = &list, *entry;
  51
  52        /* Find the place to insert the ref into.. */
  53        while ((entry = *p) != NULL) {
  54                int cmp = strcmp(entry->name, name);
  55                if (cmp > 0)
  56                        break;
  57
  58                /* Same as existing entry? */
  59                if (!cmp) {
  60                        if (new_entry)
  61                                *new_entry = entry;
  62                        return list;
  63                }
  64                p = &entry->next;
  65        }
  66
  67        /* Allocate it and add it in.. */
  68        len = strlen(name) + 1;
  69        entry = xmalloc(sizeof(struct ref_list) + len);
  70        hashcpy(entry->sha1, sha1);
  71        hashclr(entry->peeled);
  72        memcpy(entry->name, name, len);
  73        entry->flag = flag;
  74        entry->next = *p;
  75        *p = entry;
  76        if (new_entry)
  77                *new_entry = entry;
  78        return list;
  79}
  80
  81/*
  82 * Future: need to be in "struct repository"
  83 * when doing a full libification.
  84 */
  85struct cached_refs {
  86        char did_loose;
  87        char did_packed;
  88        struct ref_list *loose;
  89        struct ref_list *packed;
  90} cached_refs;
  91
  92static void free_ref_list(struct ref_list *list)
  93{
  94        struct ref_list *next;
  95        for ( ; list; list = next) {
  96                next = list->next;
  97                free(list);
  98        }
  99}
 100
 101static void invalidate_cached_refs(void)
 102{
 103        struct cached_refs *ca = &cached_refs;
 104
 105        if (ca->did_loose && ca->loose)
 106                free_ref_list(ca->loose);
 107        if (ca->did_packed && ca->packed)
 108                free_ref_list(ca->packed);
 109        ca->loose = ca->packed = NULL;
 110        ca->did_loose = ca->did_packed = 0;
 111}
 112
 113static void read_packed_refs(FILE *f, struct cached_refs *cached_refs)
 114{
 115        struct ref_list *list = NULL;
 116        struct ref_list *last = NULL;
 117        char refline[PATH_MAX];
 118        int flag = REF_ISPACKED;
 119
 120        while (fgets(refline, sizeof(refline), f)) {
 121                unsigned char sha1[20];
 122                const char *name;
 123                static const char header[] = "# pack-refs with:";
 124
 125                if (!strncmp(refline, header, sizeof(header)-1)) {
 126                        const char *traits = refline + sizeof(header) - 1;
 127                        if (strstr(traits, " peeled "))
 128                                flag |= REF_KNOWS_PEELED;
 129                        /* perhaps other traits later as well */
 130                        continue;
 131                }
 132
 133                name = parse_ref_line(refline, sha1);
 134                if (name) {
 135                        list = add_ref(name, sha1, flag, list, &last);
 136                        continue;
 137                }
 138                if (last &&
 139                    refline[0] == '^' &&
 140                    strlen(refline) == 42 &&
 141                    refline[41] == '\n' &&
 142                    !get_sha1_hex(refline + 1, sha1))
 143                        hashcpy(last->peeled, sha1);
 144        }
 145        cached_refs->packed = list;
 146}
 147
 148static struct ref_list *get_packed_refs(void)
 149{
 150        if (!cached_refs.did_packed) {
 151                FILE *f = fopen(git_path("packed-refs"), "r");
 152                cached_refs.packed = NULL;
 153                if (f) {
 154                        read_packed_refs(f, &cached_refs);
 155                        fclose(f);
 156                }
 157                cached_refs.did_packed = 1;
 158        }
 159        return cached_refs.packed;
 160}
 161
 162static struct ref_list *get_ref_dir(const char *base, struct ref_list *list)
 163{
 164        DIR *dir = opendir(git_path("%s", base));
 165
 166        if (dir) {
 167                struct dirent *de;
 168                int baselen = strlen(base);
 169                char *ref = xmalloc(baselen + 257);
 170
 171                memcpy(ref, base, baselen);
 172                if (baselen && base[baselen-1] != '/')
 173                        ref[baselen++] = '/';
 174
 175                while ((de = readdir(dir)) != NULL) {
 176                        unsigned char sha1[20];
 177                        struct stat st;
 178                        int flag;
 179                        int namelen;
 180
 181                        if (de->d_name[0] == '.')
 182                                continue;
 183                        namelen = strlen(de->d_name);
 184                        if (namelen > 255)
 185                                continue;
 186                        if (has_extension(de->d_name, ".lock"))
 187                                continue;
 188                        memcpy(ref + baselen, de->d_name, namelen+1);
 189                        if (stat(git_path("%s", ref), &st) < 0)
 190                                continue;
 191                        if (S_ISDIR(st.st_mode)) {
 192                                list = get_ref_dir(ref, list);
 193                                continue;
 194                        }
 195                        if (!resolve_ref(ref, sha1, 1, &flag)) {
 196                                error("%s points nowhere!", ref);
 197                                continue;
 198                        }
 199                        list = add_ref(ref, sha1, flag, list, NULL);
 200                }
 201                free(ref);
 202                closedir(dir);
 203        }
 204        return list;
 205}
 206
 207static struct ref_list *get_loose_refs(void)
 208{
 209        if (!cached_refs.did_loose) {
 210                cached_refs.loose = get_ref_dir("refs", NULL);
 211                cached_refs.did_loose = 1;
 212        }
 213        return cached_refs.loose;
 214}
 215
 216/* We allow "recursive" symbolic refs. Only within reason, though */
 217#define MAXDEPTH 5
 218
 219const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
 220{
 221        int depth = MAXDEPTH, len;
 222        char buffer[256];
 223        static char ref_buffer[256];
 224
 225        if (flag)
 226                *flag = 0;
 227
 228        for (;;) {
 229                const char *path = git_path("%s", ref);
 230                struct stat st;
 231                char *buf;
 232                int fd;
 233
 234                if (--depth < 0)
 235                        return NULL;
 236
 237                /* Special case: non-existing file.
 238                 * Not having the refs/heads/new-branch is OK
 239                 * if we are writing into it, so is .git/HEAD
 240                 * that points at refs/heads/master still to be
 241                 * born.  It is NOT OK if we are resolving for
 242                 * reading.
 243                 */
 244                if (lstat(path, &st) < 0) {
 245                        struct ref_list *list = get_packed_refs();
 246                        while (list) {
 247                                if (!strcmp(ref, list->name)) {
 248                                        hashcpy(sha1, list->sha1);
 249                                        if (flag)
 250                                                *flag |= REF_ISPACKED;
 251                                        return ref;
 252                                }
 253                                list = list->next;
 254                        }
 255                        if (reading || errno != ENOENT)
 256                                return NULL;
 257                        hashclr(sha1);
 258                        return ref;
 259                }
 260
 261                /* Follow "normalized" - ie "refs/.." symlinks by hand */
 262                if (S_ISLNK(st.st_mode)) {
 263                        len = readlink(path, buffer, sizeof(buffer)-1);
 264                        if (len >= 5 && !memcmp("refs/", buffer, 5)) {
 265                                buffer[len] = 0;
 266                                strcpy(ref_buffer, buffer);
 267                                ref = ref_buffer;
 268                                if (flag)
 269                                        *flag |= REF_ISSYMREF;
 270                                continue;
 271                        }
 272                }
 273
 274                /* Is it a directory? */
 275                if (S_ISDIR(st.st_mode)) {
 276                        errno = EISDIR;
 277                        return NULL;
 278                }
 279
 280                /*
 281                 * Anything else, just open it and try to use it as
 282                 * a ref
 283                 */
 284                fd = open(path, O_RDONLY);
 285                if (fd < 0)
 286                        return NULL;
 287                len = read_in_full(fd, buffer, sizeof(buffer)-1);
 288                close(fd);
 289
 290                /*
 291                 * Is it a symbolic ref?
 292                 */
 293                if (len < 4 || memcmp("ref:", buffer, 4))
 294                        break;
 295                buf = buffer + 4;
 296                len -= 4;
 297                while (len && isspace(*buf))
 298                        buf++, len--;
 299                while (len && isspace(buf[len-1]))
 300                        len--;
 301                buf[len] = 0;
 302                memcpy(ref_buffer, buf, len + 1);
 303                ref = ref_buffer;
 304                if (flag)
 305                        *flag |= REF_ISSYMREF;
 306        }
 307        if (len < 40 || get_sha1_hex(buffer, sha1))
 308                return NULL;
 309        return ref;
 310}
 311
 312int read_ref(const char *ref, unsigned char *sha1)
 313{
 314        if (resolve_ref(ref, sha1, 1, NULL))
 315                return 0;
 316        return -1;
 317}
 318
 319static int do_one_ref(const char *base, each_ref_fn fn, int trim,
 320                      void *cb_data, struct ref_list *entry)
 321{
 322        if (strncmp(base, entry->name, trim))
 323                return 0;
 324        if (is_null_sha1(entry->sha1))
 325                return 0;
 326        if (!has_sha1_file(entry->sha1)) {
 327                error("%s does not point to a valid object!", entry->name);
 328                return 0;
 329        }
 330        return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
 331}
 332
 333int peel_ref(const char *ref, unsigned char *sha1)
 334{
 335        int flag;
 336        unsigned char base[20];
 337        struct object *o;
 338
 339        if (!resolve_ref(ref, base, 1, &flag))
 340                return -1;
 341
 342        if ((flag & REF_ISPACKED)) {
 343                struct ref_list *list = get_packed_refs();
 344
 345                while (list) {
 346                        if (!strcmp(list->name, ref)) {
 347                                if (list->flag & REF_KNOWS_PEELED) {
 348                                        hashcpy(sha1, list->peeled);
 349                                        return 0;
 350                                }
 351                                /* older pack-refs did not leave peeled ones */
 352                                break;
 353                        }
 354                        list = list->next;
 355                }
 356        }
 357
 358        /* fallback - callers should not call this for unpacked refs */
 359        o = parse_object(base);
 360        if (o->type == OBJ_TAG) {
 361                o = deref_tag(o, ref, 0);
 362                if (o) {
 363                        hashcpy(sha1, o->sha1);
 364                        return 0;
 365                }
 366        }
 367        return -1;
 368}
 369
 370static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
 371                           void *cb_data)
 372{
 373        int retval;
 374        struct ref_list *packed = get_packed_refs();
 375        struct ref_list *loose = get_loose_refs();
 376
 377        while (packed && loose) {
 378                struct ref_list *entry;
 379                int cmp = strcmp(packed->name, loose->name);
 380                if (!cmp) {
 381                        packed = packed->next;
 382                        continue;
 383                }
 384                if (cmp > 0) {
 385                        entry = loose;
 386                        loose = loose->next;
 387                } else {
 388                        entry = packed;
 389                        packed = packed->next;
 390                }
 391                retval = do_one_ref(base, fn, trim, cb_data, entry);
 392                if (retval)
 393                        return retval;
 394        }
 395
 396        for (packed = packed ? packed : loose; packed; packed = packed->next) {
 397                retval = do_one_ref(base, fn, trim, cb_data, packed);
 398                if (retval)
 399                        return retval;
 400        }
 401        return 0;
 402}
 403
 404int head_ref(each_ref_fn fn, void *cb_data)
 405{
 406        unsigned char sha1[20];
 407        int flag;
 408
 409        if (resolve_ref("HEAD", sha1, 1, &flag))
 410                return fn("HEAD", sha1, flag, cb_data);
 411        return 0;
 412}
 413
 414int for_each_ref(each_ref_fn fn, void *cb_data)
 415{
 416        return do_for_each_ref("refs/", fn, 0, cb_data);
 417}
 418
 419int for_each_tag_ref(each_ref_fn fn, void *cb_data)
 420{
 421        return do_for_each_ref("refs/tags/", fn, 10, cb_data);
 422}
 423
 424int for_each_branch_ref(each_ref_fn fn, void *cb_data)
 425{
 426        return do_for_each_ref("refs/heads/", fn, 11, cb_data);
 427}
 428
 429int for_each_remote_ref(each_ref_fn fn, void *cb_data)
 430{
 431        return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
 432}
 433
 434/* NEEDSWORK: This is only used by ssh-upload and it should go; the
 435 * caller should do resolve_ref or read_ref like everybody else.  Or
 436 * maybe everybody else should use get_ref_sha1() instead of doing
 437 * read_ref().
 438 */
 439int get_ref_sha1(const char *ref, unsigned char *sha1)
 440{
 441        if (check_ref_format(ref))
 442                return -1;
 443        return read_ref(mkpath("refs/%s", ref), sha1);
 444}
 445
 446/*
 447 * Make sure "ref" is something reasonable to have under ".git/refs/";
 448 * We do not like it if:
 449 *
 450 * - any path component of it begins with ".", or
 451 * - it has double dots "..", or
 452 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
 453 * - it ends with a "/".
 454 */
 455
 456static inline int bad_ref_char(int ch)
 457{
 458        return (((unsigned) ch) <= ' ' ||
 459                ch == '~' || ch == '^' || ch == ':' ||
 460                /* 2.13 Pattern Matching Notation */
 461                ch == '?' || ch == '*' || ch == '[');
 462}
 463
 464int check_ref_format(const char *ref)
 465{
 466        int ch, level;
 467        const char *cp = ref;
 468
 469        level = 0;
 470        while (1) {
 471                while ((ch = *cp++) == '/')
 472                        ; /* tolerate duplicated slashes */
 473                if (!ch)
 474                        return -1; /* should not end with slashes */
 475
 476                /* we are at the beginning of the path component */
 477                if (ch == '.' || bad_ref_char(ch))
 478                        return -1;
 479
 480                /* scan the rest of the path component */
 481                while ((ch = *cp++) != 0) {
 482                        if (bad_ref_char(ch))
 483                                return -1;
 484                        if (ch == '/')
 485                                break;
 486                        if (ch == '.' && *cp == '.')
 487                                return -1;
 488                }
 489                level++;
 490                if (!ch) {
 491                        if (level < 2)
 492                                return -2; /* at least of form "heads/blah" */
 493                        return 0;
 494                }
 495        }
 496}
 497
 498static struct ref_lock *verify_lock(struct ref_lock *lock,
 499        const unsigned char *old_sha1, int mustexist)
 500{
 501        if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
 502                error("Can't verify ref %s", lock->ref_name);
 503                unlock_ref(lock);
 504                return NULL;
 505        }
 506        if (hashcmp(lock->old_sha1, old_sha1)) {
 507                error("Ref %s is at %s but expected %s", lock->ref_name,
 508                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
 509                unlock_ref(lock);
 510                return NULL;
 511        }
 512        return lock;
 513}
 514
 515static int remove_empty_dir_recursive(char *path, int len)
 516{
 517        DIR *dir = opendir(path);
 518        struct dirent *e;
 519        int ret = 0;
 520
 521        if (!dir)
 522                return -1;
 523        if (path[len-1] != '/')
 524                path[len++] = '/';
 525        while ((e = readdir(dir)) != NULL) {
 526                struct stat st;
 527                int namlen;
 528                if ((e->d_name[0] == '.') &&
 529                    ((e->d_name[1] == 0) ||
 530                     ((e->d_name[1] == '.') && e->d_name[2] == 0)))
 531                        continue; /* "." and ".." */
 532
 533                namlen = strlen(e->d_name);
 534                if ((len + namlen < PATH_MAX) &&
 535                    strcpy(path + len, e->d_name) &&
 536                    !lstat(path, &st) &&
 537                    S_ISDIR(st.st_mode) &&
 538                    !remove_empty_dir_recursive(path, len + namlen))
 539                        continue; /* happy */
 540
 541                /* path too long, stat fails, or non-directory still exists */
 542                ret = -1;
 543                break;
 544        }
 545        closedir(dir);
 546        if (!ret) {
 547                path[len] = 0;
 548                ret = rmdir(path);
 549        }
 550        return ret;
 551}
 552
 553static int remove_empty_directories(char *file)
 554{
 555        /* we want to create a file but there is a directory there;
 556         * if that is an empty directory (or a directory that contains
 557         * only empty directories), remove them.
 558         */
 559        char path[PATH_MAX];
 560        int len = strlen(file);
 561
 562        if (len >= PATH_MAX) /* path too long ;-) */
 563                return -1;
 564        strcpy(path, file);
 565        return remove_empty_dir_recursive(path, len);
 566}
 567
 568static int is_refname_available(const char *ref, const char *oldref,
 569                                struct ref_list *list, int quiet)
 570{
 571        int namlen = strlen(ref); /* e.g. 'foo/bar' */
 572        while (list) {
 573                /* list->name could be 'foo' or 'foo/bar/baz' */
 574                if (!oldref || strcmp(oldref, list->name)) {
 575                        int len = strlen(list->name);
 576                        int cmplen = (namlen < len) ? namlen : len;
 577                        const char *lead = (namlen < len) ? list->name : ref;
 578                        if (!strncmp(ref, list->name, cmplen) &&
 579                            lead[cmplen] == '/') {
 580                                if (!quiet)
 581                                        error("'%s' exists; cannot create '%s'",
 582                                              list->name, ref);
 583                                return 0;
 584                        }
 585                }
 586                list = list->next;
 587        }
 588        return 1;
 589}
 590
 591static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int *flag)
 592{
 593        char *ref_file;
 594        const char *orig_ref = ref;
 595        struct ref_lock *lock;
 596        struct stat st;
 597        int last_errno = 0;
 598        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
 599
 600        lock = xcalloc(1, sizeof(struct ref_lock));
 601        lock->lock_fd = -1;
 602
 603        ref = resolve_ref(ref, lock->old_sha1, mustexist, flag);
 604        if (!ref && errno == EISDIR) {
 605                /* we are trying to lock foo but we used to
 606                 * have foo/bar which now does not exist;
 607                 * it is normal for the empty directory 'foo'
 608                 * to remain.
 609                 */
 610                ref_file = git_path("%s", orig_ref);
 611                if (remove_empty_directories(ref_file)) {
 612                        last_errno = errno;
 613                        error("there are still refs under '%s'", orig_ref);
 614                        goto error_return;
 615                }
 616                ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, flag);
 617        }
 618        if (!ref) {
 619                last_errno = errno;
 620                error("unable to resolve reference %s: %s",
 621                        orig_ref, strerror(errno));
 622                goto error_return;
 623        }
 624        /* When the ref did not exist and we are creating it,
 625         * make sure there is no existing ref that is packed
 626         * whose name begins with our refname, nor a ref whose
 627         * name is a proper prefix of our refname.
 628         */
 629        if (is_null_sha1(lock->old_sha1) &&
 630            !is_refname_available(ref, NULL, get_packed_refs(), 0))
 631                goto error_return;
 632
 633        lock->lk = xcalloc(1, sizeof(struct lock_file));
 634
 635        lock->ref_name = xstrdup(ref);
 636        lock->orig_ref_name = xstrdup(orig_ref);
 637        ref_file = git_path("%s", ref);
 638        lock->force_write = lstat(ref_file, &st) && errno == ENOENT;
 639
 640        if (safe_create_leading_directories(ref_file)) {
 641                last_errno = errno;
 642                error("unable to create directory for %s", ref_file);
 643                goto error_return;
 644        }
 645        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
 646
 647        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
 648
 649 error_return:
 650        unlock_ref(lock);
 651        errno = last_errno;
 652        return NULL;
 653}
 654
 655struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
 656{
 657        char refpath[PATH_MAX];
 658        if (check_ref_format(ref))
 659                return NULL;
 660        strcpy(refpath, mkpath("refs/%s", ref));
 661        return lock_ref_sha1_basic(refpath, old_sha1, NULL);
 662}
 663
 664struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1)
 665{
 666        if (check_ref_format(ref) == -1)
 667                return NULL;
 668        return lock_ref_sha1_basic(ref, old_sha1, NULL);
 669}
 670
 671static struct lock_file packlock;
 672
 673static int repack_without_ref(const char *refname)
 674{
 675        struct ref_list *list, *packed_ref_list;
 676        int fd;
 677        int found = 0;
 678
 679        packed_ref_list = get_packed_refs();
 680        for (list = packed_ref_list; list; list = list->next) {
 681                if (!strcmp(refname, list->name)) {
 682                        found = 1;
 683                        break;
 684                }
 685        }
 686        if (!found)
 687                return 0;
 688        fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
 689        if (fd < 0)
 690                return error("cannot delete '%s' from packed refs", refname);
 691
 692        for (list = packed_ref_list; list; list = list->next) {
 693                char line[PATH_MAX + 100];
 694                int len;
 695
 696                if (!strcmp(refname, list->name))
 697                        continue;
 698                len = snprintf(line, sizeof(line), "%s %s\n",
 699                               sha1_to_hex(list->sha1), list->name);
 700                /* this should not happen but just being defensive */
 701                if (len > sizeof(line))
 702                        die("too long a refname '%s'", list->name);
 703                write_or_die(fd, line, len);
 704        }
 705        return commit_lock_file(&packlock);
 706}
 707
 708int delete_ref(const char *refname, unsigned char *sha1)
 709{
 710        struct ref_lock *lock;
 711        int err, i, ret = 0, flag = 0;
 712
 713        lock = lock_ref_sha1_basic(refname, sha1, &flag);
 714        if (!lock)
 715                return 1;
 716        if (!(flag & REF_ISPACKED)) {
 717                /* loose */
 718                i = strlen(lock->lk->filename) - 5; /* .lock */
 719                lock->lk->filename[i] = 0;
 720                err = unlink(lock->lk->filename);
 721                if (err) {
 722                        ret = 1;
 723                        error("unlink(%s) failed: %s",
 724                              lock->lk->filename, strerror(errno));
 725                }
 726                lock->lk->filename[i] = '.';
 727        }
 728        /* removing the loose one could have resurrected an earlier
 729         * packed one.  Also, if it was not loose we need to repack
 730         * without it.
 731         */
 732        ret |= repack_without_ref(refname);
 733
 734        err = unlink(git_path("logs/%s", lock->ref_name));
 735        if (err && errno != ENOENT)
 736                fprintf(stderr, "warning: unlink(%s) failed: %s",
 737                        git_path("logs/%s", lock->ref_name), strerror(errno));
 738        invalidate_cached_refs();
 739        unlock_ref(lock);
 740        return ret;
 741}
 742
 743int rename_ref(const char *oldref, const char *newref, const char *logmsg)
 744{
 745        static const char renamed_ref[] = "RENAMED-REF";
 746        unsigned char sha1[20], orig_sha1[20];
 747        int flag = 0, logmoved = 0;
 748        struct ref_lock *lock;
 749        struct stat loginfo;
 750        int log = !lstat(git_path("logs/%s", oldref), &loginfo);
 751
 752        if (S_ISLNK(loginfo.st_mode))
 753                return error("reflog for %s is a symlink", oldref);
 754
 755        if (!resolve_ref(oldref, orig_sha1, 1, &flag))
 756                return error("refname %s not found", oldref);
 757
 758        if (!is_refname_available(newref, oldref, get_packed_refs(), 0))
 759                return 1;
 760
 761        if (!is_refname_available(newref, oldref, get_loose_refs(), 0))
 762                return 1;
 763
 764        lock = lock_ref_sha1_basic(renamed_ref, NULL, NULL);
 765        if (!lock)
 766                return error("unable to lock %s", renamed_ref);
 767        lock->force_write = 1;
 768        if (write_ref_sha1(lock, orig_sha1, logmsg))
 769                return error("unable to save current sha1 in %s", renamed_ref);
 770
 771        if (log && rename(git_path("logs/%s", oldref), git_path("tmp-renamed-log")))
 772                return error("unable to move logfile logs/%s to tmp-renamed-log: %s",
 773                        oldref, strerror(errno));
 774
 775        if (delete_ref(oldref, orig_sha1)) {
 776                error("unable to delete old %s", oldref);
 777                goto rollback;
 778        }
 779
 780        if (resolve_ref(newref, sha1, 1, &flag) && delete_ref(newref, sha1)) {
 781                if (errno==EISDIR) {
 782                        if (remove_empty_directories(git_path("%s", newref))) {
 783                                error("Directory not empty: %s", newref);
 784                                goto rollback;
 785                        }
 786                } else {
 787                        error("unable to delete existing %s", newref);
 788                        goto rollback;
 789                }
 790        }
 791
 792        if (log && safe_create_leading_directories(git_path("logs/%s", newref))) {
 793                error("unable to create directory for %s", newref);
 794                goto rollback;
 795        }
 796
 797 retry:
 798        if (log && rename(git_path("tmp-renamed-log"), git_path("logs/%s", newref))) {
 799                if (errno==EISDIR || errno==ENOTDIR) {
 800                        /*
 801                         * rename(a, b) when b is an existing
 802                         * directory ought to result in ISDIR, but
 803                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
 804                         */
 805                        if (remove_empty_directories(git_path("logs/%s", newref))) {
 806                                error("Directory not empty: logs/%s", newref);
 807                                goto rollback;
 808                        }
 809                        goto retry;
 810                } else {
 811                        error("unable to move logfile tmp-renamed-log to logs/%s: %s",
 812                                newref, strerror(errno));
 813                        goto rollback;
 814                }
 815        }
 816        logmoved = log;
 817
 818        lock = lock_ref_sha1_basic(newref, NULL, NULL);
 819        if (!lock) {
 820                error("unable to lock %s for update", newref);
 821                goto rollback;
 822        }
 823
 824        lock->force_write = 1;
 825        hashcpy(lock->old_sha1, orig_sha1);
 826        if (write_ref_sha1(lock, orig_sha1, logmsg)) {
 827                error("unable to write current sha1 into %s", newref);
 828                goto rollback;
 829        }
 830
 831        if (!prefixcmp(oldref, "refs/heads/") &&
 832                        !prefixcmp(newref, "refs/heads/")) {
 833                char oldsection[1024], newsection[1024];
 834
 835                snprintf(oldsection, 1024, "branch.%s", oldref + 11);
 836                snprintf(newsection, 1024, "branch.%s", newref + 11);
 837                if (git_config_rename_section(oldsection, newsection) < 0)
 838                        return 1;
 839        }
 840
 841        return 0;
 842
 843 rollback:
 844        lock = lock_ref_sha1_basic(oldref, NULL, NULL);
 845        if (!lock) {
 846                error("unable to lock %s for rollback", oldref);
 847                goto rollbacklog;
 848        }
 849
 850        lock->force_write = 1;
 851        flag = log_all_ref_updates;
 852        log_all_ref_updates = 0;
 853        if (write_ref_sha1(lock, orig_sha1, NULL))
 854                error("unable to write current sha1 into %s", oldref);
 855        log_all_ref_updates = flag;
 856
 857 rollbacklog:
 858        if (logmoved && rename(git_path("logs/%s", newref), git_path("logs/%s", oldref)))
 859                error("unable to restore logfile %s from %s: %s",
 860                        oldref, newref, strerror(errno));
 861        if (!logmoved && log &&
 862            rename(git_path("tmp-renamed-log"), git_path("logs/%s", oldref)))
 863                error("unable to restore logfile %s from tmp-renamed-log: %s",
 864                        oldref, strerror(errno));
 865
 866        return 1;
 867}
 868
 869void unlock_ref(struct ref_lock *lock)
 870{
 871        if (lock->lock_fd >= 0) {
 872                close(lock->lock_fd);
 873                /* Do not free lock->lk -- atexit() still looks at them */
 874                if (lock->lk)
 875                        rollback_lock_file(lock->lk);
 876        }
 877        free(lock->ref_name);
 878        free(lock->orig_ref_name);
 879        free(lock);
 880}
 881
 882static int log_ref_write(const char *ref_name, const unsigned char *old_sha1,
 883                         const unsigned char *new_sha1, const char *msg)
 884{
 885        int logfd, written, oflags = O_APPEND | O_WRONLY;
 886        unsigned maxlen, len;
 887        int msglen;
 888        char *log_file, *logrec;
 889        const char *committer;
 890
 891        if (log_all_ref_updates < 0)
 892                log_all_ref_updates = !is_bare_repository();
 893
 894        log_file = git_path("logs/%s", ref_name);
 895
 896        if (log_all_ref_updates &&
 897            (!prefixcmp(ref_name, "refs/heads/") ||
 898             !prefixcmp(ref_name, "refs/remotes/") ||
 899             !strcmp(ref_name, "HEAD"))) {
 900                if (safe_create_leading_directories(log_file) < 0)
 901                        return error("unable to create directory for %s",
 902                                     log_file);
 903                oflags |= O_CREAT;
 904        }
 905
 906        logfd = open(log_file, oflags, 0666);
 907        if (logfd < 0) {
 908                if (!(oflags & O_CREAT) && errno == ENOENT)
 909                        return 0;
 910
 911                if ((oflags & O_CREAT) && errno == EISDIR) {
 912                        if (remove_empty_directories(log_file)) {
 913                                return error("There are still logs under '%s'",
 914                                             log_file);
 915                        }
 916                        logfd = open(log_file, oflags, 0666);
 917                }
 918
 919                if (logfd < 0)
 920                        return error("Unable to append to %s: %s",
 921                                     log_file, strerror(errno));
 922        }
 923
 924        adjust_shared_perm(log_file);
 925
 926        msglen = 0;
 927        if (msg) {
 928                /* clean up the message and make sure it is a single line */
 929                for ( ; *msg; msg++)
 930                        if (!isspace(*msg))
 931                                break;
 932                if (*msg) {
 933                        const char *ep = strchr(msg, '\n');
 934                        if (ep)
 935                                msglen = ep - msg;
 936                        else
 937                                msglen = strlen(msg);
 938                }
 939        }
 940
 941        committer = git_committer_info(-1);
 942        maxlen = strlen(committer) + msglen + 100;
 943        logrec = xmalloc(maxlen);
 944        len = sprintf(logrec, "%s %s %s\n",
 945                      sha1_to_hex(old_sha1),
 946                      sha1_to_hex(new_sha1),
 947                      committer);
 948        if (msglen)
 949                len += sprintf(logrec + len - 1, "\t%.*s\n", msglen, msg) - 1;
 950        written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
 951        free(logrec);
 952        close(logfd);
 953        if (written != len)
 954                return error("Unable to append to %s", log_file);
 955        return 0;
 956}
 957
 958int write_ref_sha1(struct ref_lock *lock,
 959        const unsigned char *sha1, const char *logmsg)
 960{
 961        static char term = '\n';
 962
 963        if (!lock)
 964                return -1;
 965        if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
 966                unlock_ref(lock);
 967                return 0;
 968        }
 969        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
 970            write_in_full(lock->lock_fd, &term, 1) != 1
 971                || close(lock->lock_fd) < 0) {
 972                error("Couldn't write %s", lock->lk->filename);
 973                unlock_ref(lock);
 974                return -1;
 975        }
 976        invalidate_cached_refs();
 977        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
 978            (strcmp(lock->ref_name, lock->orig_ref_name) &&
 979             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
 980                unlock_ref(lock);
 981                return -1;
 982        }
 983        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
 984                /*
 985                 * Special hack: If a branch is updated directly and HEAD
 986                 * points to it (may happen on the remote side of a push
 987                 * for example) then logically the HEAD reflog should be
 988                 * updated too.
 989                 * A generic solution implies reverse symref information,
 990                 * but finding all symrefs pointing to the given branch
 991                 * would be rather costly for this rare event (the direct
 992                 * update of a branch) to be worth it.  So let's cheat and
 993                 * check with HEAD only which should cover 99% of all usage
 994                 * scenarios (even 100% of the default ones).
 995                 */
 996                unsigned char head_sha1[20];
 997                int head_flag;
 998                const char *head_ref;
 999                head_ref = resolve_ref("HEAD", head_sha1, 1, &head_flag);
1000                if (head_ref && (head_flag & REF_ISSYMREF) &&
1001                    !strcmp(head_ref, lock->ref_name))
1002                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
1003        }
1004        if (commit_lock_file(lock->lk)) {
1005                error("Couldn't set %s", lock->ref_name);
1006                unlock_ref(lock);
1007                return -1;
1008        }
1009        lock->lock_fd = -1;
1010        unlock_ref(lock);
1011        return 0;
1012}
1013
1014int create_symref(const char *ref_target, const char *refs_heads_master,
1015                  const char *logmsg)
1016{
1017        const char *lockpath;
1018        char ref[1000];
1019        int fd, len, written;
1020        char *git_HEAD = xstrdup(git_path("%s", ref_target));
1021        unsigned char old_sha1[20], new_sha1[20];
1022
1023        if (logmsg && read_ref(ref_target, old_sha1))
1024                hashclr(old_sha1);
1025
1026        if (safe_create_leading_directories(git_HEAD) < 0)
1027                return error("unable to create directory for %s", git_HEAD);
1028
1029#ifndef NO_SYMLINK_HEAD
1030        if (prefer_symlink_refs) {
1031                unlink(git_HEAD);
1032                if (!symlink(refs_heads_master, git_HEAD))
1033                        goto done;
1034                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1035        }
1036#endif
1037
1038        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1039        if (sizeof(ref) <= len) {
1040                error("refname too long: %s", refs_heads_master);
1041                goto error_free_return;
1042        }
1043        lockpath = mkpath("%s.lock", git_HEAD);
1044        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1045        if (fd < 0) {
1046                error("Unable to open %s for writing", lockpath);
1047                goto error_free_return;
1048        }
1049        written = write_in_full(fd, ref, len);
1050        close(fd);
1051        if (written != len) {
1052                error("Unable to write to %s", lockpath);
1053                goto error_unlink_return;
1054        }
1055        if (rename(lockpath, git_HEAD) < 0) {
1056                error("Unable to create %s", git_HEAD);
1057                goto error_unlink_return;
1058        }
1059        if (adjust_shared_perm(git_HEAD)) {
1060                error("Unable to fix permissions on %s", lockpath);
1061        error_unlink_return:
1062                unlink(lockpath);
1063        error_free_return:
1064                free(git_HEAD);
1065                return -1;
1066        }
1067
1068#ifndef NO_SYMLINK_HEAD
1069        done:
1070#endif
1071        if (logmsg && !read_ref(refs_heads_master, new_sha1))
1072                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1073
1074        free(git_HEAD);
1075        return 0;
1076}
1077
1078static char *ref_msg(const char *line, const char *endp)
1079{
1080        const char *ep;
1081        char *msg;
1082
1083        line += 82;
1084        for (ep = line; ep < endp && *ep != '\n'; ep++)
1085                ;
1086        msg = xmalloc(ep - line + 1);
1087        memcpy(msg, line, ep - line);
1088        msg[ep - line] = 0;
1089        return msg;
1090}
1091
1092int read_ref_at(const char *ref, unsigned long at_time, int cnt, unsigned char *sha1, char **msg, unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1093{
1094        const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1095        char *tz_c;
1096        int logfd, tz, reccnt = 0;
1097        struct stat st;
1098        unsigned long date;
1099        unsigned char logged_sha1[20];
1100        void *log_mapped;
1101        size_t mapsz;
1102
1103        logfile = git_path("logs/%s", ref);
1104        logfd = open(logfile, O_RDONLY, 0);
1105        if (logfd < 0)
1106                die("Unable to read log %s: %s", logfile, strerror(errno));
1107        fstat(logfd, &st);
1108        if (!st.st_size)
1109                die("Log %s is empty.", logfile);
1110        mapsz = xsize_t(st.st_size);
1111        log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
1112        logdata = log_mapped;
1113        close(logfd);
1114
1115        lastrec = NULL;
1116        rec = logend = logdata + st.st_size;
1117        while (logdata < rec) {
1118                reccnt++;
1119                if (logdata < rec && *(rec-1) == '\n')
1120                        rec--;
1121                lastgt = NULL;
1122                while (logdata < rec && *(rec-1) != '\n') {
1123                        rec--;
1124                        if (*rec == '>')
1125                                lastgt = rec;
1126                }
1127                if (!lastgt)
1128                        die("Log %s is corrupt.", logfile);
1129                date = strtoul(lastgt + 1, &tz_c, 10);
1130                if (date <= at_time || cnt == 0) {
1131                        tz = strtoul(tz_c, NULL, 10);
1132                        if (msg)
1133                                *msg = ref_msg(rec, logend);
1134                        if (cutoff_time)
1135                                *cutoff_time = date;
1136                        if (cutoff_tz)
1137                                *cutoff_tz = tz;
1138                        if (cutoff_cnt)
1139                                *cutoff_cnt = reccnt - 1;
1140                        if (lastrec) {
1141                                if (get_sha1_hex(lastrec, logged_sha1))
1142                                        die("Log %s is corrupt.", logfile);
1143                                if (get_sha1_hex(rec + 41, sha1))
1144                                        die("Log %s is corrupt.", logfile);
1145                                if (hashcmp(logged_sha1, sha1)) {
1146                                        fprintf(stderr,
1147                                                "warning: Log %s has gap after %s.\n",
1148                                                logfile, show_rfc2822_date(date, tz));
1149                                }
1150                        }
1151                        else if (date == at_time) {
1152                                if (get_sha1_hex(rec + 41, sha1))
1153                                        die("Log %s is corrupt.", logfile);
1154                        }
1155                        else {
1156                                if (get_sha1_hex(rec + 41, logged_sha1))
1157                                        die("Log %s is corrupt.", logfile);
1158                                if (hashcmp(logged_sha1, sha1)) {
1159                                        fprintf(stderr,
1160                                                "warning: Log %s unexpectedly ended on %s.\n",
1161                                                logfile, show_rfc2822_date(date, tz));
1162                                }
1163                        }
1164                        munmap(log_mapped, mapsz);
1165                        return 0;
1166                }
1167                lastrec = rec;
1168                if (cnt > 0)
1169                        cnt--;
1170        }
1171
1172        rec = logdata;
1173        while (rec < logend && *rec != '>' && *rec != '\n')
1174                rec++;
1175        if (rec == logend || *rec == '\n')
1176                die("Log %s is corrupt.", logfile);
1177        date = strtoul(rec + 1, &tz_c, 10);
1178        tz = strtoul(tz_c, NULL, 10);
1179        if (get_sha1_hex(logdata, sha1))
1180                die("Log %s is corrupt.", logfile);
1181        if (msg)
1182                *msg = ref_msg(logdata, logend);
1183        munmap(log_mapped, mapsz);
1184
1185        if (cutoff_time)
1186                *cutoff_time = date;
1187        if (cutoff_tz)
1188                *cutoff_tz = tz;
1189        if (cutoff_cnt)
1190                *cutoff_cnt = reccnt;
1191        return 1;
1192}
1193
1194int for_each_reflog_ent(const char *ref, each_reflog_ent_fn fn, void *cb_data)
1195{
1196        const char *logfile;
1197        FILE *logfp;
1198        char buf[1024];
1199        int ret = 0;
1200
1201        logfile = git_path("logs/%s", ref);
1202        logfp = fopen(logfile, "r");
1203        if (!logfp)
1204                return -1;
1205        while (fgets(buf, sizeof(buf), logfp)) {
1206                unsigned char osha1[20], nsha1[20];
1207                char *email_end, *message;
1208                unsigned long timestamp;
1209                int len, tz;
1210
1211                /* old SP new SP name <email> SP time TAB msg LF */
1212                len = strlen(buf);
1213                if (len < 83 || buf[len-1] != '\n' ||
1214                    get_sha1_hex(buf, osha1) || buf[40] != ' ' ||
1215                    get_sha1_hex(buf + 41, nsha1) || buf[81] != ' ' ||
1216                    !(email_end = strchr(buf + 82, '>')) ||
1217                    email_end[1] != ' ' ||
1218                    !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1219                    !message || message[0] != ' ' ||
1220                    (message[1] != '+' && message[1] != '-') ||
1221                    !isdigit(message[2]) || !isdigit(message[3]) ||
1222                    !isdigit(message[4]) || !isdigit(message[5]))
1223                        continue; /* corrupt? */
1224                email_end[1] = '\0';
1225                tz = strtol(message + 1, NULL, 10);
1226                if (message[6] != '\t')
1227                        message += 6;
1228                else
1229                        message += 7;
1230                ret = fn(osha1, nsha1, buf+82, timestamp, tz, message, cb_data);
1231                if (ret)
1232                        break;
1233        }
1234        fclose(logfp);
1235        return ret;
1236}
1237
1238static int do_for_each_reflog(const char *base, each_ref_fn fn, void *cb_data)
1239{
1240        DIR *dir = opendir(git_path("logs/%s", base));
1241        int retval = 0;
1242
1243        if (dir) {
1244                struct dirent *de;
1245                int baselen = strlen(base);
1246                char *log = xmalloc(baselen + 257);
1247
1248                memcpy(log, base, baselen);
1249                if (baselen && base[baselen-1] != '/')
1250                        log[baselen++] = '/';
1251
1252                while ((de = readdir(dir)) != NULL) {
1253                        struct stat st;
1254                        int namelen;
1255
1256                        if (de->d_name[0] == '.')
1257                                continue;
1258                        namelen = strlen(de->d_name);
1259                        if (namelen > 255)
1260                                continue;
1261                        if (has_extension(de->d_name, ".lock"))
1262                                continue;
1263                        memcpy(log + baselen, de->d_name, namelen+1);
1264                        if (stat(git_path("logs/%s", log), &st) < 0)
1265                                continue;
1266                        if (S_ISDIR(st.st_mode)) {
1267                                retval = do_for_each_reflog(log, fn, cb_data);
1268                        } else {
1269                                unsigned char sha1[20];
1270                                if (!resolve_ref(log, sha1, 0, NULL))
1271                                        retval = error("bad ref for %s", log);
1272                                else
1273                                        retval = fn(log, sha1, 0, cb_data);
1274                        }
1275                        if (retval)
1276                                break;
1277                }
1278                free(log);
1279                closedir(dir);
1280        }
1281        else if (*base)
1282                return errno;
1283        return retval;
1284}
1285
1286int for_each_reflog(each_ref_fn fn, void *cb_data)
1287{
1288        return do_for_each_reflog("", fn, cb_data);
1289}