85c8648c51ebff7f47da1763e77ad1cddac32a4e
   1/*
   2 * Copyright (c) 2005, Junio C Hamano
   3 */
   4#include "cache.h"
   5#include "sigchain.h"
   6
   7/*
   8 * File write-locks as used by Git.
   9 *
  10 * For an overview of how to use the lockfile API, please see
  11 *
  12 *     Documentation/technical/api-lockfile.txt
  13 *
  14 * This module keeps track of all locked files in lock_file_list for
  15 * use at cleanup. This list and the lock_file objects that comprise
  16 * it must be kept in self-consistent states at all time, because the
  17 * program can be interrupted any time by a signal, in which case the
  18 * signal handler will walk through the list attempting to clean up
  19 * any open lock files.
  20 *
  21 * A lockfile is owned by the process that created it. The lock_file
  22 * object has an "owner" field that records its owner. This field is
  23 * used to prevent a forked process from closing a lockfile created by
  24 * its parent.
  25 *
  26 * The possible states of a lock_file object are as follows:
  27 *
  28 * - Uninitialized.  In this state the object's on_list field must be
  29 *   zero but the rest of its contents need not be initialized.  As
  30 *   soon as the object is used in any way, it is irrevocably
  31 *   registered in the lock_file_list, and on_list is set.
  32 *
  33 * - Locked, lockfile open (after hold_lock_file_for_update(),
  34 *   hold_lock_file_for_append(), or reopen_lock_file()). In this
  35 *   state:
  36 *   - the lockfile exists
  37 *   - active is set
  38 *   - filename holds the filename of the lockfile
  39 *   - fd holds a file descriptor open for writing to the lockfile
  40 *   - owner holds the PID of the process that locked the file
  41 *
  42 * - Locked, lockfile closed (after successful close_lock_file()).
  43 *   Same as the previous state, except that the lockfile is closed
  44 *   and fd is -1.
  45 *
  46 * - Unlocked (after commit_lock_file(), rollback_lock_file(), a
  47 *   failed attempt to lock, or a failed close_lock_file()).  In this
  48 *   state:
  49 *   - active is unset
  50 *   - filename is empty (usually, though there are transitory
  51 *     states in which this condition doesn't hold). Client code should
  52 *     *not* rely on the filename being empty in this state.
  53 *   - fd is -1
  54 *   - the object is left registered in the lock_file_list, and
  55 *     on_list is set.
  56 */
  57
  58static struct lock_file *volatile lock_file_list;
  59
  60static void remove_lock_file(void)
  61{
  62        pid_t me = getpid();
  63
  64        while (lock_file_list) {
  65                if (lock_file_list->owner == me)
  66                        rollback_lock_file(lock_file_list);
  67                lock_file_list = lock_file_list->next;
  68        }
  69}
  70
  71static void remove_lock_file_on_signal(int signo)
  72{
  73        remove_lock_file();
  74        sigchain_pop(signo);
  75        raise(signo);
  76}
  77
  78/*
  79 * p = absolute or relative path name
  80 *
  81 * Return a pointer into p showing the beginning of the last path name
  82 * element.  If p is empty or the root directory ("/"), just return p.
  83 */
  84static char *last_path_elm(char *p)
  85{
  86        /* r starts pointing to null at the end of the string */
  87        char *r = strchr(p, '\0');
  88
  89        if (r == p)
  90                return p; /* just return empty string */
  91
  92        r--; /* back up to last non-null character */
  93
  94        /* back up past trailing slashes, if any */
  95        while (r > p && *r == '/')
  96                r--;
  97
  98        /*
  99         * then go backwards until I hit a slash, or the beginning of
 100         * the string
 101         */
 102        while (r > p && *(r-1) != '/')
 103                r--;
 104        return r;
 105}
 106
 107
 108/* We allow "recursive" symbolic links. Only within reason, though */
 109#define MAXDEPTH 5
 110
 111/*
 112 * p = path that may be a symlink
 113 * s = full size of p
 114 *
 115 * If p is a symlink, attempt to overwrite p with a path to the real
 116 * file or directory (which may or may not exist), following a chain of
 117 * symlinks if necessary.  Otherwise, leave p unmodified.
 118 *
 119 * This is a best-effort routine.  If an error occurs, p will either be
 120 * left unmodified or will name a different symlink in a symlink chain
 121 * that started with p's initial contents.
 122 *
 123 * Always returns p.
 124 */
 125
 126static char *resolve_symlink(char *p, size_t s)
 127{
 128        int depth = MAXDEPTH;
 129
 130        while (depth--) {
 131                char link[PATH_MAX];
 132                int link_len = readlink(p, link, sizeof(link));
 133                if (link_len < 0) {
 134                        /* not a symlink anymore */
 135                        return p;
 136                }
 137                else if (link_len < sizeof(link))
 138                        /* readlink() never null-terminates */
 139                        link[link_len] = '\0';
 140                else {
 141                        warning("%s: symlink too long", p);
 142                        return p;
 143                }
 144
 145                if (is_absolute_path(link)) {
 146                        /* absolute path simply replaces p */
 147                        if (link_len < s)
 148                                strcpy(p, link);
 149                        else {
 150                                warning("%s: symlink too long", p);
 151                                return p;
 152                        }
 153                } else {
 154                        /*
 155                         * link is a relative path, so I must replace the
 156                         * last element of p with it.
 157                         */
 158                        char *r = (char *)last_path_elm(p);
 159                        if (r - p + link_len < s)
 160                                strcpy(r, link);
 161                        else {
 162                                warning("%s: symlink too long", p);
 163                                return p;
 164                        }
 165                }
 166        }
 167        return p;
 168}
 169
 170/* Make sure errno contains a meaningful value on error */
 171static int lock_file(struct lock_file *lk, const char *path, int flags)
 172{
 173        if (!lock_file_list) {
 174                /* One-time initialization */
 175                sigchain_push_common(remove_lock_file_on_signal);
 176                atexit(remove_lock_file);
 177        }
 178
 179        if (lk->active)
 180                die("BUG: cannot lock_file(\"%s\") using active struct lock_file",
 181                    path);
 182        if (!lk->on_list) {
 183                /* Initialize *lk and add it to lock_file_list: */
 184                lk->fd = -1;
 185                lk->active = 0;
 186                lk->owner = 0;
 187                strbuf_init(&lk->filename, PATH_MAX);
 188                lk->next = lock_file_list;
 189                lock_file_list = lk;
 190                lk->on_list = 1;
 191        } else if (lk->filename.len) {
 192                /* This shouldn't happen, but better safe than sorry. */
 193                die("BUG: lock_file(\"%s\") called with improperly-reset lock_file object",
 194                    path);
 195        }
 196
 197        strbuf_addstr(&lk->filename, path);
 198        if (!(flags & LOCK_NODEREF)) {
 199                resolve_symlink(lk->filename.buf, lk->filename.alloc);
 200                strbuf_setlen(&lk->filename, strlen(lk->filename.buf));
 201        }
 202        strbuf_addstr(&lk->filename, LOCK_SUFFIX);
 203        lk->fd = open(lk->filename.buf, O_RDWR | O_CREAT | O_EXCL, 0666);
 204        if (lk->fd < 0) {
 205                strbuf_reset(&lk->filename);
 206                return -1;
 207        }
 208        lk->owner = getpid();
 209        lk->active = 1;
 210        if (adjust_shared_perm(lk->filename.buf)) {
 211                int save_errno = errno;
 212                error("cannot fix permission bits on %s", lk->filename.buf);
 213                rollback_lock_file(lk);
 214                errno = save_errno;
 215                return -1;
 216        }
 217        return lk->fd;
 218}
 219
 220void unable_to_lock_message(const char *path, int err, struct strbuf *buf)
 221{
 222        if (err == EEXIST) {
 223                strbuf_addf(buf, "Unable to create '%s.lock': %s.\n\n"
 224                    "If no other git process is currently running, this probably means a\n"
 225                    "git process crashed in this repository earlier. Make sure no other git\n"
 226                    "process is running and remove the file manually to continue.",
 227                            absolute_path(path), strerror(err));
 228        } else
 229                strbuf_addf(buf, "Unable to create '%s.lock': %s",
 230                            absolute_path(path), strerror(err));
 231}
 232
 233int unable_to_lock_error(const char *path, int err)
 234{
 235        struct strbuf buf = STRBUF_INIT;
 236
 237        unable_to_lock_message(path, err, &buf);
 238        error("%s", buf.buf);
 239        strbuf_release(&buf);
 240        return -1;
 241}
 242
 243NORETURN void unable_to_lock_die(const char *path, int err)
 244{
 245        struct strbuf buf = STRBUF_INIT;
 246
 247        unable_to_lock_message(path, err, &buf);
 248        die("%s", buf.buf);
 249}
 250
 251/* This should return a meaningful errno on failure */
 252int hold_lock_file_for_update(struct lock_file *lk, const char *path, int flags)
 253{
 254        int fd = lock_file(lk, path, flags);
 255        if (fd < 0 && (flags & LOCK_DIE_ON_ERROR))
 256                unable_to_lock_die(path, errno);
 257        return fd;
 258}
 259
 260int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
 261{
 262        int fd, orig_fd;
 263
 264        fd = lock_file(lk, path, flags);
 265        if (fd < 0) {
 266                if (flags & LOCK_DIE_ON_ERROR)
 267                        unable_to_lock_die(path, errno);
 268                return fd;
 269        }
 270
 271        orig_fd = open(path, O_RDONLY);
 272        if (orig_fd < 0) {
 273                if (errno != ENOENT) {
 274                        if (flags & LOCK_DIE_ON_ERROR)
 275                                die("cannot open '%s' for copying", path);
 276                        rollback_lock_file(lk);
 277                        return error("cannot open '%s' for copying", path);
 278                }
 279        } else if (copy_fd(orig_fd, fd)) {
 280                if (flags & LOCK_DIE_ON_ERROR)
 281                        exit(128);
 282                rollback_lock_file(lk);
 283                return -1;
 284        }
 285        return fd;
 286}
 287
 288int close_lock_file(struct lock_file *lk)
 289{
 290        int fd = lk->fd;
 291
 292        if (fd < 0)
 293                return 0;
 294
 295        lk->fd = -1;
 296        if (close(fd)) {
 297                int save_errno = errno;
 298                rollback_lock_file(lk);
 299                errno = save_errno;
 300                return -1;
 301        }
 302        return 0;
 303}
 304
 305int reopen_lock_file(struct lock_file *lk)
 306{
 307        if (0 <= lk->fd)
 308                die(_("BUG: reopen a lockfile that is still open"));
 309        if (!lk->active)
 310                die(_("BUG: reopen a lockfile that has been committed"));
 311        lk->fd = open(lk->filename.buf, O_WRONLY);
 312        return lk->fd;
 313}
 314
 315int commit_lock_file(struct lock_file *lk)
 316{
 317        static struct strbuf result_file = STRBUF_INIT;
 318        int err;
 319
 320        if (!lk->active)
 321                die("BUG: attempt to commit unlocked object");
 322
 323        if (close_lock_file(lk))
 324                return -1;
 325
 326        /* remove ".lock": */
 327        strbuf_add(&result_file, lk->filename.buf,
 328                   lk->filename.len - LOCK_SUFFIX_LEN);
 329        err = rename(lk->filename.buf, result_file.buf);
 330        strbuf_reset(&result_file);
 331        if (err) {
 332                int save_errno = errno;
 333                rollback_lock_file(lk);
 334                errno = save_errno;
 335                return -1;
 336        }
 337
 338        lk->active = 0;
 339        strbuf_reset(&lk->filename);
 340        return 0;
 341}
 342
 343int hold_locked_index(struct lock_file *lk, int die_on_error)
 344{
 345        return hold_lock_file_for_update(lk, get_index_file(),
 346                                         die_on_error
 347                                         ? LOCK_DIE_ON_ERROR
 348                                         : 0);
 349}
 350
 351void rollback_lock_file(struct lock_file *lk)
 352{
 353        if (!lk->active)
 354                return;
 355
 356        if (!close_lock_file(lk)) {
 357                unlink_or_warn(lk->filename.buf);
 358                lk->active = 0;
 359                strbuf_reset(&lk->filename);
 360        }
 361}